import { PageHeader } from '@erp/core/components';
import { AppBreadcrumb, 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 { Outlet, useNavigate } from "react-router-dom";
import { ErrorAlert } from '../../components';
import { useCustomersQuery } from '../../hooks';
import { useTranslation } from "../../i18n";
import { CustomersListGrid } from './customers-list-grid';

export const CustomersListPage = () => {
  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: customersPageData,
    isLoading,
    isError,
    error,
  } = useCustomersQuery({
    criteria
  });

  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 || !customersPageData) {
    return (
      <AppContent>
        <ErrorAlert
          title={t("pages.list.loadErrorTitle")}
          message={(error as Error)?.message || "Error al cargar el listado"}
        />
        <BackHistoryButton />
      </AppContent>
    );
  }


  return (
    <>
      <AppHeader>
        <AppBreadcrumb />
        <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"}>
            <CustomersListGrid
              customersPage={customersPageData}
              loading={isLoading}
              pageIndex={pageIndex}
              pageSize={pageSize}
              onPageChange={handlePageChange}
              onPageSizeChange={handlePageSizeChange}
              searchValue={search}
              onSearchChange={handleSearchChange}
            />
          </div>
        </div>
        <Outlet />
      </AppContent>
    </>
  );
};
