import {
  FormCurrencyField,
  FormPercentageField,
  FormQuantityField,
  FormTextAreaField,
} from "@/components";

import { DataTableProvider } from "@/lib/hooks";
import { cn } from "@/lib/utils";
import { ResizableHandle, ResizablePanel, ResizablePanelGroup } from "@/ui";
import { useToast } from "@/ui/use-toast";
import { CurrencyData, Language, Quantity } from "@shared/contexts";
import { ColumnDef } from "@tanstack/react-table";
import { t } from "i18next";
import { ChevronDownIcon, ChevronUpIcon, CopyIcon, Trash2Icon } from "lucide-react";
import { useCallback, useState } from "react";
import { useFieldArray, useFormContext } from "react-hook-form";
import { useDetailColumns } from "../../hooks";
import { CatalogPickerDataTable } from "../CatalogPickerDataTable";
import { QuoteItemsSortableDataTable, RowIdData } from "../QuoteItemsSortableDataTable";
import { BlocksPickerDialog } from "./BlocksPickerDialog/BlocksPickerDialog";
import { CatalogPickerDialog } from "./CatalogPickerDialog";

export const QuoteDetailsCardEditor = ({
  currency,
  language,
  defaultValues,
}: {
  currency: CurrencyData;
  language: Language;
  defaultValues: Readonly<{ [x: string]: any }> | undefined;
}) => {
  const { toast } = useToast();
  const { control, register } = useFormContext();

  const [pickerMode] = useState<"dialog" | "panel">("dialog");

  const [articlePickerDialogOpen, setArticlePickerDialogOpen] = useState<boolean>(false);
  const [blockPickerDialogOpen, setBlockPickerDialogOpen] = useState<boolean>(false);

  const { fields, ...fieldActions } = useFieldArray({
    control,
    name: "items",
  });

  const columns: ColumnDef<RowIdData, unknown>[] = useDetailColumns(
    [
      /*{
        id: "row_id" as const,
        header: () => (
          <HashIcon aria-label='Orden de fila' className='items-center justify-center w-4 h-4' />
        ),
        accessorFn: (_: unknown, index: number) => index + 1,
        size: 5,
        enableHiding: false,
        enableSorting: false,
        enableResizing: false,
      },*/
      /*{
        id: "id_article" as const,
        accessorKey: "id_article",
        header: "artículo",
        cell: ({ row: { index, original } }) => {
          return (
            <FormTextAreaField
              readOnly={original?.id_article}
              autoSize
              {...register(`items.${index}.id_article`)}
            />
          );
        },
        size: 500,
      },*/
      {
        id: "description" as const,
        accessorKey: "description",
        header: t("quotes.form_fields.items.description.label"),
        cell: ({ row: { index, original } }) => {
          return (
            <FormTextAreaField
              readOnly={original?.id_article}
              autoSize
              {...register(`items.${index}.description`)}
            />
          );
        },
        size: 500,
      },
      {
        id: "quantity" as const,
        accessorKey: "quantity",
        header: () => (
          <div className='text-right'>{t("quotes.form_fields.items.quantity.label")}</div>
        ),
        cell: ({ row: { index } }) => {
          return (
            <FormQuantityField
              scale={0}
              className='text-right'
              {...register(`items.${index}.quantity`)}
            />
          );
        },
      },
      {
        id: "unit_price" as const,
        accessorKey: "unit_price",
        header: () => (
          <div className='text-right'>{t("quotes.form_fields.items.unit_price.label")}</div>
        ),
        cell: ({ row: { index } }) => {
          return (
            <FormCurrencyField
              currency={currency}
              language={language}
              scale={2}
              className='text-right'
              {...register(`items.${index}.unit_price`)}
            />
          );
        },
      },
      {
        id: "subtotal_price" as const,
        accessorKey: "subtotal_price",
        header: () => (
          <div className='text-right'>{t("quotes.form_fields.items.subtotal_price.label")}</div>
        ),
        cell: ({ row: { index } }) => {
          return (
            <FormCurrencyField
              currency={currency}
              language={language}
              scale={2}
              readOnly
              className='text-right'
              {...register(`items.${index}.subtotal_price`)}
            />
          );
        },
      },
      {
        id: "discount" as const,
        accessorKey: "discount",
        header: () => (
          <div className='text-right'>{t("quotes.form_fields.items.discount.label")}</div>
        ),
        cell: ({ row: { index } }) => {
          return (
            <FormPercentageField
              scale={2}
              className='text-right'
              {...register(`items.${index}.discount`)}
            />
          );
        },
      },
      {
        id: "total_price" as const,
        accessorKey: "total_price",
        header: () => (
          <div className='text-right'>{t("quotes.form_fields.items.total_price.label")}</div>
        ),
        cell: ({ row: { index } }) => {
          return (
            <FormCurrencyField
              variant='ghost'
              currency={currency}
              language={language}
              scale={2}
              readOnly
              className='font-semibold text-right'
              {...register(`items.${index}.total_price`)}
            />
          );
        },
      },
    ],
    {
      enableDragHandleColumn: false, // <--- Desactivado temporalmente
      enableSelectionColumn: true,
      enableActionsColumn: true,
      rowActionFn: (props) => {
        const { table, row } = props;
        return [
          {
            label: t("common.duplicate_row"),
            icon: <CopyIcon className='w-4 h-4 mr-2' />,
            onClick: () => table.options.meta?.duplicateItems(row.index),
          },
          {
            label: t("common.insert_row_above"),
            icon: <ChevronUpIcon className='w-4 h-4 mr-2' />,
            onClick: () => table.options.meta?.insertItem(row.index),
          },
          {
            label: t("common.insert_row_below"),
            icon: <ChevronDownIcon className='w-4 h-4 mr-2' />,
            onClick: () => table.options.meta?.insertItem(row.index + 1),
          },

          {
            label: "-",
          },
          {
            label: t("common.remove_row"),
            //shortcut: "⌘⌫",
            icon: <Trash2Icon className='w-4 h-4 mr-2' />,
            onClick: () => {
              table.options.meta?.deleteItems(row.index);
            },
          },
        ];
      },
    }
  );

  const handleAppendCatalogArticle = useCallback(
    (article: any, quantity: number = 1) => {
      fieldActions.append({
        ...article,
        quantity: {
          amount: 100 * quantity,
          scale: Quantity.DEFAULT_SCALE,
        },
        unit_price: article.retail_price,
        discount: {
          amount: null,
          scale: 2,
        },
      });
      toast({
        title: t("quotes.catalog_picker_dialog.toast_article_added"),
        description: article.description,
      });
    },
    [fieldActions]
  );

  const handleAppendBlock = useCallback(
    (block: any) => {
      fieldActions.append({
        description: block.body,
      });
      toast({
        title: t("quotes.blocks_picker_dialog.toast_article_added"),
        description: block.title,
      });
    },
    [fieldActions]
  );

  const [isCollapsed, setIsCollapsed] = useState(false);

  const defaultLayout = [265, 440, 655];
  const navCollapsedSize = 4;

  if (pickerMode === "dialog") {
    return (
      <div className='relative'>
        <QuoteItemsSortableDataTable
          actions={{
            ...fieldActions,
            pickCatalogArticle: () => setArticlePickerDialogOpen(true),
            pickBlock: () => setBlockPickerDialogOpen(true),
          }}
          columns={columns}
          data={fields}
          defaultValues={defaultValues}
        />
        <CatalogPickerDialog
          onSelect={handleAppendCatalogArticle}
          isOpen={articlePickerDialogOpen}
          onOpenChange={setArticlePickerDialogOpen}
        />

        <BlocksPickerDialog
          onSelect={handleAppendBlock}
          isOpen={blockPickerDialogOpen}
          onOpenChange={setBlockPickerDialogOpen}
        />
      </div>
    );
  }

  return (
    <ResizablePanelGroup
      direction='horizontal'
      autoSaveId='uecko.quotes.details_layout'
      className='items-stretch h-full'
    >
      <ResizablePanel
        defaultSize={defaultLayout[0]}
        collapsedSize={navCollapsedSize}
        collapsible={true}
        minSize={50}
        maxSize={90}
        onCollapse={() => {
          setIsCollapsed(true);
        }}
        onExpand={() => {
          setIsCollapsed(false);
        }}
        className={cn(isCollapsed && "min-w-[50px] transition-all duration-300 ease-in-out")}
      >
        <QuoteItemsSortableDataTable
          actions={fieldActions}
          columns={columns}
          data={fields}
          defaultValues={defaultValues}
        />
      </ResizablePanel>
      <ResizableHandle withHandle className='mx-3' />
      <ResizablePanel defaultSize={defaultLayout[1]} minSize={10}>
        <DataTableProvider syncWithLocation={false}>
          <CatalogPickerDataTable onSelect={handleAppendCatalogArticle} />
        </DataTableProvider>
      </ResizablePanel>
    </ResizablePanelGroup>
  );
};
