import type { CellKeyDownEvent, RowClickedEvent } from "ag-grid-community";
import { useCallback, useState } from "react";


import { DataTable, SkeletonDataTable } from '@repo/rdx-ui/components';
import { Button, InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput, Select, SelectContent, SelectItem, SelectTrigger, SelectValue, Spinner } from '@repo/shadcn-ui/components';
import { FileDownIcon, FilterIcon, SearchIcon, XIcon } from 'lucide-react';
import { useNavigate } from "react-router-dom";
import { usePinnedPreviewSheet } from '../../hooks';
import { useTranslation } from "../../i18n";
import { InvoiceSummaryFormData, InvoicesPageFormData } from '../../schemas';
import { InvoicePreviewPanel } from './invoice-preview-panel';
import { useInvoicesListColumns } from './use-invoices-list-columns';

export type InvoiceUpdateCompProps = {
  invoicesPage: InvoicesPageFormData;
  loading?: boolean;

  pageIndex: number;
  pageSize: number;
  onPageChange?: (pageNumber: number) => void;
  onPageSizeChange?: (pageSize: number) => void;

  searchValue: string;
  onSearchChange: (value: string) => void;

  onRowClick?: (row: InvoiceSummaryFormData, index: number, event: React.MouseEvent<HTMLTableRowElement>) => void;
}


// Create new GridExample component
export const InvoicesListGrid = ({
  invoicesPage,
  loading,
  pageIndex,
  pageSize,
  onPageChange,
  onPageSizeChange,
  searchValue, onSearchChange,
  onRowClick
}: InvoiceUpdateCompProps) => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const { items, total_items } = invoicesPage;

  // Hook con Sheet de shadcn
  const preview = usePinnedPreviewSheet<InvoiceSummaryFormData>({
    persistKey: "invoice-preview-pin",
    widthClass: "w-[500px]",
  });

  const [statusFilter, setStatusFilter] = useState("todas");

  const columns = useInvoicesListColumns({
    onEdit: (invoice) => navigate(`/customer-invoices/${invoice.id}/edit`),
    onDuplicate: (invoice) => null, //duplicateInvoice(inv.id),
    onDownloadPdf: (invoice) => null, //downloadInvoicePdf(inv.id),
    onSendEmail: (invoice) => null, //sendInvoiceEmail(inv.id),
    onDelete: (invoice) => null, //confirmDelete(inv.id),
  });

  // Navegación accesible (click o teclado)
  const goToRow = useCallback(
    (id: string, newTab = false) => {
      const url = `/customer-invoices/${id}/edit`;
      newTab
        ? window.open(url, "_blank", "noopener,noreferrer")
        : navigate(url);
    },
    [navigate]
  );

  const onRowClicked = useCallback(
    (e: RowClickedEvent<any>) => {
      if (!e.data) return;
      const newTab =
        e.event instanceof MouseEvent && (e.event.metaKey || e.event.ctrlKey);
      goToRow(e.data.id, newTab);
    },
    [goToRow]
  );

  const onCellKeyDown = useCallback(
    (e: CellKeyDownEvent<any>) => {
      if (!e.data) return;

      const ev = e.event;
      if (!ev || !(ev instanceof KeyboardEvent)) return;

      const key = ev.key;
      if (key === "Enter" || key === " ") {
        ev.preventDefault();
        goToRow(e.data.id);
      }
      if ((ev.ctrlKey || ev.metaKey) && key === "Enter") {
        ev.preventDefault();
        goToRow(e.data.id, true);
      }
    },
    [goToRow]
  );

  // Handlers de búsqueda
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => onSearchChange(e.target.value);
  const handleClear = () => onSearchChange("");
  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === "Enter") {
      // Envío inmediato: forzar “salto” del debounce
      onSearchChange((e.target as HTMLInputElement).value);
    }
  };

  const handleRowClick = useCallback(
    (invoice: InvoiceSummaryFormData, _i: number, e: React.MouseEvent) => {
      const url = `/customer-invoices/${invoice.id}/edit`;
      if (e.metaKey || e.ctrlKey) { window.open(url, "_blank", "noopener,noreferrer"); return; }
      preview.open(invoice);
    },
    [preview]
  );

  if (loading) {
    return (
      <div className="flex flex-col gap-4">
        <SkeletonDataTable
          columns={columns.length}
          rows={Math.max(6, pageSize)}
          showFooter
          footerProps={{ pageIndex, pageSize, totalItems: total_items ?? 0 }}
        />
      </div>
    );
  }

  // Render principal
  return (
    <div className="flex flex-col gap-4">
      {/* Barra de filtros */}
      <div className="flex flex-col sm:flex-row gap-4 mb-6">
        <div className="relative flex-1" aria-label={t("pages.list.searchPlaceholder")}>
          <InputGroup className='bg-background' data-disabled={loading}>
            <InputGroupInput
              placeholder={t("common.search_placeholder")}
              value={searchValue}
              onChange={handleInputChange}
              onKeyDown={handleKeyDown}
              inputMode="search"
              autoComplete="off"
              spellCheck={false}
              disabled={loading}
            />
            <InputGroupAddon>
              <SearchIcon />
            </InputGroupAddon>
            <InputGroupAddon align="inline-end">
              {loading && <Spinner />}
              {!searchValue && !loading && <InputGroupButton variant='secondary' className='cursor-pointer'>
                {t("common.search")}
              </InputGroupButton>}
              {searchValue && !loading && <InputGroupButton variant='secondary' className='cursor-pointer' aria-label={t("common.clear")} onClick={handleClear}>
                <XIcon className="size-4" aria-hidden />
                <span className="sr-only">{t("common.search")}</span>
              </InputGroupButton>}

            </InputGroupAddon>
          </InputGroup>
        </div>
        <Select value={statusFilter} onValueChange={setStatusFilter}>
          <SelectTrigger className="w-full sm:w-48 bg-white border-gray-200 shadow-sm">
            <FilterIcon className="mr-2 h-4 w-4" />
            <SelectValue placeholder="Estado" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="todas">Todas</SelectItem>
            <SelectItem value="pagada">Pagadas</SelectItem>
            <SelectItem value="pendiente">Pendientes</SelectItem>
            <SelectItem value="vencida">Vencidas</SelectItem>
          </SelectContent>
        </Select>
        <Button variant="outline" className="border-blue-200 text-blue-600 hover:bg-blue-50 bg-transparent">
          <FileDownIcon className="mr-2 h-4 w-4" />
          Exportar
        </Button>
      </div>
      <div className="relative flex">
        <div className={preview.isPinned ? "flex-1 mr-[500px]" : "flex-1"}>
          <DataTable
            columns={columns}
            data={items}
            readOnly
            enableRowSelection
            enablePagination
            manualPagination
            pageIndex={pageIndex}
            pageSize={pageSize}
            totalItems={total_items}
            onPageChange={onPageChange}
            onPageSizeChange={onPageSizeChange}
            onRowClick={handleRowClick}
          />
        </div>

        <preview.Preview>
          {({ item, isPinned, close, togglePin }) => (
            <InvoicePreviewPanel
              invoice={item}
              isPinned={isPinned}
              onClose={close}
              onTogglePin={togglePin}
            />
          )}
        </preview.Preview>
      </div>
    </div>
  );
};