import React from 'react';
import {
  FormField,
  FormItem,
  FormLabel,
  FormControl,
  FormMessage,
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import {
  Popover,
  PopoverTrigger,
  PopoverContent,
} from '@/components/ui/popover';
import {
  Command,
  CommandInput,
  CommandEmpty,
  CommandGroup,
  CommandItem,
} from '@/components/ui/command';
import { DropIcon } from '@/components/common/forms/DropIcon';
import { Control } from 'react-hook-form';
import { VC_COMMISSION_TYPE } from '@/constants';
import { UnknownRecord } from '@/types';
import { Textarea } from '@/components/ui/textarea';

interface EditableCommissionFieldsRowProps {
  index: number;
  name: string;
  control: Control<any>;
  instanceSelected: UnknownRecord;
  records: any[];
  popoverOpenStates: boolean[];
  handlePopoverOpenChange: (index: any, open: boolean) => void;
  handleTuitionFeesOnChange: (index: number, value: string) => void;
  handleCommissionTypeOnChange: (index: number, value: string) => void;
  handleCommissionPercentageOnChange: (index: number, value: string) => void;
  getValues: (name: string) => any;
  handleCommissionAmountOnChange: (index: number, value: string) => void;
  handleMaCommissionPercentageOnChange: (index: number, value: string) => void;
  handleMaCommissionAmountOnChange: (index: number, value: string) => void;
  differenceReasons: any[];
  enquiryType?: string;
}

export const EditableCommissionFieldsRow: React.FC<
  EditableCommissionFieldsRowProps
> = ({
  index,
  name,
  control,
  instanceSelected,
  records,
  popoverOpenStates,
  handlePopoverOpenChange,
  handleTuitionFeesOnChange,
  handleCommissionTypeOnChange,
  handleCommissionPercentageOnChange,
  getValues,
  handleCommissionAmountOnChange,
  handleMaCommissionPercentageOnChange,
  handleMaCommissionAmountOnChange,
  differenceReasons,
  enquiryType,
}) => {
  return (
    <>
      <div 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, String(value));
                      return;
                    }

                    if (isValid || value === '') {
                      field.onChange(String(value));
                      handleTuitionFeesOnChange(index, String(value));
                    }
                  }}
                  onBlur={field.onBlur}
                />
              </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>
                Commission Type
              </FormLabel>
              <Popover
                open={
                  popoverOpenStates[`${index}-commission_type` as any] || false
                }
                onOpenChange={(open) =>
                  handlePopoverOpenChange(`${index}-commission_type`, open)
                }
                modal
              >
                <PopoverTrigger asChild>
                  <Button
                    className="w-full text-left flex justify-between button-text-length"
                    variant="outline"
                    aria-expanded={
                      popoverOpenStates[`${index}-commission_type` as any]
                    }
                  >
                    <span>
                      {
                        VC_COMMISSION_TYPE.find(
                          (item) =>
                            String(item.id) === String(field.value || ''),
                        )?.name
                      }
                    </span>
                    <DropIcon />
                  </Button>
                </PopoverTrigger>
                <PopoverContent className="p-0 select-picker-widget-popover">
                  <Command>
                    <CommandInput placeholder="Search 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}-commission_type` as any,
                              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>
                  Commission %
                </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 Commission Percentage"
                    value={String(field.value || '')}
                    onChange={(e) => {
                      const value = e.target.value;
                      if (value === '') {
                        field.onChange('');
                        handleCommissionPercentageOnChange(index, '');
                        return;
                      }

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

                      let isValid = false;

                      /** FIXED AMOUNT */
                      if (enqType === '1') {
                        // Max 14 digits + optional .00
                        const fixedRegex = /^\d{0,9}(\.\d{0,2})?$/;
                        isValid = fixedRegex.test(value);
                      }

                      /** PERCENTAGE */
                      if (enqType === '2') {
                        // 0–100 with max 2 decimals
                        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(`${name}.${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>Commission 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 Commission Amount"
                    value={String(field.value || '')}
                    onChange={(e) => {
                      if (!isEditable) return;
                      const value = e.target.value;

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

                      let isValid = false;

                      /** FIXED AMOUNT */
                      if (enqType === '1') {
                        // Max 14 digits + optional .00
                        const fixedRegex = /^\d{0,9}(\.\d{0,2})?$/;
                        isValid = fixedRegex.test(value);
                      }

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

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

        {enquiryType !== '2' && (
          <FormField
            control={control}
            name={`${name}.${index}.difference`}
            render={({ field }) => {
              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>Difference
                  </FormLabel>
                  <div className="country-tag">
                    {instanceSelected.currency ??
                      records[0]?.commission_currency}
                  </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 Difference"
                      value={String(field.value || '0')}
                      onChange={(e) => {
                        if (/^\d*\.?\d*$/.test(String(e.target.value))) {
                          field.onChange(String(e.target.value));
                        }
                      }}
                      readOnly
                      onBlur={field.onBlur}
                    />
                  </FormControl>
                  <FormMessage className="min-h-[20px]" />
                </FormItem>
              );
            }}
          />
        )}

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

      <div className="flex flex-row items-start gap-4 mt-4">
        {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,
                                );
                              }}
                            >
                              <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;

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

                          let isValid = false;

                          /** FIXED AMOUNT */
                          if (enqType === '1') {
                            // Max 14 digits + optional .00
                            const fixedRegex = /^\d{0,9}(\.\d{0,2})?$/;
                            isValid = fixedRegex.test(value);
                          }

                          /** PERCENTAGE */
                          if (enqType === '2') {
                            // 0–100 with max 2 decimals
                            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(`${name}.${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(`${name}.${index}.ma_commission_type`) ||
                              '',
                          );

                          let isValid = false;

                          /** FIXED AMOUNT */
                          if (enqType === '1') {
                            // Max 14 digits + optional .00
                            const fixedRegex = /^\d{0,9}(\.\d{0,2})?$/;
                            isValid = fixedRegex.test(value);
                          }

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

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

        {enquiryType === '2' && (
          <FormField
            control={control}
            name={`${name}.${index}.difference`}
            render={({ field }) => {
              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>Difference
                  </FormLabel>
                  <div className="country-tag">
                    {instanceSelected.currency ??
                      records[0]?.commission_currency}
                  </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 Difference"
                      value={String(field.value || '0')}
                      onChange={(e) => {
                        if (/^\d*\.?\d*$/.test(String(e.target.value))) {
                          field.onChange(String(e.target.value));
                        }
                      }}
                      readOnly
                      onBlur={field.onBlur}
                    />
                  </FormControl>
                  <FormMessage className="min-h-[20px]" />
                </FormItem>
              );
            }}
          />
        )}

        {enquiryType === '2' && (
          <FormField
            control={control}
            name={`${name}.${index}.difference_reason_id`}
            render={({ field }) => (
              <FormItem className="w-full">
                <FormLabel className="font-bold">
                  <span className="text-red-600 pl-1">*</span>
                  Difference Reason
                </FormLabel>
                <Popover
                  open={
                    popoverOpenStates[`${index}-difference_reason_id` as any] ||
                    false
                  }
                  onOpenChange={(open) =>
                    handlePopoverOpenChange(
                      `${index}-difference_reason_id`,
                      open,
                    )
                  }
                  modal
                >
                  <PopoverTrigger asChild>
                    <Button
                      className="w-full text-left flex justify-between button-text-length"
                      variant="outline"
                      aria-expanded={
                        popoverOpenStates[
                          `${index}-difference_reason_id` as any
                        ]
                      }
                    >
                      <span>
                        {differenceReasons.find(
                          (item) =>
                            String(item.id) === String(field.value || ''),
                        )?.name || 'Choose Difference Reason'}
                      </span>
                      <DropIcon />
                    </Button>
                  </PopoverTrigger>
                  <PopoverContent className="p-0 select-picker-widget-popover">
                    <Command>
                      <CommandInput placeholder="Search Difference Reason..." />
                      <CommandEmpty>No record found</CommandEmpty>
                      <CommandGroup>
                        {differenceReasons.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}-difference_reason_id` as any,
                                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>
      <div className="flex flex-row items-start gap-4 mt-4">
        <FormField
          control={control}
          name={`${name}.${index}.remarks`}
          render={({ field }) => (
            <FormItem className="w-full rounded-full">
              <FormLabel className="no-error-styles font-bold">
                <span className="text-red-600 pl-1">*</span>Remarks
              </FormLabel>
              <FormControl className="input-pl-50">
                <Textarea
                  {...field}
                  placeholder="Type remarks here."
                  rows={4}
                  value={field.value || ''}
                  onChange={field.onChange}
                />
              </FormControl>
              <FormMessage className="min-h-[20px]" />
            </FormItem>
          )}
        />
      </div>
    </>
  );
};
