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

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

export const CatalogPickerDataTable = ({
  onSelect,
}: {
  onSelect: (data: unknown, quantity: number) => void;
}) => {
  const navigate = useNavigate();
  const { pagination, globalFilter, isFiltered } = useDataTableContext();

  const [quantities, setQuantities] = useState<number[]>([]);

  const handleQuantity = (index: number, quantity: number) => {
    setQuantities((prev) => {
      prev[index] = quantity;
      return prev;
    });
  };

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

  const columns = useMemo<ColumnDef<IListArticles_Response_DTO>[]>(() => {
    return [
      {
        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>;
        },
      },
      {
        id: "quantity" as const,
        accessorKey: "quantity",
        header: () => <div className='text-right'>{t("catalog.list.columns.quantity")}</div>,
        cell: ({ row: { index } }) => {
          return (
            <input
              type='number'
              name='quantity'
              defaultValue={1}
              min={1}
              value={quantities[index]}
              onChange={(event) => {
                event.preventDefault();
                handleQuantity(index, +event.target.value);
              }}
            />
          );
        },
      },
      {
        id: "row-actions",
        header: () => null,
        cell: ({ row }: { row: Row<IListArticles_Response_DTO> }) => (
          <Button
            size='sm'
            variant='outline'
            className='h-8 gap-1'
            onClick={(event) => {
              event.preventDefault();
              onSelect && onSelect(row.original, quantities[row.index]);
            }}
          >
            <PackagePlusIcon className='h-3.5 w-3.5' />
            <span className='sr-only xl:not-sr-only xl:whitespace-nowrap'>{t("common.add")}</span>
          </Button>
        ),
      },
    ];
  }, []);

  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 (
      <DataTableSkeleton
        columnCount={6}
        searchableColumnCount={1}
        filterableColumnCount={2}
        //cellWidths={["10rem", "40rem", "12rem", "12rem", "8rem"]}
        shrinkZero
      />
    );
  }

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

  return (
    <DataTable
      className='bg-transparent border-0 shadow-none'
      table={table}
      paginationOptions={{ visible: true, enablePageSizeSelector: false }}
      footerClassName='px-10 pt-2 border-t'
    >
      <CatalogDataTableFilter table={table} />
    </DataTable>
  );
};
