"use client";

import { DropdownMenuTrigger } from "@radix-ui/react-dropdown-menu";
import { Table } from "@tanstack/react-table";
import { RefreshCw, RotateCcw, Settings2 } from "lucide-react";
import { useTranslation } from "react-i18next";

import { Button } from "@/shared/common/ui/button";
import {
  DropdownMenu,
  DropdownMenuCheckboxItem,
  DropdownMenuContent,
  DropdownMenuLabel,
  DropdownMenuSeparator,
} from "@/shared/common/ui/dropdown-menu";
import { useState } from "react";
import { getColumnToggleLabel } from "./getColumnToggleLabel";

interface DataTableViewOptionsProps<TData> {
  table: Table<TData>;
  refreshTable?: () => void;
}
export function DataTableViewOptions<TData>({
  table,
  refreshTable,
}: DataTableViewOptionsProps<TData>) {
  const [refreshing, setRefreshing] = useState(false);
  const handleRefresh = async () => {
    if (refreshTable) {
      try {
        setRefreshing(true);
        await refreshTable(); // your actual refresh logic
      } finally {
        setRefreshing(false);
      }
    }
  };
  const { t } = useTranslation();
  return (
    <div className="flex flex-wrap justify-end gap-2 sm:gap-3 mt-2">
      {/* Refresh Button */}
      <Button
        variant="outline"
        size="sm"
        className="h-8"
        onClick={handleRefresh}
      >
        <RefreshCw
          className={`mr-2 transition-transform duration-500 ${
            refreshing ? "animate-spin" : ""
          }`}
        />
        {t("dashboard.refresh")}
      </Button>

      {/* Column Visibility Dropdown */}
      <DropdownMenu>
        <DropdownMenuTrigger asChild>
          <Button variant="outline" size="sm" className="h-8">
            <Settings2 className="mr-2" />
            {t("viewDetail.view")}
          </Button>
        </DropdownMenuTrigger>
        <DropdownMenuContent align="end" className="min-w-[200px]">
          <DropdownMenuLabel>{t("viewDetail.toogleColumns")}</DropdownMenuLabel>
          <DropdownMenuSeparator />
          {table
            .getAllColumns()
            .filter(
              (column) =>
                typeof column.accessorFn !== "undefined" && column.getCanHide()
            )
            .map((column) => (
              <DropdownMenuCheckboxItem
                key={column.id}
                checked={column.getIsVisible()}
                onCheckedChange={(value) => column.toggleVisibility(!!value)}
              >
                {getColumnToggleLabel(column.id, t)}
              </DropdownMenuCheckboxItem>
            ))}
        </DropdownMenuContent>
      </DropdownMenu>
    </div>
  );
}
