import { Badge, 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 { IListQuotes_Response_DTO, MoneyValue, UTCDateValue } from "@shared/contexts";
import { ColumnDef } from "@tanstack/react-table";
import { t } from "i18next";
import { useMemo } from "react";
import { useNavigate } from "react-router-dom";
import { useQuotesList } from "../hooks";

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

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

  const columns = useMemo<ColumnDef<IListQuotes_Response_DTO, any>[]>(
    () => [
      {
        id: "date" as const,
        accessor: "date",
        header: () => <>{t("quotes.list.columns.date")}</>,
        cell: ({ table, row: { index, original }, column, getValue }) => {
          console.log(original.date);
          const quoteDate = UTCDateValue.create(original.date);
          return quoteDate.isSuccess ? quoteDate.object.toLocaleDateString("es-ES") : "-";
        },
        enableResizing: false,
        size: 10,
      },
      {
        id: "customer_information" as const,
        accessorKey: "customer_information",
        header: () => <>{t("quotes.list.columns.customer_information")}</>,
        cell: ({ renderValue }: { renderValue: () => any }) => (
          <div className='font-semibold'>{renderValue()}</div>
        ),
        enableResizing: false,
        size: 10,
      },
      {
        id: "reference" as const,
        accessorKey: "reference",
        header: () => <>{t("quotes.list.columns.reference")}</>,
        enableResizing: false,
        size: 10,
      },
      {
        id: "status" as const,
        accessorKey: "status",
        header: () => <>{t("quotes.list.columns.status")}</>,
        cell: ({ renderValue }: { renderValue: () => any }) => <Badge>{renderValue()}</Badge>,
        enableResizing: false,
        size: 10,
      },
      {
        id: "total_price" as const,
        accessor: "total_price",
        header: () => <div className='text-right'>{t("quotes.list.columns.total_price")}</div>,
        cell: ({ table, row: { index, original }, column, getValue }) => {
          const price = MoneyValue.create(original.total_price);
          return (
            <div className='text-right'>{price.isSuccess ? price.object.toFormat() : "-"}</div>
          );
        },
        enableResizing: false,
        size: 20,
      },
    ],
    []
  );

  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 creando alguna cotización'
        buttonText=''
        onButtonClick={() => navigate("add", { relative: "path" })}
      />
    );
  }

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