import React, { useEffect, useState } from 'react';
import { Card, CardContent } from '@/components/ui/card';
import {
  useFieldArray,
  Control,
  FieldValues,
  FieldArrayPath,
  useFormContext,
  UseFormSetValue,
} from 'react-hook-form';
import { Button } from '@/components/ui/button';
import { UnknownRecord } from '@/types';
import CommissionInfoTable from './CommissionInfoTable';

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;
  response?: string;
  commission_date?: string;
  visa_case_id: string;
  group_index?: number;
  group_total?: number;
}

interface GroupedCommissionField extends CommissionField {
  group_index: number;
  group_total: number;
  group_id: string;
}

export default function CommissionResponseCards({
  instanceSelected,
  control,
  name = 'items',
  records = [],
  reasons,
  setValue,
  existingCommissionAmount,
  totalCommission,
  responses,
  setError,
  clearErrors,
  differenceReasons,
  isReceived,
  enquiryType,
  fileManager,
}: {
  instanceSelected: UnknownRecord;
  control: Control<FieldValues>;
  name?: FieldArrayPath<FieldValues>;
  records: any[];
  reasons: any[];
  setValue: UseFormSetValue<FieldValues>;
  existingCommissionAmount: any[];
  totalCommission: string | number;
  responses: any[];
  setError: any;
  clearErrors: any;
  differenceReasons: any[];
  isReceived: boolean;
  enquiryType: string;
  fileManager?: any;
}) {
  const { fields } = useFieldArray({
    control,
    name,
  });

  const { getValues } = useFormContext();

  const [popoverOpenStates, setPopoverOpenStates] = useState<boolean[]>([]);
  const [groupedFields, setGroupedFields] = useState<
    GroupedCommissionField[][]
  >([]);
  const [caseCardResponses, setCaseCardResponses] = useState<UnknownRecord[]>(
    [],
  );

  useEffect(() => {
    const grouped = fields.reduce(
      (groups, field) => {
        const typedField = field as CommissionField;
        const visaCaseId = typedField.visa_case_id;

        if (!groups[visaCaseId]) {
          groups[visaCaseId] = [];
        }

        groups[visaCaseId].push(typedField as GroupedCommissionField);
        return groups;
      },
      {} as Record<string, GroupedCommissionField[]>,
    );

    Object.values(grouped).forEach((group) => {
      group.forEach((field, index) => {
        field.group_index = index;
        field.group_total = group.length;
        field.group_id = field.visa_case_id;
      });
    });

    setGroupedFields(Object.values(grouped));
  }, [fields]);

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

  useEffect(() => {
    setPopoverOpenStates(new Array(fields.length).fill(false));
  }, [fields.length]);

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

    const difference = (
      Number(existingCommissionAmount[index].commission_amount) - Number(amount)
    ).toFixed(2);
    setValue(`items.${index}.difference`, String(difference));
  };

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

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

    const difference = (
      Number(existingCommissionAmount[index].commission_amount) - Number(amount)
    ).toFixed(2);
    setValue(`items.${index}.difference`, String(difference));
  };

  const handleCommissionAmountOnChange = (index: number, value: string) => {
    const difference = (
      Number(existingCommissionAmount[index].commission_amount) - Number(value)
    ).toFixed(2);
    setValue(`items.${index}.difference`, String(difference));
  };

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

  const handleDateMask = (value: string) => {
    value = value.replace(/\D/g, '');
    if (value.length > 2 && value.length <= 4) {
      value = value.slice(0, 2) + '/' + value.slice(2);
    } else if (value.length > 4) {
      value =
        value.slice(0, 2) + '/' + value.slice(2, 4) + '/' + value.slice(4, 8);
    }
    return value.slice(0, 10);
  };

  const validateDateLive = (value: string) => {
    if (!/^\d{2}\/\d{2}\/\d{4}$/.test(value)) {
      return '';
    }
    const [day, month, year] = value.split('/').map(Number);
    if (month < 1 || month > 12) return 'Invalid month (01-12)';
    if (day < 1 || day > 31) return 'Invalid day (01-31)';
    const currentYear = new Date().getFullYear();
    const previousYear = currentYear - 1;
    if (year !== currentYear && year !== previousYear) {
      return `Year must be ${previousYear} or ${currentYear}`;
    }
    const daysInMonth = new Date(year, month, 0).getDate();
    if (day > daysInMonth) return `Month ${month} has only ${daysInMonth} days`;
    return '';
  };

  const getOriginalIndex = (groupIndex: number, itemIndex: number): number => {
    let currentIndex = 0;
    for (let i = 0; i < groupIndex; i++) {
      currentIndex += groupedFields[i]?.length || 0;
    }
    return currentIndex + itemIndex;
  };

  return (
    <div className="space-y-4 p-1 m-0 w-full">
      {groupedFields.map((group, groupIndex) => {
        const firstField = group[0];

        return (
          <Card key={firstField.visa_case_id} className="space-y-1 pt-4 pb-4">
            <div className="flex justify-between flex-strip-line pl-6 pr-6 mb-4">
              <div>
                {groupIndex + 1}. {firstField.fname} {firstField.lname} -{' '}
                {firstField.student_uid} - {firstField.case_uid}
                {group.length > 1 && (
                  <span className="text-sm text-gray-500 ml-2">
                    ({group.length} record{group.length > 1 ? 's' : ''})
                  </span>
                )}
              </div>
              <div>
                <Button
                  type="button"
                  className="m-0"
                  onClick={() => alert('feature coming soon')}
                >
                  Commission Info
                </Button>{' '}
              </div>
            </div>

            <CardContent className="space-y-4">
              {group.map((field, itemIndex) => {
                const originalIndex = getOriginalIndex(groupIndex, itemIndex);

                return (
                  <div
                    key={field.id}
                    className="border-b border-gray-200 pb-4 last:border-b-0 last:pb-0"
                  >
                    <div className="w-full">
                      <CommissionInfoTable
                        commissionData={existingCommissionAmount[originalIndex]}
                        index={originalIndex}
                        control={control}
                        name={name}
                        handleDateMask={handleDateMask}
                        popoverOpenStates={popoverOpenStates}
                        handlePopoverOpenChange={handlePopoverOpenChange}
                        getValues={getValues}
                        setCaseCardResponses={setCaseCardResponses}
                        instanceSelected={instanceSelected}
                        records={records}
                        handleTuitionFeesOnChange={handleTuitionFeesOnChange}
                        handleCommissionTypeOnChange={
                          handleCommissionTypeOnChange
                        }
                        handleCommissionPercentageOnChange={
                          handleCommissionPercentageOnChange
                        }
                        handleCommissionAmountOnChange={
                          handleCommissionAmountOnChange
                        }
                        differenceReasons={differenceReasons}
                        caseCardResponses={caseCardResponses}
                        reasons={reasons}
                        setValue={setValue}
                        enquiryType={enquiryType}
                      />
                    </div>
                  </div>
                );
              })}
            </CardContent>
          </Card>
        );
      })}

      {/* {isReceived && (
        <CommissionReceivedDetails
          control={control}
          instanceSelected={instanceSelected}
          records={records}
          totalCommission={totalCommission}
          handleDateMask={handleDateMask}
          handlePopoverOpenChange={handlePopoverOpenChange}
          popoverOpenStates={popoverOpenStates}
          getValues={getValues}
          setValue={setValue}
          setError={setError}
          clearErrors={clearErrors}
          fileManager={fileManager}
        />
      )} */}
    </div>
  );
}
