import {
  Button,
  Input,
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
  Textarea,
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@repo/shadcn-ui/components";
import { ChevronDownIcon, ChevronUpIcon, CopyIcon, Plus, TrashIcon } from "lucide-react";


import { useMoney } from '@erp/core/hooks';
import { useEffect, useState } from 'react';
import { useFormContext } from 'react-hook-form';
import { useTranslation } from '../../../i18n';
import { InvoiceItemFormData } from '../../../schemas';
import { HoverCardTotalsSummary } from './hover-card-total-summary';
import { CustomItemViewProps } from "./types";

export interface TableViewProps extends CustomItemViewProps { }

export const TableView = ({ items, actions }: TableViewProps) => {
  const { t } = useTranslation();
  const { control } = useFormContext<InvoiceItemFormData>();
  const { format } = useMoney();
  const [lines, setLines] = useState<InvoiceItemFormData[]>(items);

  useEffect(() => {
    setLines(items)
  }, [items])

  // Mantiene sincronía con el formulario padre
  const updateItems = (updated: InvoiceItemFormData[]) => {
    setLines(updated);
    onItemsChange(updated);
  };

  /** 🔹 Actualiza una fila con recalculo */
  const updateItem = (index: number, patch: Partial<InvoiceItemFormData>) => {
    const newItems = [...lines];
    const merged = { ...newItems[index], ...patch };
    newItems[index] = calculateItemAmounts(merged as InvoiceItemFormData);
    updateItems(newItems);
  };

  /** 🔹 Mueve la fila hacia arriba o abajo */
  const moveItem = (index: number, direction: "up" | "down") => {
    if (
      (direction === "up" && index === 0) ||
      (direction === "down" && index === lines.length - 1)
    )
      return;

    const newItems = [...lines];
    const target = direction === "up" ? index - 1 : index + 1;
    [newItems[index], newItems[target]] = [newItems[target], newItems[index]];
    updateItems(newItems);
  };

  /** 🔹 Duplica una línea */
  const duplicateItem = (index: number) => {
    const newItems = [...lines];
    const copy = structuredClone(newItems[index]);
    newItems.splice(index + 1, 0, copy);
    updateItems(newItems);
  };

  /** 🔹 Elimina una línea */
  const removeItem = (index: number) => {
    updateItems(lines.filter((_, i) => i !== index));
  };

  /** 🔹 Añade una nueva línea vacía */
  const addNewItem = () => {
    const newItem: InvoiceItemFormData = {
      is_non_valued: false,
      description: "",
      quantity: { value: "0", scale: "2" },
      unit_amount: { value: "0", scale: "2", currency_code: "EUR" },
      discount_percentage: { value: "0", scale: "2" },
      discount_amount: { value: "0", scale: "2", currency_code: "EUR" },
      taxable_amount: { value: "0", scale: "2", currency_code: "EUR" },
      taxes_amount: { value: "0", scale: "2", currency_code: "EUR" },
      subtotal_amount: { value: "0", scale: "2", currency_code: "EUR" },
      total_amount: { value: "0", scale: "2", currency_code: "EUR" },
      tax_codes: ["iva_21"],
    };
    updateItems([...lines, calculateItemAmounts(newItem)]);
  };

  return (
    <div className="space-y-4">
      <div className="rounded-lg border border-border">
        <Table className="min-w-full">
          <TableHeader className="sticky top-0 z-20 bg-background shadow-sm">
            <TableRow className="bg-muted/30 text-xs text-muted-foreground">
              <TableHead className="w-10 text-center">#</TableHead>
              <TableHead>{t("form_fields.item.description.label")}</TableHead>
              <TableHead className="text-right w-24">{t("form_fields.item.quantity.label")}</TableHead>
              <TableHead className="text-right w-32">{t("form_fields.item.unit_amount.label")}</TableHead>
              <TableHead className="text-right w-24">{t("form_fields.item.discount_percentage.label")}</TableHead>
              <TableHead className="text-right w-32">{t("form_fields.item.tax_codes.label")}</TableHead>
              <TableHead className="text-right w-32">{t("form_fields.item.total_amount.label")}</TableHead>
              <TableHead className="w-44 text-center">{t("common.actions")}</TableHead>
            </TableRow>
          </TableHeader>

          <TableBody>
            {lines.map((item, i) => (
              <TableRow key={`item-${i}`} className="text-sm hover:bg-muted/40">
                {/* ÍNDICE */}
                <TableCell className="text-center text-muted-foreground font-mono align-text-top">
                  {i + 1}
                </TableCell>

                {/* DESCRIPCIÓN */}

                <TableCell className="align-top">
                  <Textarea
                    value={item.description}
                    onChange={(e) => updateItem(i, { description: e.target.value })}
                    placeholder="Descripción del producto o servicio…"
                    className="min-h-[2.5rem] max-h-[10rem] resize-y bg-transparent border-none shadow-none focus:bg-background
               px-2 py-0
               leading-5 overflow-y-auto"
                    aria-label={`Descripción línea ${i + 1}`}
                    spellCheck={true}
                    autoComplete="off"
                  />


                </TableCell>

                {/* CANTIDAD */}
                <TableCell className="text-right">
                  <Input
                    type="number"
                    inputMode="decimal"
                    className="text-right border-0 bg-transparent focus-visible:ring-0 px-2 py-1"
                    value={Number(item.quantity.value) / 10 ** Number(item.quantity.scale)}
                    onChange={(e) =>
                      updateItem(i, {
                        quantity: {
                          value: (
                            Number(e.target.value) * 10 ** Number(item.quantity.scale)
                          ).toString(),
                          scale: item.quantity.scale,
                        },
                      })
                    }
                    aria-label={`Cantidad línea ${i + 1}`}
                  />
                </TableCell>

                {/* PRECIO UNITARIO */}
                <TableCell className="text-right">
                  <Input
                    type="number"
                    inputMode="decimal"
                    className="text-right border-0 bg-transparent focus-visible:ring-0 px-2 py-1"
                    value={Number(item.unit_amount.value) / 10 ** Number(item.unit_amount.scale)}
                    onChange={(e) =>
                      updateItem(i, {
                        unit_amount: {
                          ...item.unit_amount,
                          value: (
                            Number(e.target.value) * 10 ** Number(item.unit_amount.scale)
                          ).toString(),
                        },
                      })
                    }
                    aria-label={`Precio unitario línea ${i + 1}`}
                  />
                </TableCell>

                {/* DESCUENTO */}
                <TableCell className="text-right">
                  <Input
                    type="number"
                    inputMode="decimal"
                    className="text-right border-0 bg-transparent focus-visible:ring-0 px-2 py-1"
                    value={
                      Number(item.discount_percentage.value) /
                      10 ** Number(item.discount_percentage.scale)
                    }
                    onChange={(e) =>
                      updateItem(i, {
                        discount_percentage: {
                          value: (
                            Number(e.target.value) *
                            10 ** Number(item.discount_percentage.scale)
                          ).toString(),
                          scale: item.discount_percentage.scale,
                        },
                      })
                    }
                    aria-label={`Descuento línea ${i + 1}`}
                  />
                </TableCell>

                <TableCell className="text-right">
                </TableCell>


                {/* TOTAL */}
                <TableCell className="text-right font-mono">
                  <HoverCardTotalsSummary item={item}>
                    <span className="cursor-help hover:text-primary transition-colors">
                      {format(item.total_amount)}
                    </span>
                  </HoverCardTotalsSummary>
                </TableCell>

                {/* ACCIONES */}
                <TableCell className="text-center">
                  <div className="flex items-center justify-center gap-1">
                    <TooltipProvider>
                      <Tooltip>
                        <TooltipTrigger asChild>
                          <Button
                            variant="ghost"
                            size="icon"
                            onClick={() => moveItem(i, "up")}
                            disabled={i === 0}
                            className="h-7 w-7"
                          >
                            <ChevronUpIcon className="size-3.5" />
                          </Button>
                        </TooltipTrigger>
                        <TooltipContent>Mover arriba</TooltipContent>
                      </Tooltip>
                    </TooltipProvider>

                    <TooltipProvider>
                      <Tooltip>
                        <TooltipTrigger asChild>
                          <Button
                            variant="ghost"
                            size="icon"
                            onClick={() => moveItem(i, "down")}
                            disabled={i === lines.length - 1}
                            className="h-7 w-7"
                          >
                            <ChevronDownIcon className="size-3.5" />
                          </Button>
                        </TooltipTrigger>
                        <TooltipContent>Mover abajo</TooltipContent>
                      </Tooltip>
                    </TooltipProvider>

                    <TooltipProvider>
                      <Tooltip>
                        <TooltipTrigger asChild>
                          <Button
                            variant="ghost"
                            size="icon"
                            onClick={() => duplicateItem(i)}
                            className="h-7 w-7"
                          >
                            <CopyIcon className="size-3.5" />
                          </Button>
                        </TooltipTrigger>
                        <TooltipContent>Duplicar línea</TooltipContent>
                      </Tooltip>
                    </TooltipProvider>

                    <TooltipProvider>
                      <Tooltip>
                        <TooltipTrigger asChild>
                          <Button
                            variant="ghost"
                            size="icon"
                            onClick={() => removeItem(i)}
                            className="h-7 w-7 text-destructive hover:text-destructive"
                          >
                            <TrashIcon className="size-3.5" />
                          </Button>
                        </TooltipTrigger>
                        <TooltipContent>Eliminar línea</TooltipContent>
                      </Tooltip>
                    </TooltipProvider>
                  </div>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </div>

      <Button
        onClick={addNewItem}
        variant="outline"
        className="w-full border-dashed bg-transparent"
        aria-label="Agregar nueva línea"
      >
        <Plus className="h-4 w-4 mr-2" />
        Agregar línea
      </Button>
    </div>
  );
}