import { Description, FieldGroup, Fieldset, Legend } from "@repo/rdx-ui/components";
import { Badge } from "@repo/shadcn-ui/components";
import { ReceiptIcon } from "lucide-react";
import { ComponentProps } from 'react';
import { useFormContext, useWatch } from "react-hook-form";
import { useTranslation } from "../../i18n";
import { InvoiceFormData } from "../../schemas";

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

  const taxes = useWatch({
    control,
    name: "taxes",
    defaultValue: [],
  });

  console.log(getValues());

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

  const displayTaxes = taxes || [];

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

      <Description>{t("form_groups.tax_resume.description")}</Description>
      <FieldGroup className='grid grid-cols-1'>
        <div className='space-y-3'>
          {displayTaxes.map((tax, index) => (
            <div key={`${tax.tax_code}-${index}`} className='border rounded-lg p-3 space-y-2'>
              <div className='flex items-center justify-between mb-2 '>
                <Badge variant='secondary' className='text-xs'>
                  {tax.tax_label}
                </Badge>
              </div>
              <div className='space-y-2 text-sm'>
                <div className='flex justify-between'>
                  <span className='text-muted-foreground'>Base para el impuesto:</span>
                  <span className='font-medium tabular-nums'>{formatCurrency(tax.taxable_amount)}</span>
                </div>
                <div className='flex justify-between'>
                  <span className='text-muted-foreground'>Importe de impuesto:</span>
                  <span className='font-medium text-primary tabular-nums'>
                    {formatCurrency(tax.taxes_amount)}
                  </span>
                </div>
              </div>
            </div>
          ))}

          {displayTaxes.length === 0 && (
            <div className='text-center py-6 text-muted-foreground'>
              <ReceiptIcon className='h-8 w-8 mx-auto mb-2 opacity-50' />
              <p className='text-sm'>No hay impuestos aplicados</p>
            </div>
          )}
        </div>
      </FieldGroup>
    </Fieldset>
  );
};
