import { formatDate } from '@erp/core/client';
import { DataTableColumnHeader } from '@repo/rdx-ui/components';
import {
  Button, DropdownMenu, DropdownMenuContent,
  DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger,
  Tooltip, TooltipContent, TooltipTrigger
} from '@repo/shadcn-ui/components';
import type { ColumnDef } from "@tanstack/react-table";
import { CopyIcon, DownloadIcon, EditIcon, MailIcon, MoreVerticalIcon, Trash2Icon } from 'lucide-react';
import * as React from "react";
import { CustomerInvoiceStatusBadge } from '../../components';
import { useTranslation } from '../../i18n';
import { InvoiceSummaryFormData } from '../../schemas';

type InvoiceActionHandlers = {
  onEdit?: (invoice: InvoiceSummaryFormData) => void;
  onDuplicate?: (invoice: InvoiceSummaryFormData) => void;
  onDownloadPdf?: (invoice: InvoiceSummaryFormData) => void;
  onSendEmail?: (invoice: InvoiceSummaryFormData) => void;
  onDelete?: (invoice: InvoiceSummaryFormData) => void;
};

export function useInvoicesListColumns(
  handlers: InvoiceActionHandlers = {}
): ColumnDef<InvoiceSummaryFormData>[] {
  const { t } = useTranslation();
  const {
    onEdit, onDuplicate, onDownloadPdf, onSendEmail, onDelete,
  } = handlers;

  return React.useMemo<ColumnDef<InvoiceSummaryFormData>[]>(() => [
    // Nº
    {
      accessorKey: "invoice_number",
      header: ({ column }) => (
        <DataTableColumnHeader column={column} title={t("pages.list.grid_columns.invoice_number")} className="text-left" />
      ),
      cell: ({ row }) => (
        <div className="font-semibold text-left text-primary">
          {row.getValue("invoice_number")}
        </div>
      ),
      enableHiding: false,
      enableSorting: false,
      size: 160,
      minSize: 120,
    },
    // Estado
    {
      accessorKey: "status",
      header: ({ column }) => (
        <DataTableColumnHeader column={column} title={t("pages.list.grid_columns.status")} className="text-left" />
      ),
      cell: ({ row }) => <CustomerInvoiceStatusBadge status={row.getValue("status")} />,
      enableSorting: false,
      size: 140,
      minSize: 120,
    },
    // Serie
    {
      accessorKey: "series",
      header: ({ column }) => (
        <DataTableColumnHeader column={column} title={t("pages.list.grid_columns.series")} className="text-left" />
      ),
      cell: ({ row }) => <div className="font-medium text-left">{row.getValue("series")}</div>,
      enableSorting: false,
      size: 120,
      minSize: 100,
    },
    // Fecha factura
    {
      accessorKey: "invoice_date",
      header: ({ column }) => (
        <DataTableColumnHeader column={column} title={t("pages.list.grid_columns.invoice_date")} className="text-left tabular-nums" />
      ),
      cell: ({ row }) => (
        <div className="font-medium text-left tabular-nums">
          {formatDate(row.getValue("invoice_date"))}
        </div>
      ),
      enableSorting: false,
      size: 140,
      minSize: 120,
    },
    // Fecha operación
    {
      accessorKey: "operation_date",
      header: ({ column }) => (
        <DataTableColumnHeader column={column} title={t("pages.list.grid_columns.operation_date")} className="text-left tabular-nums" />
      ),
      cell: ({ row }) => (
        <div className="font-medium text-left tabular-nums">
          {formatDate(row.getValue("operation_date"))}
        </div>
      ),
      enableSorting: false,
      size: 140,
      minSize: 120,
    },
    // TIN
    {
      id: "recipient_tin",
      accessorKey: "recipient.tin",
      header: ({ column }) => (
        <DataTableColumnHeader column={column} title={t("pages.list.grid_columns.recipient_tin")} className="text-left tabular-nums" />
      ),
      cell: ({ row }) => (
        <div className="font-medium text-left tabular-nums">{row.getValue("recipient_tin")}</div>
      ),
      enableSorting: false,
      size: 160,
      minSize: 140,
    },
    // Cliente
    {
      accessorKey: "recipient.name",
      id: "recipient_name",
      header: ({ column }) => (
        <DataTableColumnHeader column={column} title={t("pages.list.grid_columns.recipient_name")} className="text-left" />
      ),
      cell: ({ row }) => (
        <div className="font-semibold text-left truncate" title={row.getValue("recipient_name")}>
          {row.getValue("recipient_name")}
        </div>
      ),
      enableSorting: false,
      size: 260,
      minSize: 200,
    },
    // Total
    {
      accessorKey: "total_amount_fmt",
      header: ({ column }) => (
        <DataTableColumnHeader column={column} title={t("pages.list.grid_columns.total_amount")} className="text-right tabular-nums" />
      ),
      cell: ({ row }) => (
        <div className="font-semibold text-right tabular-nums">{row.getValue("total_amount_fmt")}</div>
      ),
      enableSorting: false,
      size: 140,
      minSize: 120,
    },

    // ─────────────────────────────
    // Acciones
    // ─────────────────────────────
    {
      id: "actions",
      header: () => <span className="sr-only">{t("common.actions")}</span>,
      enableSorting: false,
      enableHiding: false,
      size: 110,
      minSize: 96,
      cell: ({ row }) => {
        const invoice = row.original;
        const stop = (e: React.MouseEvent | React.KeyboardEvent) => e.stopPropagation();

        return (
          <div className="flex items-center justify-end gap-1 pr-1" onClick={stop} onKeyDown={stop}>
            {/* Editar (acción primaria) */}
            <Tooltip>
              <TooltipTrigger asChild>
                <Button
                  type="button"
                  size="sm"
                  variant="ghost"
                  className='cursor-pointer text-muted-foreground hover:text-primary'
                  aria-label={t("common.edit")}
                  onClick={(e) => {
                    e.stopPropagation();
                    onEdit?.(invoice);
                  }}
                >
                  <EditIcon className="size-4" aria-hidden="true" />
                </Button>
              </TooltipTrigger>
              <TooltipContent>{t("common.edit")}</TooltipContent>
            </Tooltip>

            {/* Menú demás acciones */}
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button
                  type="button"
                  size="sm"
                  variant="ghost"
                  className='cursor-pointer text-muted-foreground hover:text-primary'
                  aria-label={t("common.more_actions")}
                  onClick={stop}
                >
                  <MoreVerticalIcon className="size-4" aria-hidden="true" />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end" className="w-48">
                <DropdownMenuItem
                  onClick={() => onDuplicate?.(invoice)}
                  className="cursor-pointer"
                >
                  <CopyIcon className="mr-2 size-4" />
                  {t("common.duplicate")}
                </DropdownMenuItem>
                <DropdownMenuSeparator />
                <DropdownMenuItem
                  onClick={() => onDownloadPdf?.(invoice)}
                  className="cursor-pointer"
                >
                  <DownloadIcon className="mr-2 size-4" />
                  {t("common.download_pdf")}
                </DropdownMenuItem>

                <DropdownMenuItem
                  onClick={() => onSendEmail?.(invoice)}
                  className="cursor-pointer"
                >
                  <MailIcon className="mr-2 size-4" />
                  {t("common.send_email")}
                </DropdownMenuItem>                        <DropdownMenuSeparator />
                <DropdownMenuItem
                  onClick={() => onDelete?.(invoice)}
                  className="text-destructive focus:text-destructive-foreground focus:bg-destructive cursor-pointer"
                >
                  <Trash2Icon className="mr-2 size-4 text-destructive focus:text-destructive-foreground" />
                  {t("common.delete")}
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>

          </div>
        );
      },
    },
  ], [t, onEdit, onDuplicate, onDownloadPdf, onSendEmail, onDelete]);
}
