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

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

import { DataTable } from "@/components";
import { useDataTable, useDataTableContext } from "@/lib/hooks";
import { IListArticles_Response_DTO, MoneyValue } from "@shared/contexts";
import { ColumnDef, Row } from "@tanstack/react-table";
import { t } from "i18next";
import { useMemo } from "react";
import { useNavigate } from "react-router-dom";
import { useCatalogList } from "../hooks";
import { CatalogDataTableFilter } from "./CatalogDataTableFilter";

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

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

  const columns = useMemo<ColumnDef<IListArticles_Response_DTO>[]>(
    () => [
      {
        id: "id" as const,
        accessorKey: "id",
      },
      {
        id: "id_article" as const,
        accessorKey: "id_article",
      },
      {
        id: "catalog_name" as const,
        accessorKey: "catalog_name",
      },
      {
        id: "description" as const,
        accessorKey: "description",
        header: () => <>{t("catalog.list.columns.description")}</>,
      },
      {
        id: "points" as const,
        accessorKey: "points",
        header: () => <div className='text-right'>{t("catalog.list.columns.points")}</div>,
        cell: ({ renderValue }: { renderValue: () => any }) => (
          <div className='text-right'>{renderValue()}</div>
        ),
      },
      {
        id: "retail_price" as const,
        accessorKey: "retail_price",
        header: () => <div className='text-right'>{t("catalog.list.columns.retail_price")}</div>,
        cell: ({ row }: { row: Row<IListArticles_Response_DTO> }) => {
          const price = MoneyValue.create(row.original.retail_price).object;
          return <div className='text-right'>{price.toFormat()}</div>;
        },
      },
    ],
    []
  );

  const { table } = useDataTable({
    data: data?.items ?? [],
    columns: columns,
    pageCount: data?.total_pages ?? -1,
    initialState: {
      columnVisibility: {
        id: false,
        id_article: false,
        catalog_name: false,
      },
    },
  });

  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 }}>
      <CatalogDataTableFilter table={table} />
    </DataTable>
  );
};
