import React, { useEffect, useState } from 'react';
import { Card, CardContent } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import {
  useFieldArray,
  Control,
  FieldValues,
  FieldArrayPath,
  useFormContext,
} from 'react-hook-form';
import { VC_COMMISSION_TYPE } from '@/constants';
import {
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form';
import { Button } from '@/components/ui/button';
import { UnknownRecord } from '@/types';
import { Popover, PopoverTrigger } from '@radix-ui/react-popover';
import { DropIcon } from '@/components/common/forms/DropIcon';
import { PopoverContent } from '@/components/ui/popover';
import {
  Command,
  CommandEmpty,
  CommandInput,
  CommandItem,
} from '@/components/ui/command';
import { CommandGroup } from 'cmdk';
import CommissionInfoDialog from '../../common/view/CommissionInfoDialog';

interface CommissionField {
  id: string;
  case_uid: string;
  course_end_date: string;
  course_start_date: string;
  fname: string;
  lname: string;
  student_uid: string;
  visa_result_on: string;
  visa_status: string;
  tuition_fees: string;
  commission_type?: string;
  commission_amount?: string;
  commission_percentage?: string;
  ma_commission_type?: string;
  ma_commission_amount?: string;
  ma_commission_percentage?: string;
}

export default function CommissionCards({
  instanceSelected,
  control,
  name = 'items',
  records = [],
  enquiryType,
  isEdit = false,
  filterEligibleCases,
}: {
  instanceSelected: UnknownRecord;
  control: Control<FieldValues>;
  name?: FieldArrayPath<FieldValues>;
  records: any[];
  enquiryType: string;
  isEdit?: boolean;
  filterEligibleCases?: any;
}) {
  const { fields, replace } = useFieldArray({
    control,
    name,
  });
  records = filterEligibleCases;
  const { setValue, getValues } = useFormContext();

  const [popoverOpenStates, setPopoverOpenStates] = useState<boolean[]>([]);

  const handlePopoverOpenChange = (index: number, open: boolean) => {
    setPopoverOpenStates((prev) => {
      const newStates = [...prev];
      newStates[index] = open;
      return newStates;
    });
  };

  useEffect(() => {
    setPopoverOpenStates(new Array(fields.length).fill(false));
    const existingItems = getValues(name);

    if (isEdit && existingItems?.length > 0) {
      return;
    }

    if (!isEdit && existingItems?.length > 0) {
      return;
    }

    async function fetchStudentTuitionFees() {
      if (records?.length) {
        replace(
          records.map((rec: any) => ({
            case_uid: rec.case_uid,
            course_end_date: rec.course_end_date,
            course_start_date: rec.course_start_date,
            fname: rec.fname,
            id: rec.main_id ?? rec.id,
            lname: rec.lname,
            student_uid: rec.student_uid,
            visa_result_on: rec.visa_result_on,
            visa_status: rec.visa_status,
            visa_case_id: rec.visa_case_id
              ? String(rec.visa_case_id)
              : String(rec.id),
            commission_currency:
              rec.commission_currency ?? String(instanceSelected.currency),
            tuition_fees_currency:
              rec.tuition_fees_currency ?? String(instanceSelected.currency),
            tuition_fees: String(
              rec?.commission_received || rec?.tuition_fees || '',
            ),
            commission_type: rec.commission_type
              ? String(rec.commission_type)
              : instanceSelected.commission_type
                ? String(instanceSelected.commission_type)
                : '',
            commission_percentage: rec.commission_percentage ?? null,
            commission_amount:
              rec.commission_amount ??
              (String(instanceSelected.commission_type) === '1'
                ? String(instanceSelected.commission_amount)
                : String(
                    calculateCommission(
                      String(rec.commission_received ?? ''),
                      String(instanceSelected.commission_amount || ''),
                    ) || '',
                  ) || ''),
          })),
        );
      }
    }
    fetchStudentTuitionFees();
  }, [records, fields.length, replace, instanceSelected.instance_no]);

  const handleTuitionFeesOnChange = (index: number, value: string) => {
    const amount =
      String(getValues(`items.${index}.commission_type`)) === '1'
        ? String(getValues(`items.${index}.commission_amount`) || '')
        : calculateCommission(
            String(getValues(`items.${index}.commission_percentage`) || ''),
            String(value),
          );
    setValue(`items.${index}.commission_amount`, String(amount));
    if (enquiryType === '2') {
      const maAmount =
        String(getValues(`items.${index}.ma_commission_type`)) === '1'
          ? String(getValues(`items.${index}.ma_commission_amount`) || '')
          : calculateCommission(
              String(
                getValues(`items.${index}.ma_commission_percentage`) || '',
              ),
              String(value),
            );
      setValue(`items.${index}.ma_commission_amount`, String(maAmount));
    }
  };

  const handleCommissionTypeOnChange = (index: number, value: string) => {
    setValue(`items.${index}.commission_percentage`, '0');
    setValue(`items.${index}.commission_amount`, '0');
  };

  const handleMaCommissionTypeOnChange = (index: number, value: string) => {
    setValue(`items.${index}.ma_commission_percentage`, '0');
    setValue(`items.${index}.ma_commission_amount`, '0');
  };

  const handleCommissionPercentageOnChange = (index: number, value: string) => {
    setValue(
      `items.${index}.commission_amount`,
      String(
        calculateCommission(
          String(value),
          getValues(`items.${index}.tuition_fees`),
        ) || '',
      ),
    );
  };

  const calculateCommission = (percentage: string, tuitionFees: any) => {
    const commissionPercentage = parseFloat(percentage as string) || 0;
    return parseFloat(((tuitionFees * commissionPercentage) / 100).toFixed(2));
  };

  return (
    <div className="space-y-2 p-1 m-0 w-full">
      {fields.map((field, index: number) => {
        const typedField = field as CommissionField;

        return (
          <Card key={field.id} className="space-y-1 pt-4 pb-4">
            <div className="flex justify-between flex-strip-line pl-6 pr-6 mb-4">
              <div>
                {index + 1}. {typedField.fname} {typedField.lname} -{' '}
                {typedField.student_uid} - {typedField.case_uid}
              </div>
              <div>
                <CommissionInfoDialog
                  record={typedField}
                  enquiryType={'3'}
                />{' '}
              </div>
            </div>
            <CardContent className="flex flex-row items-start gap-4">
              {isEdit ? (
                <FormField
                  control={control}
                  name={`${name}.${index}.tuition_fees`}
                  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>Commission
                        Received
                      </FormLabel>
                      <div className="country-tag">{'INR'}</div>
                      <FormControl className="input-pl-50">
                        <Input
                          minLength={1}
                          maxLength={10}
                          type="text"
                          className="rounded-full border-gray-600 shadow-none focus-within:shadow-none hover:shadow-none focus:shadow-none"
                          placeholder="Enter Commission Received"
                          value={String(field.value || '')}
                          onChange={(e) => {
                            const value = e.target.value;

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

                            if (/^\d*\.?\d*$/.test(String(value))) {
                              field.onChange(String(value));
                              handleTuitionFeesOnChange(index, String(value));
                            }
                          }}
                          onBlur={field.onBlur}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              ) : (
                <FormField
                  control={control}
                  name={`${name}.${index}.tuition_fees`}
                  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>Commission
                        Received
                      </FormLabel>{' '}
                      <div className="country-tag">{'INR'}</div>
                      <FormControl className="input-pl-50">
                        <Input
                          minLength={1}
                          maxLength={10}
                          type="text"
                          className="rounded-full border-gray-600 shadow-none focus-within:shadow-none hover:shadow-none focus:shadow-none"
                          placeholder="Enter Commission Received"
                          value={String(field.value || '')}
                          onChange={(e) => {
                            const value = e.target.value;

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

                            if (/^\d*\.?\d*$/.test(String(value))) {
                              field.onChange(String(value));
                              handleTuitionFeesOnChange(index, String(value));
                            }
                          }}
                          onBlur={field.onBlur}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              )}

              <FormField
                control={control}
                name={`${name}.${index}.commission_type`}
                render={({ field }) => (
                  <FormItem className="w-full">
                    <FormLabel className="font-bold">
                      <span className="text-red-600 pl-1">*</span>
                      {enquiryType === '2' ? ' Comm. Type' : ` Commission Type`}
                    </FormLabel>
                    <Popover
                      open={popoverOpenStates[index] || false}
                      onOpenChange={(open) =>
                        handlePopoverOpenChange(index, open)
                      }
                      modal
                    >
                      <PopoverTrigger asChild>
                        <Button
                          className="w-full text-left flex justify-between button-text-length"
                          variant="outline"
                          aria-expanded={popoverOpenStates[index]}
                        >
                          <span>
                            {VC_COMMISSION_TYPE.find(
                              (item) =>
                                String(item.id) === String(field.value || ''),
                            )?.name ||
                              `Select ${
                                enquiryType === '2'
                                  ? ' Comm. Type'
                                  : ' Commission Type'
                              }`}
                          </span>
                          <DropIcon />
                        </Button>
                      </PopoverTrigger>
                      <PopoverContent className="p-0 select-picker-widget-popover">
                        <Command>
                          <CommandInput
                            placeholder={`Search ${
                              enquiryType === '2'
                                ? ' Comm. Type'
                                : ' Commission Type'
                            }...`}
                          />
                          <CommandEmpty>No record found</CommandEmpty>
                          <CommandGroup>
                            {VC_COMMISSION_TYPE.map((item) => (
                              <CommandItem
                                key={`${field.name}-${item.id}`}
                                className="cursor-pointer single-select-option"
                                value={String(field.value || '')}
                                searchValue={item.name}
                                onSelect={() => {
                                  field.onChange(String(item.id));
                                  handlePopoverOpenChange(index, false);
                                  handleCommissionTypeOnChange(
                                    index,
                                    String(item.id),
                                  );
                                }}
                              >
                                <span
                                  className={
                                    String(item.id) === String(field.value)
                                      ? 'font-semibold'
                                      : ''
                                  }
                                >
                                  {item.name}
                                </span>
                              </CommandItem>
                            ))}
                          </CommandGroup>
                        </Command>
                      </PopoverContent>
                    </Popover>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {String(getValues(`items.${index}.commission_type`) || '') ===
                '2' && (
                <FormField
                  control={control}
                  name={`${name}.${index}.commission_percentage`}
                  render={({ field: formField }) => (
                    <FormItem className="space-y-2 w-full rounded-full">
                      <FormLabel className="no-error-styles font-bold">
                        <span className="text-red-600 pl-1">*</span>
                        {enquiryType === '2'
                          ? ' Comm. Per'
                          : `Commission Percentage`}
                      </FormLabel>
                      <FormControl>
                        <Input
                          type="text"
                          inputMode="decimal"
                          className="rounded-full border-gray-600 shadow-none focus-within:shadow-none hover:shadow-none focus:shadow-none"
                          placeholder={`Enter ${
                            enquiryType === '2'
                              ? ' Comm. Per'
                              : 'Commission Percentage'
                          }`}
                          value={String(formField.value || '')}
                          onChange={(e) => {
                            const value = e.target.value;

                            if (value === '') {
                              formField.onChange('');
                              handleCommissionPercentageOnChange(index, '');
                              return;
                            }

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

                            if (regex.test(value)) {
                              const num = parseFloat(value);
                              if (num <= 100) {
                                formField.onChange(String(value));
                                handleCommissionPercentageOnChange(
                                  index,
                                  String(value),
                                );
                              }
                            }
                          }}
                          onBlur={formField.onBlur}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              )}

              <FormField
                control={control}
                name={`${name}.${index}.commission_amount`}
                render={({ field: formField }) => {
                  const isEditable =
                    String(
                      getValues(`items.${index}.commission_type`) || '',
                    ) === '1';
                  return (
                    <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>{' '}
                        {enquiryType === '2'
                          ? ' Comm. Amt'
                          : ' Commission Amount'}
                      </FormLabel>
                      <div className="country-tag">{'INR'}</div>
                      <FormControl className="input-pl-50">
                        <Input
                          minLength={1}
                          maxLength={8}
                          type="text"
                          className="rounded-full border-gray-600 shadow-none focus-within:shadow-none hover:shadow-none focus:shadow-none"
                          placeholder={`Enter ${
                            enquiryType === '2'
                              ? ' Comm. Amt'
                              : ' Commission Amount'
                          }`}
                          value={String(formField.value || '')}
                          onChange={(e) => {
                            if (!isEditable) return;
                            if (/^\d*\.?\d*$/.test(String(e.target.value))) {
                              formField.onChange(String(e.target.value));
                            }
                          }}
                          onBlur={formField.onBlur}
                          readOnly={!isEditable}
                          style={{
                            backgroundColor: !isEditable ? '#f5f5f5' : 'white',
                            cursor: !isEditable ? 'not-allowed' : 'text',
                          }}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  );
                }}
              />
            </CardContent>
          </Card>
        );
      })}
    </div>
  );
}
