import {
  ButtonGroup,
  ColorBadge,
  DataTable,
  DataTableSkeleton,
  ErrorOverlay,
  SimpleEmptyState,
} from "@/components";
import { DataTableToolbar } from "@/components/DataTable/DataTableToolbar";
import { useDataTable, useDataTableContext } from "@/lib/hooks";
import {
  Button,
  Card,
  CardContent,
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
  Tooltip,
  TooltipContent,
  TooltipTrigger,
} from "@/ui";
import { useToast } from "@/ui/use-toast";
import { IListQuotes_Response_DTO, UTCDateValue } from "@shared/contexts";
import { ColumnDef, Row } from "@tanstack/react-table";
import { t } from "i18next";
import { FilePenLineIcon, MoreVerticalIcon } from "lucide-react";
import { useCallback, useEffect, useId, useMemo, useState } from "react";
import { useNavigate } from "react-router-dom";
import { useQuotes } from "../hooks";
import { DownloadQuoteDialog } from "./DownloadQuoteDialog";
import { QuoteResume } from "./QuoteResume";

export const QuotesDataTable = ({
  status = "all",
  preview = false,
}: {
  status?: string;
  preview?: boolean;
}) => {
  const navigate = useNavigate();
  const { toast } = useToast();

  const tableId = useId();
  const previewId = useId();

  const { pagination, globalFilter, isFiltered } = useDataTableContext();

  const [activeRow, setActiveRow] = useState<Row<IListQuotes_Response_DTO> | undefined>(undefined);

  const { useList, useDownloader, getQuotePDFFilename } = useQuotes();

  const { data, isPending, isError, error } = useList({
    pagination: {
      pageIndex: pagination.pageIndex,
      pageSize: pagination.pageSize,
    },
    status,
    quickSearchTerm: globalFilter,
  });

  const { download, ...downloadProps } = useDownloader();

  const handleOnRowClick = (row: Row<IListQuotes_Response_DTO>) => {
    setActiveRow(row);
  };

  const handleFinishDownload = useCallback(() => {
    toast({
      description: t("quotes.downloading_dialog.toast_success"),
    });
  }, [toast]);

  const handleEditQuote = useCallback(
    (quote: IListQuotes_Response_DTO) => {
      toast({ title: "Guardo => " + quote.id });
      navigate(`/quotes/edit/${quote.id}`, { relative: "path" });
    },
    [navigate, toast]
  );

  const columns = useMemo<ColumnDef<IListQuotes_Response_DTO, unknown>[]>(() => {
    const columns = [
      {
        id: "reference" as const,
        accessorKey: "reference",
        header: () => <>{t("quotes.list.columns.reference")}</>,
        cell: ({
          row: { original },
          renderValue,
        }: {
          row: { original: IListQuotes_Response_DTO };
          renderValue: () => any;
        }) => (
          <Button
            size='sm'
            variant='link'
            className='h-8 gap-1 px-0 text-left text-ellipsis'
            onClick={(e) => {
              e.preventDefault();
              handleEditQuote(original);
            }}
          >
            <div className=''>{renderValue()}</div>
          </Button>
        ),
      },

      {
        id: "status" as const,
        accessorKey: "status",
        header: () => <>{t("quotes.list.columns.status")}</>,
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        cell: ({ row: { original } }: { row: { original: IListQuotes_Response_DTO } }) => (
          <ColorBadge label={t(`quotes.status.${original.status}`)} />
        ),
      },
      {
        id: "date" as const,
        accessor: "date",
        header: () => (
          <div className='text-right text-ellipsis'>{t("quotes.list.columns.date")}</div>
        ),
        cell: ({ row: { original } }: { row: { original: IListQuotes_Response_DTO } }) => {
          const quoteDate = UTCDateValue.create(original.date);
          return (
            <div className='text-right text-ellipsis'>
              {quoteDate.isSuccess ? quoteDate.object.toLocaleDateString("es-ES") : "-"}
            </div>
          );
        },
      },
      {
        id: "customer_reference" as const,
        accessorKey: "customer_reference",
        header: () => <>{t("quotes.list.columns.customer_reference")}</>,
        cell: ({ renderValue }: { renderValue: () => any }) => (
          <div className='text-left text-ellipsis'>{renderValue()}</div>
        ),
      },
      {
        id: "customer_information" as const,
        accessorKey: "customer_information",
        header: () => <>{t("quotes.list.columns.customer_information")}</>,
        cell: ({ row: { original } }: { row: { original: IListQuotes_Response_DTO } }) => (
          <div className='text-left text-ellipsis'>
            {original.customer_information.split("\n").map((item, index) => {
              return (
                <span
                  key={index}
                  className={
                    index === 0 ? "font-medium" : "hidden text-sm text-muted-foreground md:inline"
                  }
                >
                  {item}
                  <br />
                </span>
              );
            })}
          </div>
        ),
        size: 600,
      },
      /*{
          id: "total_price" as const,
          accessor: "total_price",
          header: () => <div className='text-right'>{t("quotes.list.columns.total_price")}</div>,
          cell: ({ row: { original } }) => {
            const price = MoneyValue.create(original.total_price);
            return (
              <div className='text-right'>{price.isSuccess ? price.object.toFormat() : "-"}</div>
            );
          },
        },*/
    ];

    const actionColumn = [
      {
        id: "row-actions",
        header: () => null,
        cell: ({ row }: { row: Row<IListQuotes_Response_DTO> }) => (
          <ButtonGroup>
            <Tooltip>
              <TooltipTrigger asChild>
                <Button
                  size='sm'
                  variant='outline'
                  className='h-8 gap-1'
                  onClick={(e) => {
                    e.preventDefault();
                    handleEditQuote(row.original);
                  }}
                >
                  <FilePenLineIcon className='h-3.5 w-3.5' />
                  <span className='lg:sr-only xl:not-sr-only xl:whitespace-nowrap'>
                    {t("quotes.list.columns.actions.edit")}
                  </span>
                </Button>
              </TooltipTrigger>
              <TooltipContent>
                <p>{t("quotes.list.columns.actions.edit")}</p>
              </TooltipContent>
            </Tooltip>

            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button size='icon' variant='outline' className='w-8 h-8'>
                  <MoreVerticalIcon className='h-3.5 w-3.5' />
                  <span className='sr-only'>{t("common.more")}</span>
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align='end'>
                <DropdownMenuItem
                  onClick={() => {
                    download(row.original.id, getQuotePDFFilename(row.original));
                  }}
                >
                  Download
                </DropdownMenuItem>
                <DropdownMenuSeparator />
                <DropdownMenuItem>{t("common.archive")}</DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          </ButtonGroup>
        ),
      },
    ];

    return preview ? columns : [...columns, ...actionColumn];
  }, [preview]);

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

  useEffect(() => {
    if (table && data && data?.total_pages > 0) {
      setActiveRow(table.getRowModel().rows[0]);
    }
  }, [data, table]);

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

  if (isPending) {
    return (
      <div className='grid items-start flex-1 gap-4 sm:py-0 md:gap-8 lg:grid-cols-3 xl:grid-cols-3'>
        <Card className='grid items-start gap-4 auto-rows-max md:gap-8 lg:col-span-2'>
          <CardContent>
            <DataTableSkeleton
              columnCount={6}
              searchableColumnCount={1}
              filterableColumnCount={2}
              //cellWidths={["10rem", "40rem", "12rem", "12rem", "8rem"]}
              shrinkZero
            />
          </CardContent>
        </Card>
        <div></div>
      </div>
    );
  }

  if (data?.total_items === 0 && !isFiltered) {
    return (
      <Card>
        <CardContent>
          <SimpleEmptyState
            subtitle='Empieza creando alguna cotización'
            buttonText={t("quotes.create.title")}
            onButtonClick={() => navigate("add", { relative: "path" })}
          />
        </CardContent>
      </Card>
    );
  }

  return (
    <>
      <div className='flex flex-col items-stretch flex-1 gap-4 xl:flex-row'>
        <div id={tableId} className='flex items-stretch flex-1'>
          <DataTable
            table={table}
            paginationOptions={{ visible: true }}
            className='grid items-start flex-1 gap-4 auto-rows-max md:gap-8 lg:col-span-2'
            onRowClick={handleOnRowClick}
            activeRowIndex={activeRow?.index}
          >
            <DataTableToolbar table={table} />
          </DataTable>
        </div>

        {preview && (
          <div id={previewId} className='flex items-stretch '>
            <QuoteResume quoteId={activeRow?.original.id} />
          </div>
        )}
      </div>
      <DownloadQuoteDialog {...downloadProps} onFinishDownload={handleFinishDownload} />
    </>
  );
};
