import { Description, FieldGroup, Fieldset, Legend } from "@repo/rdx-ui/components";
import { Input, Label, Separator } from "@repo/shadcn-ui/components";
import { CalculatorIcon } from "lucide-react";
import { ComponentProps } from 'react';
import { Controller, useFormContext } from "react-hook-form";
import { useTranslation } from "../../i18n";
import { InvoiceFormData } from "../../schemas";

export const InvoiceTotals = (props: ComponentProps<"fieldset">) => {
  const { t } = useTranslation();
  const { control, getValues } = useFormContext<InvoiceFormData>();

  //const invoiceFormData = useWatch({ control });

  /*const [invoice, setInvoice] = useState({
    items: [],
    subtotal_amount: 0,
    discount_percentage: 0,
    discount_amount: 0,
    taxable_amount: 0,
    taxes_amount: 0,
    total_amount: 0,
  });

  const updateDiscount = (value: number) => {
    const subtotal = getValues('items.reduce(
      (sum: number, item: any) => sum + item.subtotal_amount,
      0
    );
    const discountAmount = (subtotal * value) / 100;
    const taxableAmount = subtotal - discountAmount;
    const taxesAmount = taxableAmount * 0.21; // Mock calculation
    const totalAmount = taxableAmount + taxesAmount;

    setInvoice({
      ...invoice,
      subtotal_amount: subtotal,
      discount_percentage: value,
      discount_amount: discountAmount,
      taxable_amount: taxableAmount,
      taxes_amount: taxesAmount,
      total_amount: totalAmount,
    });
  };*/

  const formatCurrency = (amount: number) => {
    return new Intl.NumberFormat("es-ES", {
      style: "currency",
      currency: "EUR",
      minimumFractionDigits: 2,
      maximumFractionDigits: 2,
    }).format(amount);
  };

  return (
    <Fieldset {...props}>
      <Legend className='flex items-center gap-2 text-foreground'>
        <CalculatorIcon className='size-5' /> {t("form_groups.totals.title")}
      </Legend>

      <Description>{t("form_groups.totals.description")}</Description>
      <FieldGroup className='grid grid-cols-1'>
        <div className='space-y-3'>
          <div className='flex justify-between items-center'>
            <Label className='text-sm text-muted-foreground'>Subtotal</Label>
            <span className='font-medium tabular-nums'>{formatCurrency(getValues('subtotal_amount'))}</span>
          </div>

          <div className='flex justify-between items-center gap-4'>
            <Label className='text-sm text-muted-foreground'>Descuento (%)</Label>
            <div className='flex items-center gap-2'>
              <Controller
                control={control}
                name={"discount_percentage"}
                render={({
                  field, fieldState
                }) => (<Input
                  readOnly={false}
                  value={field.value}
                  onChange={field.onChange}
                  disabled={fieldState.isValidating}
                  onBlur={field.onBlur}
                  className='w-20 text-right'
                />)}
              />
            </div>
          </div>

          <div className='flex justify-between items-center'>
            <Label className='text-sm text-muted-foreground'>Importe del descuento</Label>
            <span className='font-medium text-destructive tabular-nums'>
              -{formatCurrency(getValues("discount_amount"))}
            </span>
          </div>

          <Separator />

          <div className='flex justify-between items-center'>
            <Label className='text-sm text-muted-foreground'>Base imponible</Label>
            <span className='font-medium tabular-nums'>{formatCurrency(getValues('taxable_amount'))}</span>
          </div>

          <div className='flex justify-between items-center'>
            <Label className='text-sm text-muted-foreground'>Total de impuestos</Label>
            <span className='font-medium tabular-nums'>{formatCurrency(getValues('taxes_amount'))}</span>
          </div>

          <Separator />

          <div className='flex justify-between items-center'>
            <Label className='text-lg font-semibold'>Total de la factura</Label>
            <span className='text-xl font-bold text-primary tabular-nums'>
              {formatCurrency(getValues('total_amount'))}
            </span>
          </div>
        </div>
      </FieldGroup>
    </Fieldset>
  );
};
