import { Card, CardContent } from "@/ui";

import { DataTableSkeleton, ErrorOverlay, SimpleEmptyState } from "@/components";

import { DataTable } from "@/components";
import { DataTableToolbar } from "@/components/DataTable/DataTableToolbar";
import { useDataTable, useDataTableContext } from "@/lib/hooks";
import { IListArticles_Response_DTO } from "@shared/contexts";
import { ColumnDef } from "@tanstack/react-table";
import { useMemo } from "react";
import { useNavigate } from "react-router-dom";
import { useDealerList } from "../hooks";

export const DealerDataTable = () => {
  const navigate = useNavigate();
  const { pagination, globalFilter, isFiltered } = useDataTableContext();

  const { data, isPending, isError, error } = useDealerList({
    pagination: {
      pageIndex: pagination.pageIndex,
      pageSize: pagination.pageSize,
    },
    searchTerm: globalFilter,
  });

  const columns = useMemo<ColumnDef<IListArticles_Response_DTO, any>[]>(
    () => [
      {
        id: "id" as const,
        accessorKey: "id",
        enableResizing: false,
        size: 10,
      },
      {
        id: "name" as const,
        accessorKey: "name",
        enableResizing: false,
        size: 10,
      },
    ],
    []
  );

  const { table } = useDataTable({
    data: data?.items ?? [],
    columns: columns,
    pageCount: data?.total_pages ?? -1,
  });

  if (isError) {
    return <ErrorOverlay subtitle={(error as Error).message} />;
  }

  if (isPending) {
    return (
      <Card>
        <CardContent>
          <DataTableSkeleton
            columnCount={6}
            searchableColumnCount={1}
            filterableColumnCount={2}
            //cellWidths={["10rem", "40rem", "12rem", "12rem", "8rem"]}
            shrinkZero
          />
        </CardContent>
      </Card>
    );
  }

  if (data?.total_items === 0 && !isFiltered) {
    return (
      <SimpleEmptyState
        subtitle='Empieza cargando los artículos del catálogo'
        buttonText=''
        onButtonClick={() => navigate("/catalog/add")}
      />
    );
  }

  return (
    <>
      <DataTable table={table} paginationOptions={{ visible: true }}>
        <DataTableToolbar table={table} />
      </DataTable>
    </>
  );
};
