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 { API_ENDPOINTS, 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 { globalApiPost } from '@/services/global';
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,
  filterEligibleCases,
}: {
  instanceSelected: UnknownRecord;
  control: Control<FieldValues>;
  name?: FieldArrayPath<FieldValues>;
  records: any[];
  enquiryType: string;
  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));
    async function fetchStudentTuitionFees() {
      const ids = records.map((record) => {
        return record.visa_case_id ?? record.id;
      });

      let fees: any = [];

      if (ids.length > 0) {
        fees = await globalApiPost(API_ENDPOINTS.VC_ENQUIRY.TUITION_FEES, {
          commission_instance: instanceSelected.instance_no ?? '1',
          visa_case_ids: ids,
        });
      }

      if (records?.length) {
        const maCommissionType = getValues(`ma_commission_type`);
        const maCommissionAmount = getValues(`ma_commission_amount`);
        const maCommissionPercentage = getValues(`ma_commission_percentage`);
        replace(
          records.map((rec) => ({
            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: String(rec.id),
            commission_currency:
              rec.commission_currency ?? String(instanceSelected.currency),
            tuition_fees_currency:
              rec.tuition_fees_currency ?? String(instanceSelected.currency),
            tuition_fees:
              rec.tuition_fees ??
              String(
                fees.find(
                  (item: UnknownRecord) => item.ol_visa_case_id === rec.id,
                )?.oli_instance_fee || '',
              ),
            commission_type: rec.commission_type
              ? String(rec.commission_type)
              : String(instanceSelected.commission_type || ''),
            commission_percentage: rec.commission_percentage ?? '',
            commission_amount:
              rec.commission_amount ??
              (instanceSelected.commission_type === '1' ||
              instanceSelected.commission_type === 1
                ? String(instanceSelected.commission_amount)
                : String(
                    calculateCommission(
                      String(instanceSelected.commission_amount || ''),
                      String(
                        fees.find(
                          (item: UnknownRecord) =>
                            item.ol_visa_case_id === rec.id,
                        )?.oli_instance_fee || '',
                      ),
                    ) || '',
                  ) || ''),
            ma_commission_type:
              (rec.ma_commission_type as string) ??
              String(maCommissionType || ''),
            ma_commission_percentage:
              rec.ma_commission_percentage ??
              String(maCommissionPercentage || ''),
            ma_commission_amount:
              (rec.ma_commission_amount ?? (maCommissionType as string) === '1')
                ? String(rec.ma_commission_amount || maCommissionAmount || '')
                : String(
                    calculateCommission(
                      String(
                        rec.ma_commission_percentage ||
                          maCommissionPercentage ||
                          '',
                      ),
                      String(
                        fees.find(
                          (item: UnknownRecord) =>
                            item.ol_visa_case_id === rec.id,
                        )?.oli_instance_fee || '',
                      ),
                    ) || '',
                  ),
          })),
        );
      }
    }
    fetchStudentTuitionFees();
  }, [records, fields.length, replace, instanceSelected.instance_no]);

  const handleTuitionFeesOnChange = (index: number, value: string) => {
    const tuitionFees = Number(value || 0);

    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'
          ? Number(getValues(`items.${index}.ma_commission_amount`) || 0)
          : calculateCommission(
              String(
                getValues(`items.${index}.ma_commission_percentage`) || '',
              ),
              tuitionFees,
            );

      setValue(`items.${index}.ma_commission_amount`, String(maAmount || 0));

      calculateOurCommission(index);
    }
  };

  const calculateOurCommission = (index: number, percentage?: string) => {
    const commissionType = String(
      getValues(`items.${index}.commission_type`) || '',
    );

    // Our commission must be Percentage
    if (commissionType !== '2') return;

    const tuitionFees = Number(getValues(`items.${index}.tuition_fees`) || 0);

    const maType = String(getValues(`items.${index}.ma_commission_type`) || '');

    const maPercentage = Number(
      getValues(`items.${index}.ma_commission_percentage`) || 0,
    );

    const maAmount = Number(
      getValues(`items.${index}.ma_commission_amount`) || 0,
    );

    const ourPercentage = Number(
      percentage ?? getValues(`items.${index}.commission_percentage`) ?? 0,
    );

    if (tuitionFees <= 0 || ourPercentage <= 0 || maAmount <= 0) {
      setValue(`items.${index}.commission_amount`, '0');
      return;
    }

    // Only validate MA %
    if (maType === '2' && maPercentage <= 0) {
      setValue(`items.${index}.commission_amount`, '0');
      return;
    }

    const amount = ((maAmount * ourPercentage) / 100).toFixed(2);

    setValue(`items.${index}.commission_amount`, amount);
  };

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

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

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

      return;
    }

    calculateOurCommission(index, value);
  };

  const handleMaCommissionPercentageOnChange = (
    index: number,
    value: string,
  ) => {
    const tuitionFees = Number(getValues(`items.${index}.tuition_fees`) || 0);

    const maAmount = calculateCommission(value, tuitionFees);

    setValue(`items.${index}.ma_commission_amount`, String(maAmount || 0));

    calculateOurCommission(index);
  };

  const calculateCommission = (
    percentage: string | number,
    tuitionFees: string | number,
  ) => {
    const fee = Number(tuitionFees);
    const per = Number(percentage);

    if (
      !Number.isFinite(fee) ||
      !Number.isFinite(per) ||
      fee <= 0 ||
      per <= 0
    ) {
      return 0;
    }

    return Number(((fee * per) / 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={enquiryType}
                />{' '}
              </div>
            </div>
            <CardContent className="flex flex-row items-start gap-4">
              <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> Tuition Fees
                    </FormLabel>
                    <div className="country-tag">
                      {instanceSelected.currency ??
                        records[0]?.commission_currency}
                    </div>
                    <FormControl className="input-pl-50">
                      <Input
                        type="text"
                        className="rounded-full border-gray-600 shadow-none focus-within:shadow-none hover:shadow-none focus:shadow-none"
                        placeholder="Enter Tuition Fees"
                        value={String(field.value || '')}
                        onChange={(e) => {
                          const value = e.target.value;
                          const fixedRegex = /^\d{0,9}(\.\d{0,2})?$/;
                          let isValid = false;
                          isValid = fixedRegex.test(value);

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

                          if (isValid || value === '') {
                            field.onChange(String(value));
                            handleTuitionFeesOnChange(index, String(value));
                          }
                        }}
                        onBlur={field.onBlur}
                      />
                    </FormControl>
                    <FormMessage className="min-h-[20px]" />
                  </FormItem>
                )}
              />

              {enquiryType === '2' && (
                <>
                  <FormField
                    control={control}
                    name={`${name}.${index}.ma_commission_type`}
                    render={({ field }) => (
                      <FormItem className="w-full">
                        <FormLabel className="font-bold">
                          <span className="text-red-600 pl-1">*</span>
                          (Ma) Comm. Type
                        </FormLabel>
                        <Popover
                          open={
                            popoverOpenStates[`ma-${index}` as any] || false
                          }
                          onOpenChange={(open) =>
                            handlePopoverOpenChange(`ma-${index}` as any, open)
                          }
                          modal
                        >
                          <PopoverTrigger asChild>
                            <Button
                              className="w-full text-left flex justify-between button-text-length"
                              variant="outline"
                              aria-expanded={
                                popoverOpenStates[`ma-${index}` as any]
                              }
                            >
                              <span>
                                {VC_COMMISSION_TYPE.find(
                                  (item) =>
                                    String(item.id) ===
                                    String(field.value || ''),
                                )?.name || 'Select (Ma) Comm. Type'}
                              </span>
                              <DropIcon />
                            </Button>
                          </PopoverTrigger>
                          <PopoverContent className="p-0 select-picker-widget-popover">
                            <Command>
                              <CommandInput
                                placeholder={`Search (Ma) Comm. 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(
                                        `ma-${index}` as any,
                                        false,
                                      );
                                      handleMaCommissionTypeOnChange(
                                        index,
                                        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>
                    )}
                  />

                  {String(
                    getValues(`items.${index}.ma_commission_type`) || '',
                  ) === '2' && (
                    <FormField
                      control={control}
                      name={`${name}.${index}.ma_commission_percentage`}
                      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>
                            (Ma) Comm. Per
                          </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 (Ma) Comm. Per"
                              value={String(field.value || '')}
                              onChange={(e) => {
                                const value = e.target.value;
                                if (value === '') {
                                  field.onChange('');
                                  handleMaCommissionPercentageOnChange(
                                    index,
                                    '',
                                  );
                                  return;
                                }

                                const enqType = String(
                                  getValues(
                                    `items.${index}.ma_commission_type`,
                                  ) || '',
                                );

                                let isValid = false;

                                if (enqType === '1') {
                                  const fixedRegex = /^\d{0,9}(\.\d{0,2})?$/;
                                  isValid = fixedRegex.test(value);
                                }

                                if (enqType === '2') {
                                  const percentRegex =
                                    /^(100(\.00?)?|(\d{0,2})(\.\d{0,2})?)$/;
                                  isValid =
                                    percentRegex.test(value) &&
                                    Number(value) <= 100;
                                }

                                if (isValid || value === '') {
                                  field.onChange(String(value));
                                  handleMaCommissionPercentageOnChange(
                                    index,
                                    String(value),
                                  );
                                }
                              }}
                              onBlur={field.onBlur}
                            />
                          </FormControl>
                          <FormMessage className="min-h-[20px]" />
                        </FormItem>
                      )}
                    />
                  )}

                  <FormField
                    control={control}
                    name={`${name}.${index}.ma_commission_amount`}
                    render={({ field }) => {
                      const isEditable =
                        String(
                          getValues(`items.${index}.ma_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> (Ma)
                            Comm. Amt
                          </FormLabel>
                          <div className="country-tag">
                            {instanceSelected.currency ??
                              records[0]?.commission_currency}
                          </div>
                          <FormControl className="input-pl-50">
                            <Input
                              type="text"
                              className="rounded-full border-gray-600 shadow-none focus-within:shadow-none hover:shadow-none focus:shadow-none"
                              placeholder="Enter (Ma) Comm. Amt"
                              value={String(field.value || '')}
                              onChange={(e) => {
                                if (!isEditable) return;

                                const value = e.target.value;
                                const enqType = String(
                                  getValues(
                                    `items.${index}.ma_commission_type`,
                                  ) || '',
                                );

                                let isValid = false;

                                if (enqType === '1') {
                                  const fixedRegex = /^\d{0,9}(\.\d{0,2})?$/;
                                  isValid = fixedRegex.test(value);
                                }

                                if (enqType === '2') {
                                  const percentRegex =
                                    /^(100(\.00?)?|(\d{0,2})(\.\d{0,2})?)$/;
                                  isValid =
                                    percentRegex.test(value) &&
                                    Number(value) <= 100;
                                }

                                if (isValid || value === '') {
                                  field.onChange(String(value));
                                }
                                calculateOurCommission(index);
                              }}
                              onBlur={field.onBlur}
                              readOnly={!isEditable}
                              style={{
                                backgroundColor: !isEditable
                                  ? '#f5f5f5'
                                  : 'white',
                                cursor: !isEditable ? 'not-allowed' : 'text',
                              }}
                            />
                          </FormControl>
                          <FormMessage className="min-h-[20px]" />
                        </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'
                        ? 'Our Comm. Type'
                        : `Our 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'
                                  ? 'Our Comm. Type'
                                  : 'Our Commission Type'
                              }`}
                          </span>
                          <DropIcon />
                        </Button>
                      </PopoverTrigger>
                      <PopoverContent className="p-0 select-picker-widget-popover">
                        <Command>
                          <CommandInput
                            placeholder={`Search ${
                              enquiryType === '2'
                                ? 'Our Comm. Type'
                                : 'Our 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 className="min-h-[20px]" />
                  </FormItem>
                )}
              />

              {String(getValues(`items.${index}.commission_type`) || '') ===
                '2' && (
                <FormField
                  control={control}
                  name={`${name}.${index}.commission_percentage`}
                  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>
                        {enquiryType === '2'
                          ? 'Our 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'
                              ? 'Our Comm. Per'
                              : 'Commission Percentage'
                          }`}
                          value={String(field.value || '')}
                          onChange={(e) => {
                            const value = e.target.value;

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

                            const enqType = String(
                              getValues(`items.${index}.commission_type`) || '',
                            );

                            let isValid = false;

                            if (enqType === '1') {
                              const fixedRegex = /^\d{0,9}(\.\d{0,2})?$/;
                              isValid = fixedRegex.test(value);
                            }

                            if (enqType === '2') {
                              const percentRegex =
                                /^(100(\.00?)?|(\d{0,2})(\.\d{0,2})?)$/;
                              isValid =
                                percentRegex.test(value) &&
                                Number(value) <= 100;
                            }

                            if (isValid || value === '') {
                              field.onChange(String(value));
                              handleCommissionPercentageOnChange(
                                index,
                                String(value),
                              );
                            }
                          }}
                          onBlur={field.onBlur}
                        />
                      </FormControl>
                      <FormMessage className="min-h-[20px]" />
                    </FormItem>
                  )}
                />
              )}

              <FormField
                control={control}
                name={`${name}.${index}.commission_amount`}
                render={({ field }) => {
                  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'
                          ? 'Our Comm. Amt'
                          : 'Our Commission Amount'}
                      </FormLabel>
                      <div className="country-tag">
                        {instanceSelected.currency ??
                          records[0]?.commission_currency}
                      </div>
                      <FormControl className="input-pl-50">
                        <Input
                          type="text"
                          className="rounded-full border-gray-600 shadow-none focus-within:shadow-none hover:shadow-none focus:shadow-none"
                          placeholder={`Enter ${
                            enquiryType === '2'
                              ? 'Our Comm. Amt'
                              : 'Our Commission Amount'
                          }`}
                          value={String(field.value || '')}
                          onChange={(e) => {
                            if (!isEditable) return;
                            const value = e.target.value;

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

                            const enqType = String(
                              getValues(`items.${index}.commission_type`) || '',
                            );

                            let isValid = false;

                            if (enqType === '1') {
                              const fixedRegex = /^\d{0,9}(\.\d{0,2})?$/;
                              isValid = fixedRegex.test(value);
                            }

                            if (enqType === '2') {
                              const percentRegex =
                                /^(100(\.00?)?|(\d{0,2})(\.\d{0,2})?)$/;
                              isValid =
                                percentRegex.test(value) &&
                                Number(value) <= 100;
                            }

                            if (isValid || value === '') {
                              field.onChange(String(value));
                            }
                          }}
                          onBlur={field.onBlur}
                          readOnly={!isEditable}
                          style={{
                            backgroundColor: !isEditable ? '#f5f5f5' : 'white',
                            cursor: !isEditable ? 'not-allowed' : 'text',
                          }}
                        />
                      </FormControl>
                      <FormMessage className="min-h-[20px]" />
                    </FormItem>
                  );
                }}
              />
            </CardContent>
          </Card>
        );
      })}
    </div>
  );
}
