import { PageHeader } from "@erp/core/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 { Outlet, useNavigate } from "react-router-dom";
import { ErrorAlert } from "../../components";
import { useCustomerListQuery } 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 } = useCustomerListQuery({ criteria });

  const handlePageChange = (newPageIndex: number) => {
    setPageIndex(newPageIndex);
  };

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

  const handleSearchChange = (value: string) => {
    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>
        <PageHeader
          title={t("pages.list.title")}
          description={t("pages.list.description")}
          rightSlot={
            <div className='flex items-center space-x-2'>
              <Button
                onClick={() => navigate("/customers/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>
          }
        />
      </AppHeader>
      <AppContent>
        <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>
    </>
  );
};
