import { PageHeader } from '@erp/core/components';
import { ErrorAlert } from '@erp/customers/components';
import { AppContent, AppHeader, BackHistoryButton, useDebounce } from "@repo/rdx-ui/components";
import { Button } from "@repo/shadcn-ui/components";
import { PlusIcon } from "lucide-react";
import { useMemo, useState } from 'react';
import { useNavigate } from "react-router-dom";
import { useInvoicesQuery } from '../../hooks';
import { useTranslation } from "../../i18n";
import { invoiceResumeDtoToFormAdapter } from '../../schemas/invoice-resume-dto.adapter';
import { InvoicesListGrid } from './invoices-list-grid';

export const InvoiceListPage = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();

  const [pageIndex, setPageIndex] = useState(0);
  const [pageSize, setPageSize] = useState(10);
  const [search, setSearch] = useState("");
  const debouncedQ = useDebounce(search, 300);


  const criteria = useMemo(
    () => ({
      q: debouncedQ || "",
      pageSize,
      pageNumber: pageIndex,
    }),
    [pageSize, pageIndex, debouncedQ]
  );

  const {
    data,
    isLoading,
    isError,
    error,
  } = useInvoicesQuery({
    criteria
  });

  const invoicesPageData = useMemo(() => {
    if (!data) return undefined;
    return {
      ...data,
      items: invoiceResumeDtoToFormAdapter.fromDto(data.items)
    }
  }, [data]);


  const handlePageChange = (newPageIndex: number) => {
    // TanStack usa pageIndex 0-based → API usa 0-based también
    setPageIndex(newPageIndex);
  };

  const handlePageSizeChange = (newSize: number) => {
    setPageSize(newSize);
    setPageIndex(0);
  };

  const handleSearchChange = (value: string) => {
    // Normalización ligera: recorta y colapsa espacios internos
    const cleaned = value.trim().replace(/\s+/g, " ");
    setSearch(cleaned);
    setPageIndex(0);
  };

  if (isError || !invoicesPageData) {
    return (
      <AppContent>
        <ErrorAlert
          title={t("pages.list.loadErrorTitle")}
          message={(error as Error)?.message || "Error al cargar el listado"}
        />
        <BackHistoryButton />
      </AppContent>
    );
  }

  return (
    <>
      <AppHeader>
        <PageHeader
          title={t("pages.list.title")}
          rightSlot={
            <></>}


        />
      </AppHeader>
      <AppContent>
        <div className='flex items-center justify-between space-y-6'>
          <div>
            <h2 className='text-2xl font-bold tracking-tight'>{t("pages.list.title")}</h2>
            <p className='text-muted-foreground'>{t("pages.list.description")}</p>
          </div>
          <div className='flex items-center space-x-2'>
            <Button
              onClick={() => navigate("/customer-invoices/create")}
              variant={'default'}
              aria-label={t("pages.create.title")}
              className='cursor-pointer'
            >
              <PlusIcon className="mr-2 h-4 w-4" aria-hidden />
              {t("pages.create.title")}
            </Button>
          </div>
        </div>
        <div className='flex flex-col w-full h-full py-3'>
          <div className={"flex-1"}>
            <InvoicesListGrid
              invoicesPage={invoicesPageData}
              loading={isLoading}
              pageIndex={pageIndex}
              pageSize={pageSize}
              onPageChange={handlePageChange}
              onPageSizeChange={handlePageSizeChange}
              searchValue={search}
              onSearchChange={handleSearchChange}
            />
          </div>
        </div>
      </AppContent>
    </>
  );
};
