import { DataTableColumnHeader } from '@repo/rdx-ui/components';
import { InputGroup, InputGroupTextarea } from "@repo/shadcn-ui/components";
import { cn } from "@repo/shadcn-ui/lib/utils";
import type { ColumnDef } from "@tanstack/react-table";
import * as React from "react";
import { Controller, useFormContext } from "react-hook-form";
import { useInvoiceContext } from '../../../context';
import { CustomerInvoiceTaxesMultiSelect } from '../../customer-invoice-taxes-multi-select';
import { AmountInputField } from './amount-input-field';
import { HoverCardTotalsSummary } from './hover-card-total-summary';
import { ItemDataTableRowActions } from './items-data-table-row-actions';
import { PercentageInputField } from './percentage-input-field';
import { QuantityInputField } from './quantity-input-field';


export interface InvoiceItemFormData {
  id: string;                // ← mapea RHF field.id aquí
  description: string;
  quantity: number | "";
  unit_amount: number | "";
  discount_percentage: number | "";
  tax_codes: string[];
  total_amount: number | ""; // readonly calculado
}
export interface InvoiceFormData { items: InvoiceItemFormData[] }

export function useItemsColumns(): ColumnDef<InvoiceItemFormData>[] {
  const { t, readOnly, currency_code, language_code } = useInvoiceContext();
  const { control } = useFormContext<InvoiceFormData>();

  // Atención: Memoizar siempre para evitar reconstrucciones y resets de estado de tabla
  return React.useMemo<ColumnDef<InvoiceItemFormData>[]>(() => [
    {
      id: 'position',
      header: ({ column }) => (
        <DataTableColumnHeader column={column} title={"#"} className='text-center' />
      ),
      cell: ({ row }) => row.index + 1,
      enableSorting: false,
      size: 32,
    },
    {
      accessorKey: "description",
      header: ({ column }) => (
        <DataTableColumnHeader column={column} title={t("form_fields.item.description.label")} className='text-left' />
      ),
      cell: ({ row }) => (
        <Controller
          control={control}
          name={`items.${row.index}.description`}
          render={({ field }) => (
            <InputGroup>
              <InputGroupTextarea {...field}
                id={`desc-${row.original.id}`} // ← estable
                rows={1}
                aria-label={t("form_fields.item.description.label")}
                spellCheck
                readOnly={readOnly}
                // auto-grow simple
                onInput={(e) => {
                  const el = e.currentTarget;
                  el.style.height = "auto";
                  el.style.height = `${el.scrollHeight}px`;
                }}
                className={cn(
                  "min-w-[12rem] max-w-[46rem] w-full resize-none bg-transparent border-dashed transition",
                  "focus-visible:ring-2 focus-visible:ring-ring focus-visible:bg-background focus-visible:border-solid",
                  "focus:resize-y"
                )}
                data-cell-focus />
              {/*<InputGroupAddon align="block-end">
                <InputGroupText>Line 1, Column 1</InputGroupText>
                <InputGroupButton
                  variant="default"
                  className="rounded-full"
                  size="icon-xs"
                  disabled
                >
                  <ArrowUpIcon />
                  <span className="sr-only">Send</span>
                </InputGroupButton>
              </InputGroupAddon>*/}
            </InputGroup>

          )}
        />
      ),
      enableSorting: false,
      size: 480, minSize: 240, maxSize: 768,
    },
    {
      accessorKey: "quantity",
      header: ({ column }) => (
        <DataTableColumnHeader column={column} title={t("form_fields.item.quantity.label")} className='text-right' />
      ),
      cell: ({ row }) => (
        <QuantityInputField
          control={control}
          name={`items.${row.index}.quantity`}
          readOnly={readOnly}
          inputId={`qty-${row.original.id}`}
          emptyMode="blank"
          data-row-index={row.index}
          data-col-index={4}
          data-cell-focus
          className="font-base"
        />
      ),
      enableSorting: false,
      size: 52, minSize: 48, maxSize: 64,
    },
    {
      accessorKey: "unit_amount",
      header: ({ column }) => (
        <DataTableColumnHeader column={column} title={t("form_fields.item.unit_amount.label")} className='text-right' />
      ),
      cell: ({ row }) => (
        <AmountInputField
          control={control}
          name={`items.${row.index}.unit_amount`}
          readOnly={readOnly}
          inputId={`unit-${row.original.id}`}
          scale={4}
          currencyCode={currency_code}
          languageCode={language_code}
          data-row-index={row.index}
          data-col-index={5}
          data-cell-focus
          className="font-base"
        />
      ),
      enableSorting: false,
      size: 120, minSize: 100, maxSize: 160,
    },
    {
      accessorKey: "discount_percentage",
      header: ({ column }) => (
        <DataTableColumnHeader column={column} title={t("form_fields.item.discount_percentage.label")} className='text-right' />
      ),
      cell: ({ row }) => (
        <PercentageInputField
          control={control}
          name={`items.${row.index}.discount_percentage`}
          readOnly={readOnly}
          inputId={`disc-${row.original.id}`}
          scale={4}
          data-row-index={row.index}
          data-col-index={6}
          data-cell-focus
          className="font-base"
        />
      ),
      enableSorting: false,
      size: 40, minSize: 40
    },
    {
      accessorKey: "tax_codes",
      header: ({ column }) => (
        <DataTableColumnHeader column={column} title={t("form_fields.item.tax_codes.label")} />
      ),
      cell: ({ row }) => (
        <Controller
          control={control}
          name={`items.${row.index}.tax_codes`}
          render={({ field }) => (
            <CustomerInvoiceTaxesMultiSelect
              {...field}
              inputId={`tax-${row.original.id}`}
              data-row-index={row.index}
              data-col-index={7}
              data-cell-focus
            />
          )}
        />
      ),
      enableSorting: false,
      size: 240, minSize: 232, maxSize: 320,
    },
    {
      accessorKey: "total_amount",
      header: ({ column }) => (
        <DataTableColumnHeader column={column} title={t("form_fields.item.total_amount.label")} className='text-right' />
      ),
      cell: ({ row }) => (
        <HoverCardTotalsSummary rowIndex={row.index}>
          <AmountInputField
            control={control}
            name={`items.${row.index}.total_amount`}
            readOnly
            inputId={`total-${row.original.id}`}
            currencyCode={currency_code}
            languageCode={language_code}
            className="font-semibold"
          />
        </HoverCardTotalsSummary>
      ),
      enableSorting: false,
      size: 120, minSize: 100, maxSize: 160,
    },
    {
      id: "actions",
      header: ({ column }) => (
        <DataTableColumnHeader column={column} title={t("components.datatable.actions")} />
      ),
      cell: ({ row, table }) => <ItemDataTableRowActions row={row} table={table} />,
    },
  ], [t, readOnly, control, currency_code, language_code,]);
}
