"use client";

import {
  Button,
  DropdownMenu,
  DropdownMenuCheckboxItem,
  DropdownMenuContent,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@repo/shadcn-ui/components";
import type { Column, Table } from "@tanstack/react-table";
import { Settings2 } from "lucide-react";

import { useTranslation } from "../../locales/i18n.ts";

export function DataTableViewOptions<TData>({ table }: { table: Table<TData> }) {
  const { t } = useTranslation();
  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <Button className="ml-auto hidden h-8 lg:flex" size="sm" type="button" variant="outline">
          <Settings2 />
          {t("components.datatable_view_options.columns_button")}
        </Button>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="end">
        <DropdownMenuLabel>
          {t("components.datatable_view_options.toggle_columns")}
        </DropdownMenuLabel>
        <DropdownMenuSeparator />
        {table
          .getAllColumns()
          .filter((column) => typeof column.accessorFn !== "undefined" && column.getCanHide())
          .map((column) => {
            return (
              <DropdownMenuCheckboxItem
                checked={column.getIsVisible()}
                key={column.id}
                onCheckedChange={(value) => column.toggleVisibility(!!value)}
              >
                {getColumnLabel(column)}
              </DropdownMenuCheckboxItem>
            );
          })}
      </DropdownMenuContent>
    </DropdownMenu>
  );
}

const getColumnLabel = <TData, TValue>(column: Column<TData, TValue>): string => {
  let label = String(column.id);
  const h = column.columnDef.header;

  // header como string literal
  if (typeof h === "string") label = h;

  // header función → intentar obtener title si lo usas en tus componentes
  if (typeof h === "function") {
    // tu DataTableColumnHeader recibe `title` como prop → está en column.columnDef.meta
    const meta = column.columnDef.meta as { title?: string } | undefined;
    label = meta?.title ?? column.id;
  }
  return label;
};
