'use client';

import React, { useCallback, useEffect, useRef, useState } from 'react';
import { Card, CardContent } from '@/components/ui/card';
import {
  FormField,
  FormItem,
  FormLabel,
  FormControl,
  FormMessage,
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from '@/components/ui/popover';
import { Button } from '@/components/ui/button';
import { DropIcon } from '@/components/common/forms/DropIcon';
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
} from '@/components/ui/command';
import TaxSection from '@/components/common/TaxSection';
import { ApiResponse, UnknownRecord } from '@/types';
import { Text } from '@/components/ui/text';
import { Controller, FieldValues, UseFormSetValue } from 'react-hook-form';
import { calculateAmount } from '@/components/visa-commission/bonus/sub-agent/constants';
import { API_ENDPOINTS } from '@/constants';
import { globalApiGet } from '@/services/global';
import { FileUploadField } from '../../contracts/forms/FileUploadField';
import { ATTACHMENT_VALIDATION_COMMON } from '@/constants/attachment';

interface CommissionReceivedDetailsProps {
  control: any;
  instanceSelected: any;
  records: any[];
  totalCommission: string | number;
  handleDateMask: (value: string) => string;
  popoverOpenStates: boolean[];
  handlePopoverOpenChange: (index: any, open: boolean) => void;
  getValues: (name: string) => any;
  setValue: UseFormSetValue<FieldValues>;
  setError: any;
  clearErrors: any;
  fileManager?: any;
}

const CommissionReceivedDetails: React.FC<CommissionReceivedDetailsProps> = ({
  control,
  instanceSelected,
  records,
  totalCommission,
  handleDateMask,
  handlePopoverOpenChange,
  popoverOpenStates,
  getValues,
  setValue,
  setError,
  clearErrors,
  fileManager,
}) => {
  const [totalAmount, setTotalAmount] = useState<number | string>(0);
  const [amountAfterTax, setAmountAfterTax] = useState<string | number>(0);
  const [otherDeduction, setOtherDeduction] = useState<string | number>(0);
  const [netAmount, setNetAmount] = useState<string | number>(0);
  const [defaultPaymentModes, setDefaultPaymentModes] = useState<
    UnknownRecord[]
  >([]);
  const [defaultFromBanks, setDefaultFromBanks] = useState<UnknownRecord[]>([]);
  const [paymentMode, setPaymentMode] = useState<number | string>(0);

  const amountAfterTaxRef = useRef<number>(0);
  const otherDeductionRef = useRef<number>(0);

  const fileInputRef = useRef<HTMLInputElement | null>(null);

  const convertToInr = (currentConversionRate?: string) => {
    const conversionRate = parseFloat(
      currentConversionRate ?? getValues(`received.conversion_rate`) ?? '0',
    );
    const totalAmt = parseFloat(getValues(`received.total_amount`) || '0');

    const convertedAmount = totalAmt * conversionRate;
    const total = parseFloat(convertedAmount.toFixed(2));
    setValue(`received.total_amount_inr`, String(total));
    setTotalAmount(String(total));

    const taxes = getValues(`received.taxes`);
    let totalTax = 0;
    if (taxes?.length > 0) {
      taxes.forEach((tax: any, index: number) => {
        const taxAmount = calculateAmount(tax.tax_per, convertedAmount);
        totalTax += taxAmount;
        setValue(`received.taxes.${index}.tax_amount`, taxAmount as any);
      });
      totalTax = parseFloat(totalTax.toFixed(2));
    }

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

    amountAfterTaxRef.current = afterTax;
    setAmountAfterTax(afterTax);

    const deduction = otherDeductionRef.current;
    const net = parseFloat((afterTax - deduction).toFixed(2));
    setNetAmount(net.toString());
    setValue('received.net_amount_inr', net.toString());
  };

  const handleOtherDeductionOnChange = (deduction: number | string) => {
    const deductionValue = parseFloat(String(deduction)) || 0;

    const afterTax = amountAfterTaxRef.current;

    if (deductionValue > afterTax) {
      setError('received.other_deductions', {
        type: 'manual',
        message: 'Other deductions cannot exceed the amount after tax',
      });
    } else {
      clearErrors('received.other_deductions');
    }

    const finalAmount = parseFloat((afterTax - deductionValue).toFixed(2));

    otherDeductionRef.current = deductionValue;
    setOtherDeduction(deductionValue);
    setNetAmount(finalAmount.toString());
    setValue('received.net_amount_inr', finalAmount.toString());
  };

  const handleSetAmountAfterTax = (value: string | number) => {
    const parsed = parseFloat(String(value)) || 0;
    amountAfterTaxRef.current = parsed;
    setAmountAfterTax(parsed);

    // Recalculate net with latest deduction
    const deduction = otherDeductionRef.current;
    const net = parseFloat((parsed - deduction).toFixed(2));
    setNetAmount(net.toString());
    setValue('received.net_amount_inr', net.toString());
  };

  const currency =
    instanceSelected?.currency ?? records?.[0]?.commission_currency ?? '';

  const enquiryType = '1';

  const handleOnOpen = useCallback(async () => {
    const extractData = (response: unknown) =>
      Array.isArray(response) ? response : [];

    const apiRequests = [
      globalApiGet(API_ENDPOINTS.SUB_AGENT_BONUS.PAYMENT_MODE_LIST),
      globalApiGet(API_ENDPOINTS.SUB_AGENT_BONUS.FROM_BANK_LIST),
    ];

    try {
      const [paymentModesRes, fromBanksRes] = (await Promise.all(
        apiRequests,
      )) as ApiResponse<UnknownRecord>[];

      setDefaultPaymentModes(extractData(paymentModesRes));
      setDefaultFromBanks(extractData(fromBanksRes));
    } catch (error) {
      console.error('Error loading data:', error);
      setDefaultPaymentModes([]);
      setDefaultFromBanks([]);
    }
  }, [enquiryType]);

  useEffect(() => {
    handleOnOpen();
  }, []);

  return (
    <Card className="space-y-1 pt-4 pb-4">
      <div className="flex justify-between flex-strip-line pl-6 pr-6 mb-4">
        <div>Record Commission Received</div>
      </div>

      <CardContent className="space-y-4">
        <div className="flex flex-col md:flex-row lg:flex-row items-start gap-4">
          <FormField
            control={control}
            name="received.total_amount"
            render={({ field }) => (
              <FormItem className="space-y-2 w-full rounded-full count-set">
                <FormLabel className="no-error-styles font-bold">
                  <span className="text-red-600 pl-1">*</span>Total Amount in{' '}
                  {currency}
                </FormLabel>
                <div className="country-tag">{currency}</div>
                <FormControl className="input-pl-50">
                  <Input
                    type="text"
                    readOnly
                    placeholder="Enter Total Commission"
                    value={String(field.value || '')}
                    onBlur={field.onBlur}
                    className="rounded-full border-gray-600 shadow-none focus:shadow-none"
                  />
                </FormControl>
                <FormMessage className="min-h-[20px]" />
              </FormItem>
            )}
          />

          <FormField
            control={control}
            name="received.conversion_rate"
            render={({ field }) => (
              <FormItem className="space-y-2 w-full rounded-full">
                <FormLabel className="no-error-styles font-bold">
                  <span className="text-red-600 pl-1">*</span>Conversion Rate
                </FormLabel>
                <FormControl className="input-pl-50">
                  <Input
                    type="text"
                    placeholder="Enter Conversion Rate"
                    value={String(field.value || '')}
                    onChange={(e) => {
                      const value = e.target.value;
                      if (value === '') {
                        field.onChange('');
                        convertToInr('0');
                        return;
                      }
                      const fixedRegex = /^\d{0,4}(\.\d{0,2})?$/;
                      if (fixedRegex.test(value)) {
                        field.onChange(value);

                        convertToInr(value);
                      }
                    }}
                    onBlur={field.onBlur}
                    className="rounded-full border-gray-600 shadow-none focus:shadow-none"
                  />
                </FormControl>
                <FormMessage className="min-h-[20px]" />
              </FormItem>
            )}
          />

          <FormField
            control={control}
            name="received.total_amount_inr"
            render={({ field }) => (
              <FormItem className="space-y-2 w-full rounded-full count-set">
                <FormLabel className="no-error-styles font-bold">
                  <span className="text-red-600 pl-1">*</span>Converted to INR
                </FormLabel>
                <div className="country-tag">INR</div>
                <FormControl className="input-pl-50">
                  <Input
                    type="text"
                    placeholder="Enter Total Amount INR"
                    value={String(field.value || '')}
                    onChange={(e) => {
                      const value = String(e.target.value);
                      if (value === '') return field.onChange('');
                      if (/^\d*\.?\d*$/.test(value)) {
                        field.onChange(value);
                      }
                    }}
                    readOnly
                    onBlur={field.onBlur}
                    className="rounded-full border-gray-600 shadow-none focus:shadow-none"
                  />
                </FormControl>
                <FormMessage className="min-h-[20px]" />
              </FormItem>
            )}
          />
        </div>

        <div className="flex flex-col md:flex-row items-start">
          <Text className="flex flex-wrap p-2 pl-0 pr-0 form-mid mt-0 z-10 w-full">
            <TaxSection
              control={control}
              name="received.taxes"
              record={{}}
              totalAmount={totalAmount}
              amountAfterTax={amountAfterTax}
              setAmountAfterTax={handleSetAmountAfterTax}
              otherDeduction={otherDeduction}
              setNetAmount={setNetAmount}
            />
          </Text>
        </div>

        <div className="flex flex-col md:flex-row items-start gap-4">
          <FormField
            control={control}
            name="received.other_deductions"
            render={({ field }) => (
              <FormItem className="space-y-2 w-1/4 rounded-full">
                <FormLabel className="no-error-styles font-bold">
                  Other Deductions
                </FormLabel>
                <FormControl className="input-pl-50">
                  <Input
                    type="text"
                    placeholder="Enter Other Deductions"
                    value={String(field.value || '')}
                    onBlur={field.onBlur}
                    className="rounded-full border-gray-600 shadow-none focus:shadow-none"
                    onChange={(e) => {
                      const value = String(e.target.value);
                      if (value === '') {
                        field.onChange('');
                        handleOtherDeductionOnChange(0);
                        return;
                      }
                      const fixedRegex = /^\d{0,13}(\.\d{0,2})?$/;
                      if (fixedRegex.test(value)) {
                        field.onChange(value);

                        handleOtherDeductionOnChange(value);
                      }
                    }}
                  />
                </FormControl>
                <FormMessage className="min-h-[20px]" />
              </FormItem>
            )}
          />

          <FormField
            control={control}
            name="received.deduction_reason"
            render={({ field }) => (
              <FormItem className="space-y-2 w-3/4 rounded-full">
                <FormLabel className="no-error-styles font-bold">
                  Deduction Reason
                </FormLabel>
                <FormControl className="input-pl-50">
                  <Input
                    type="text"
                    placeholder="Enter Other Deductions"
                    value={String(field.value || '')}
                    onBlur={field.onBlur}
                    className="rounded-full border-gray-600 shadow-none focus:shadow-none"
                    onChange={(e) => {
                      field.onChange(e.target.value);
                    }}
                  />
                </FormControl>
                <FormMessage className="min-h-[20px]" />
              </FormItem>
            )}
          />
        </div>

        <div className="flex flex-col md:flex-row items-start">
          <FormField
            control={control}
            name="received.net_amount_inr"
            render={({ field }) => (
              <FormItem className="space-y-2 w-1/4 p-2 rounded-full">
                <FormLabel className="no-error-styles font-bold">
                  <span className="text-red-600 pl-1">*</span>Total Amount in
                  INR
                </FormLabel>
                <FormControl className="input-pl-50">
                  <Input
                    type="text"
                    readOnly
                    placeholder="Enter Net Amount in INR"
                    value={String(netAmount || field.value || '')}
                    onBlur={field.onBlur}
                    className="rounded-full border-gray-600 shadow-none focus:shadow-none"
                  />
                </FormControl>
                <FormMessage className="min-h-[20px]" />
              </FormItem>
            )}
          />

          <FormField
            control={control}
            name={`received.payment_date`}
            render={({ field }) => (
              <FormItem className="space-y-2 w-1/4 p-2 rounded-full">
                <FormLabel className="no-error-styles font-bold">
                  <span className="text-red-600 pl-1">*</span>
                  Payment Date
                </FormLabel>
                <FormControl className="input-pl-50">
                  <Input
                    {...field}
                    type="text"
                    inputMode="numeric"
                    maxLength={10}
                    placeholder="DD/MM/YYYY"
                    className="rounded-full border-gray-600 shadow-none focus-within:shadow-none hover:shadow-none focus:shadow-none"
                    value={field.value || ''}
                    onChange={(e) => {
                      const maskedValue = handleDateMask(e.target.value);
                      field.onChange(maskedValue);
                    }}
                  />
                </FormControl>
                <FormMessage className="min-h-[20px]" />
              </FormItem>
            )}
          />

          <FormField
            control={control}
            name={`received.payment_mode_id`}
            render={({ field }) => (
              <FormItem className="space-y-2 w-1/4 p-2 rounded-full">
                <FormLabel className="font-bold">
                  <span className="text-red-600 pl-1">*</span>
                  Mode of Payment
                </FormLabel>
                <Popover
                  open={popoverOpenStates[`payment_mode_id` as any] || false}
                  onOpenChange={(open) =>
                    handlePopoverOpenChange(`payment_mode_id`, open)
                  }
                  modal
                >
                  <PopoverTrigger asChild>
                    <Button
                      className="w-full text-left flex justify-between button-text-length"
                      variant="outline"
                      aria-expanded={
                        popoverOpenStates[`payment_mode_id` as any]
                      }
                    >
                      <span>
                        {defaultPaymentModes.find(
                          (item) =>
                            String(item.id) === String(field.value || ''),
                        )?.name || 'Choose Mode of Payment'}
                      </span>
                      <DropIcon />
                    </Button>
                  </PopoverTrigger>
                  <PopoverContent className="p-0 select-picker-widget-popover">
                    <Command>
                      <CommandInput placeholder="Search Mode of Payment..." />
                      <CommandEmpty>No record found</CommandEmpty>
                      <CommandGroup>
                        {defaultPaymentModes.map((item) => (
                          <CommandItem
                            key={`${field.name}-${item.id}`}
                            className="cursor-pointer single-select-option"
                            value={String(item.id)}
                            searchValue={item.name}
                            onSelect={() => {
                              field.onChange(String(item.id));
                              handlePopoverOpenChange(`payment_mode_id`, false);
                              setPaymentMode(String(item.id));
                            }}
                          >
                            <span
                              className={
                                String(item.id) === String(field.value)
                                  ? 'font-semibold'
                                  : ''
                              }
                            >
                              {item.name}
                            </span>
                          </CommandItem>
                        ))}
                      </CommandGroup>
                    </Command>
                  </PopoverContent>
                </Popover>
                <FormMessage className="min-h-[20px]" />
              </FormItem>
            )}
          />

          {paymentMode !== '1' && (
            <FormField
              control={control}
              name={`received.bank_account_id`}
              render={({ field }) => (
                <FormItem className="space-y-2 w-1/4 p-2 rounded-full">
                  <FormLabel className="font-bold">
                    <span className="text-red-600 pl-1">*</span>
                    Bank Account
                  </FormLabel>
                  <Popover
                    open={popoverOpenStates[`bank_account_id` as any] || false}
                    onOpenChange={(open) =>
                      handlePopoverOpenChange(`bank_account_id`, open)
                    }
                    modal
                  >
                    <PopoverTrigger asChild>
                      <Button
                        className="w-full text-left flex justify-between button-text-length"
                        variant="outline"
                        aria-expanded={
                          popoverOpenStates[`bank_account_id` as any]
                        }
                      >
                        <span>
                          {defaultFromBanks.find(
                            (item) =>
                              String(item.id) === String(field.value || ''),
                          )?.name || 'Choose Bank Account'}
                        </span>
                        <DropIcon />
                      </Button>
                    </PopoverTrigger>
                    <PopoverContent className="p-0 select-picker-widget-popover">
                      <Command>
                        <CommandInput placeholder="Search Bank Account..." />
                        <CommandEmpty>No record found</CommandEmpty>
                        <CommandGroup>
                          {defaultFromBanks.map((item) => (
                            <CommandItem
                              key={`${field.name}-${item.id}`}
                              className="cursor-pointer single-select-option"
                              value={String(item.id)}
                              searchValue={item.name}
                              onSelect={() => {
                                field.onChange(String(item.id));
                                handlePopoverOpenChange(
                                  `bank_account_id`,
                                  false,
                                );
                              }}
                            >
                              <span
                                className={
                                  String(item.id) === String(field.value)
                                    ? 'font-semibold'
                                    : ''
                                }
                              >
                                {item.name}
                              </span>
                            </CommandItem>
                          ))}
                        </CommandGroup>
                      </Command>
                    </PopoverContent>
                  </Popover>
                  <FormMessage className="min-h-[20px]" />
                </FormItem>
              )}
            />
          )}
        </div>

        {paymentMode !== '1' && (
          <div className="flex flex-col md:flex-row items-start gap-4">
            <FormField
              control={control}
              name="received.transaction_id"
              render={({ field }) => (
                <FormItem className="space-y-2 w-1/4 rounded-full">
                  <FormLabel className="no-error-styles font-bold">
                    <span className="text-red-600 pl-1">*</span>Transaction ID
                  </FormLabel>
                  <FormControl className="input-pl-50">
                    <Input
                      type="text"
                      placeholder="Enter Transaction ID"
                      value={String(field.value || '')}
                      onBlur={field.onBlur}
                      className="rounded-full border-gray-600 shadow-none focus:shadow-none"
                      onChange={(e) => {
                        field.onChange(e.target.value);
                      }}
                    />
                  </FormControl>
                  <FormMessage className="min-h-[20px]" />
                </FormItem>
              )}
            />

            <Controller
              control={control}
              name="attachment_files"
              render={({ field }) => {
                const specificFiles =
                  fileManager.filesByIndex['attachment_files'] || [];
                const dropdownOpen =
                  fileManager.dropdownsByIndex['attachment_files'] || false;

                return (
                  <FileUploadField
                    field={field}
                    label={`Transaction Screenshot (Allowed: ${ATTACHMENT_VALIDATION_COMMON.label})`}
                    acceptFileFormat={ATTACHMENT_VALIDATION_COMMON.allowedTypes
                      .map((t) => `.${t}`)
                      .join(',')}
                    maxFiles={ATTACHMENT_VALIDATION_COMMON.maxFiles}
                    maxFileSize={ATTACHMENT_VALIDATION_COMMON.maxFileSize}
                    acceptFileFormatLabel={ATTACHMENT_VALIDATION_COMMON.label}
                    files={specificFiles}
                    onFilesChange={(newFiles) => {
                      fileManager.setFilesByIndex((prev: any) => ({
                        ...prev,
                        ['attachment_files']: newFiles,
                      }));
                      field.onChange(newFiles);
                    }}
                    dropdownOpen={dropdownOpen}
                    onToggleDropdown={() =>
                      fileManager.toggleDropdown('attachment_files')
                    }
                    onRemoveFile={(fileIndex) => {
                      const updatedFiles = specificFiles.filter(
                        (_: any, index: number) => index !== fileIndex,
                      );
                      fileManager.setFilesByIndex((prev: any) => ({
                        ...prev,
                        ['attachment_files']: updatedFiles,
                      }));
                      field.onChange(updatedFiles);
                    }}
                  />
                );
              }}
            />
          </div>
        )}

        <div className="flex flex-row items-start gap-4">
          <FormField
            control={control}
            name="received.remarks"
            render={({ field }) => (
              <FormItem className="w-full rounded-full">
                <FormLabel className="no-error-styles font-bold">
                  Remarks
                </FormLabel>
                <FormControl className="input-pl-50">
                  <Textarea
                    rows={4}
                    placeholder="Type received commission remarks here."
                    value={field.value || ''}
                    onChange={field.onChange}
                  />
                </FormControl>
                <FormMessage className="min-h-[20px]" />
              </FormItem>
            )}
          />
        </div>
      </CardContent>
    </Card>
  );
};

export default CommissionReceivedDetails;
