import { formatCurrency } from '@erp/core';
import { Badge, FieldDescription, FieldGroup, FieldLegend, FieldSet } from '@repo/shadcn-ui/components';
import { ReceiptIcon } from "lucide-react";
import { ComponentProps } from 'react';
import { useFormContext, useWatch } from "react-hook-form";
import { useInvoiceContext } from '../../context';
import { useTranslation } from "../../i18n";
import { InvoiceFormData } from "../../schemas";

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


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

  const displayTaxes = taxes || [];

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

        <FieldDescription>{t("form_groups.tax_resume.description")}</FieldDescription>
        <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 text-base '>
                <div className='flex items-center justify-between mb-2 '>
                  <Badge variant='secondary' className='text-sm font-semibold'>
                    {tax.tax_label}
                  </Badge>
                </div>
                <div className='space-y-2 text-sm'>
                  <div className='flex justify-between'>
                    <span className='text-current'>Base para el impuesto:</span>
                    <span className='text-base text-current tabular-nums'>{formatCurrency(tax.taxable_amount, 2, currency_code, language_code)}</span>
                  </div>
                  <div className='flex justify-between'>
                    <span className='text-current font-semibold'>Importe de impuesto:</span>
                    <span className='text-base text-current font-semibold tabular-nums'>
                      {formatCurrency(tax.taxes_amount, 2, currency_code, language_code)}
                    </span>
                  </div>
                </div>
              </div>
            ))}

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