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,
  useFormContext,
} from 'react-hook-form';
import { calculateAmount } from '../../bonus/sub-agent/constants';

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

export interface FormDataWithTaxDetails extends FieldValues {
  tax_details: {
    taxes: TaxDetailItem[];
    net_amount_inr: string;
    payment_date: string;
    payment_mode_id: number;
    other_deductions?: string;
    deduction_reason?: string;
    from_bank_account_id?: string;
    to_bank_account_id?: string;
    transaction_id?: string;
    remarks?: string;
    [key: string]: unknown;
  };
  items?: any[];
}

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;
}

const defaultItem: TaxDetailItem = {
  tax_name: '',
  tax_per: '',
  tax_amount: '',
};

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

  const { setValue, getValues } = useFormContext();

  const handleTaxOnChange = (index: number) => {
    const taxPercentage = parseFloat(
      getValues(`${name}.${index}.tax_per`) || '0',
    );

    const calculatedTaxAmount = calculateAmount(
      taxPercentage as any,
      Number(totalAmount),
    );

    setValue(
      `${name}.${index}.tax_amount`,
      calculatedTaxAmount.toFixed(2) as any,
    );

    // Recalculate total tax
    const taxes = (getValues(name) || []) as TaxDetailItem[];
    const totalTax = taxes.reduce((sum, tax, idx) => {
      if (idx === index) {
        return sum + calculatedTaxAmount;
      }
      const taxAmt = calculateAmount(
        parseFloat(tax.tax_per || '0') as any,
        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)));
  };

  const handleRemoveTaxOnChange = () => {
    const taxes = getValues(name) as TaxDetailItem[];
    let totalTax = 0;

    taxes.forEach((tax) => {
      const taxAmount = calculateAmount(
        parseFloat(tax.tax_per || '0') as any,
        Number(totalAmount),
      );
      totalTax += taxAmount;
    });

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

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

  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',
      }));
      replace(fieldArrayData as any);
    }
  }, [record, replace]);

  useEffect(() => {
    const taxes = (getValues(name) || []) as TaxDetailItem[];
    const totalTax = taxes.reduce((sum, tax, index) => {
      const taxAmount = calculateAmount(
        parseFloat(tax.tax_per || '0') as any,
        Number(totalAmount),
      );

      setValue(`${name}.${index}.tax_amount`, taxAmount.toFixed(2) as any);
      return sum + taxAmount;
    }, 0);

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

    const net = Number((afterTax - (Number(otherDeduction) || 0)).toFixed(2));
    setNetAmount(net);
  }, [
    fields,
    getValues,
    name,
    otherDeduction,
    setAmountAfterTax,
    setNetAmount,
    setValue,
    totalAmount,
  ]);

  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;
                        field.onChange(value);
                        handleTaxOnChange(index);
                      }}
                    />
                  )}
                />
              </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
                      value={field.value || ''}
                    />
                  )}
                />
              </div>

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

        <Button type="button" onClick={() => append(defaultItem as any)}>
          + 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>
    </>
  );
}
