import React, { useEffect } from 'react';
import { Trash2 } from 'lucide-react';
import { Card, CardContent } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import {
  useFieldArray,
  Controller,
  Control,
  FieldValues,
  FieldArrayPath,
  Path,
  FieldArray,
  ArrayPath,
  useFormContext,
} from 'react-hook-form';
import { calculateAmount } from '../visa-commission/bonus/sub-agent/constants';

// ---------------------- Types ----------------------
export interface TaxDetailItem {
  tax_name: string;
  tax_per: string;
  tax_amount: string;
}

// Define a proper form data type that includes the field array
export interface FormDataWithTaxDetails extends FieldValues {
  items: TaxDetailItem[];
}

export interface TaxDetailItemsProps<
  TFieldValues extends FormDataWithTaxDetails,
> {
  control: Control<TFieldValues>;
  name?: FieldArrayPath<TFieldValues>;
  record?: {
    actions?: TaxDetailItem[];
    [key: string]: unknown;
  };
  totalAmount: number | string;
  amountAfterTax: number | string;
  setAmountAfterTax: (param: number | string) => void;
  otherDeduction: number | string;
  setNetAmount: (param: number | string) => void;
}

// ------------------- Default Item -------------------
const defaultItem: TaxDetailItem = {
  tax_name: '',
  tax_per: '',
  tax_amount: '',
};

// ------------------- Component -------------------
export default function TaxSection<
  TFieldValues extends FormDataWithTaxDetails,
>({
  control,
  name = 'items' as FieldArrayPath<TFieldValues>,
  record,
  totalAmount,
  amountAfterTax,
  setAmountAfterTax,
  otherDeduction,
  setNetAmount,
}: TaxDetailItemsProps<TFieldValues>) {
  const { fields, append, remove, replace } = useFieldArray({
    control,
    name,
  });

  const { setValue, getValues } = useFormContext();

  type FieldArrayItem = FieldArray<TFieldValues, ArrayPath<TFieldValues>>;

  const handleTaxOnChange = (index: number, freshTaxPer?: string) => {
    const taxPercentage = parseFloat(
      freshTaxPer ?? getValues(`${name}.${index}.tax_per`) ?? '0',
    );
    const taxes = getValues(`${name}`) as Record<string, any>[];

    const calculatedTaxAmount = calculateAmount(
      taxPercentage as any,
      Number(totalAmount),
    );
    setValue(
      `${name}.${index}.tax_amount`,
      calculatedTaxAmount.toFixed(2) as any,
    );

    const totalTax = taxes.reduce((sum, tax) => {
      const taxAmt = calculateAmount(tax.tax_per, Number(totalAmount));
      return sum + (taxAmt || 0);
    }, 0);

    const afterTax = Number(totalAmount) - totalTax;
    setAmountAfterTax(afterTax.toFixed(2));

    const net = afterTax - (Number(otherDeduction) || 0);
    setNetAmount(parseFloat(net.toFixed(2)));
    setValue('net_amount_inr', net.toFixed(2));
  };

  const handleRemoveTaxOnChange = () => {
    const total = parseFloat(String(totalAmount)) || 0;

    const taxes = getValues(name) as Array<Record<string, any>>;
    let totalTax = 0;

    taxes.forEach((tax, index) => {
      const taxAmount = calculateAmount(tax.tax_per, total);
      totalTax += taxAmount;
      setValue(`${name}.${index}.tax_amount`, taxAmount as any);
    });

    const afterTax = parseFloat((total - totalTax).toFixed(2));
    setAmountAfterTax(afterTax);

    const deduction = parseFloat(String(otherDeduction)) || 0;
    const net = parseFloat((afterTax - deduction).toFixed(2));

    setNetAmount(net);
    setValue('net_amount_inr', net.toFixed(2));
  };

  // Initialize fields on first load
  useEffect(() => {
    if (Array.isArray(record?.actions) && record.actions.length > 0) {
      const fieldArrayData = record.actions.map((r: TaxDetailItem) => ({
        tax_name: r.tax_name ?? '',
        tax_per: r.tax_per ?? 0,
        tax_amount: r.tax_amount ?? 0,
      })) as FieldArrayItem[];
      replace(fieldArrayData);
    } else if (fields.length === 0) {
      //append(defaultItem as FieldArrayItem);
    }
  }, [record, append, replace, fields.length]);

  useEffect(() => {
    if (fields.length > 0) {
      fields.forEach((_, index) => {
        handleTaxOnChange(index);
      });
    }
  }, [fields.length]);

  return (
    <>
      <div className="hr-heading p-4 pl-0 pr-0 m-2 ml-0 mr-0 w-full">
        <div className="heading-widget mt-1 mb-1">
          <div className="heading ml-2">
            Total Before Tax _______________ INR {totalAmount}
          </div>
        </div>
      </div>
      <div className="space-y-2 p-1 ml-4 mr-4">
        {fields.map((fieldItem, index) => (
          <Card
            key={fieldItem.id}
            className="space-y-1 pt-4 pb-0 pl-0 pr-0 mt-2 !mb-4"
          >
            <CardContent className="flex flex-col md:flex-row items-end gap-4">
              <div className="space-y-2 w-full rounded-full">
                <label className="block text-sm font-medium mb-1">
                  Tax Name
                </label>
                <Controller
                  name={`${name}.${index}.tax_name` as Path<TFieldValues>}
                  control={control}
                  render={({ field }) => (
                    <Input {...field} placeholder="Enter tax name" />
                  )}
                />
              </div>

              <div className="space-y-2 w-full rounded-full">
                <label className="block text-sm font-medium mb-1">
                  Tax Percentage (%)
                </label>
                <Controller
                  name={`${name}.${index}.tax_per` as Path<TFieldValues>}
                  control={control}
                  render={({ field }) => (
                    <Input
                      {...field}
                      placeholder="0.00"
                      value={field.value}
                      onChange={(e) => {
                        const value = e.target.value;

                        if (value === '') {
                          field.onChange('');
                          handleTaxOnChange(index, value);
                          return;
                        }

                        const regex =
                          /^(100(\.0{0,2})?|(\d{1,2})(\.\d{0,2})?)$/;

                        if (regex.test(value)) {
                          const num = parseFloat(value);
                          if (num <= 100) {
                            field.onChange(value);
                            handleTaxOnChange(index, value);
                          }
                        }
                      }}
                    />
                  )}
                />
              </div>

              <div className="space-y-2 w-full rounded-full">
                <label className="block text-sm font-medium mb-1">
                  Tax Amount
                </label>
                <Controller
                  name={`${name}.${index}.tax_amount` as Path<TFieldValues>}
                  control={control}
                  render={({ field }) => (
                    <Input
                      {...field}
                      placeholder="Calculated amount"
                      readOnly
                    />
                  )}
                />
              </div>

              <div className="w-[20] flex justify-end">
                <Button
                  size="icon"
                  variant="destructive"
                  onClick={() => {
                    remove(index);
                    handleRemoveTaxOnChange();
                  }}
                >
                  <Trash2 className="h-4 w-4" />
                </Button>
              </div>
            </CardContent>
          </Card>
        ))}

        <Button
          type="button"
          onClick={() => append(defaultItem as FieldArrayItem)}
        >
          + Add Tax
        </Button>
      </div>
      <div className="hr-heading p-4 pl-0 pr-0 m-2 ml-0 mr-0 w-full">
        <div className="heading-widget mt-4 mb-4">
          <div className="heading ml-2">
            Amount After Tax _______________ INR {amountAfterTax ?? totalAmount}
          </div>
        </div>
      </div>
    </>
  );
}
