
import { DataTable, SkeletonDataTable } from "@repo/rdx-ui/components";
import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput, Spinner } from '@repo/shadcn-ui/components';
import { SearchIcon, XIcon } from 'lucide-react';
import { useCallback, useState } from "react";
import { useNavigate } from "react-router-dom";
import { useTranslation } from "../../i18n";
import { CustomerSummaryFormData, CustomersPageFormData } from '../../schemas';
import { useCustomersListColumns } from './use-customers-list-columns';


export type CustomerUpdateCompProps = {
  customersPage: CustomersPageFormData;
  loading?: boolean;

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

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

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

export const CustomersListGrid = ({
  customersPage,
  loading,
  pageIndex,
  pageSize,
  onPageChange,
  onPageSizeChange,
  searchValue, onSearchChange,
  onRowClick
}: CustomerUpdateCompProps) => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const { items, total_items } = customersPage;

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

  const columns = useCustomersListColumns({
    onEdit: (customer) => navigate(`/customers/${customer.id}/edit`),
    onView: (customer) => null, //duplicateInvoice(inv.id),
    onDelete: (customer) => null, //confirmDelete(inv.id),
  });


  // Navegación centralizada (click/teclado)
  const goToRow = useCallback(
    (id: string, newTab = false) => {
      const url = `/customers/${id}`;
      if (newTab) {
        window.open(url, "_blank", "noopener,noreferrer");
      } else {
        navigate(url);
      }
    },
    [navigate]
  );

  // 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(
    (customer: CustomerSummaryFormData, _i: number, e: React.MouseEvent) => {
      const url = `/customer-invoices/${customer.id}/edit`;
      if (e.metaKey || e.ctrlKey) { window.open(url, "_blank", "noopener,noreferrer"); return; }
      preview.open(customer);
    },
    [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 max-w-lg" 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>
      </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={() => null /*handleRowClick*/}
          />
        </div>

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