import React from 'react';
import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  FormField,
  FormItem,
  FormControl,
  FormMessage,
  FormLabel,
} from '@/components/ui/form';
import { Control, FieldValues, UseFormSetValue } from 'react-hook-form';
import { formatDate } from '@/utils/decorators';
import { VC_COMMISSION_TYPE } from '@/constants';
import { EnquiryResponses } from '../forms/operations';
import { Input } from '@/components/ui/input';
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from '@/components/ui/popover';
import { Button } from '@/components/ui/button';
import { DropIcon } from '@/components/common/forms/DropIcon';
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
} from '@/components/ui/command';
import { EditableCommissionFieldsRow } from './EditableCommissionFieldsRow';
import { UnknownRecord } from '@/types';
import { Separator } from '@/components/ui/separator';

interface CommissionData {
  tuition_fees: string;
  tuition_fees_currency: string;
  commission_type: string;
  commission_percentage: string;
  commission_amount: string;
  commission_currency: string;
  response: string;
  commission_date: string;
  response_reason: string;
  difference: string;
  difference_reason: string;
  remarks: string;
  ma_commission_type: string;
  ma_commission_percentage: string;
  ma_commission_amount: string;
  response_reason_id: string;
}

interface CommissionInfoTableProps {
  commissionData: CommissionData;
  index: number;
  control: Control<any>;
  name: string;
  disabled?: boolean;
  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;
  differenceReasons: any[];
  handleDateMask: (value: string) => string;
  setCaseCardResponses: any;
  caseCardResponses: any;
  reasons: UnknownRecord[];
  setValue: UseFormSetValue<FieldValues>;
  enquiryType: string;
}

export default function CommissionInfoTable({
  commissionData,
  index,
  control,
  name,
  disabled = false,
  instanceSelected,
  records,
  popoverOpenStates,
  handlePopoverOpenChange,
  handleTuitionFeesOnChange,
  handleCommissionTypeOnChange,
  handleCommissionPercentageOnChange,
  getValues,
  handleCommissionAmountOnChange,
  differenceReasons,
  handleDateMask,
  setCaseCardResponses,
  caseCardResponses,
  reasons,
  setValue,
  enquiryType,
}: CommissionInfoTableProps) {
  const formatCurrency = (value: string) => {
    const num = parseFloat(value);
    return isNaN(num)
      ? '0.00'
      : num.toLocaleString('en-US', {
          minimumFractionDigits: 2,
          maximumFractionDigits: 2,
        });
  };

  return (
    <Card className="w-full">
      <CardContent className="space-y w-full">
        <div className="space-y-4">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead className="w-[200px]">Commission Received</TableHead>
                <TableHead className="w-[180px]">Commission Type</TableHead>
                <TableHead className="w-[150px]">Commission %</TableHead>
                <TableHead className="w-[180px]">Commission Amt.</TableHead>
                {enquiryType !== '2' && (
                  <TableHead className="w-[130px]">Response</TableHead>
                )}
                {enquiryType !== '2' && (
                  <TableHead className="w-[130px]">Date</TableHead>
                )}
              </TableRow>
            </TableHeader>
            <TableBody>
              <TableRow>
                <TableCell className="font-medium">
                  <div className="flex items-center gap-1">
                    <span>{formatCurrency(commissionData.tuition_fees)}</span>
                    <Badge variant="secondary" className="text-xs">
                      {commissionData.tuition_fees_currency || 'USD'}
                    </Badge>
                  </div>
                </TableCell>

                <TableCell>
                  <div className="space-y-1">
                    <div className="font-medium">
                      {String(
                        VC_COMMISSION_TYPE.find(
                          (item) =>
                            String(item.id) ===
                            String(commissionData.commission_type || ''),
                        )?.name || '',
                      )}
                    </div>
                  </div>
                </TableCell>

                <TableCell className="font-medium">
                  {commissionData.commission_percentage
                    ? `${commissionData.commission_percentage}%`
                    : '-'}
                </TableCell>

                <TableCell className="font-medium">
                  <div className="flex items-center gap-1">
                    <span>
                      {formatCurrency(commissionData.commission_amount)}
                    </span>
                    <Badge variant="secondary" className="text-xs">
                      {commissionData.commission_currency || 'USD'}
                    </Badge>
                  </div>
                </TableCell>

                {/* {enquiryType === '2' && (
                  <>
                    <TableCell>
                      <div className="space-y-1">
                        <div className="font-medium">
                          {String(
                            VC_COMMISSION_TYPE.find(
                              (item) =>
                                String(item.id) ===
                                String(commissionData.ma_commission_type || ''),
                            )?.name || '',
                          )}
                        </div>
                      </div>
                    </TableCell>
                    <TableCell className="font-medium">
                      {commissionData.commission_percentage
                        ? `${commissionData.ma_commission_percentage}%`
                        : '-'}
                    </TableCell>
                    <TableCell className="font-medium">
                      <div className="flex items-center gap-1">
                        <span>
                          {formatCurrency(commissionData.ma_commission_amount)}
                        </span>
                        <Badge variant="secondary" className="text-xs">
                          {commissionData.commission_currency || 'USD'}
                        </Badge>
                      </div>
                    </TableCell>
                  </>
                )} */}

                {enquiryType !== '2' && (
                  <TableCell>
                    {commissionData.response_reason_id !== '' ? (
                      <div className="font-medium">
                        {String(
                          EnquiryResponses.find(
                            (item) =>
                              String(item.id) ===
                              String(commissionData.response_reason_id || ''),
                          )?.name || '',
                        )}
                      </div>
                    ) : (
                      <FormField
                        control={control}
                        name={`${name}.${index}.response_reason_id`}
                        render={({ field }) => (
                          <FormItem className="w-full">
                            <Popover
                              open={
                                popoverOpenStates[
                                  `${index}-response_reason_id` as any
                                ] || false
                              }
                              onOpenChange={(open) =>
                                handlePopoverOpenChange(
                                  `${index}-response_reason_id`,
                                  open,
                                )
                              }
                              modal
                            >
                              <PopoverTrigger asChild>
                                <Button
                                  className="w-full text-left flex justify-between button-text-length"
                                  variant="outline"
                                  aria-expanded={
                                    popoverOpenStates[
                                      `${index}-response_reason_id` as any
                                    ]
                                  }
                                >
                                  <span>
                                    {EnquiryResponses.find(
                                      (item) =>
                                        String(item.id) ===
                                        String(field.value || ''),
                                    )?.name || 'Choose Response'}
                                  </span>
                                  <DropIcon />
                                </Button>
                              </PopoverTrigger>
                              <PopoverContent className="p-0 select-picker-widget-popover">
                                <Command>
                                  <CommandInput placeholder="Search Response..." />
                                  <CommandEmpty>No record found</CommandEmpty>
                                  <CommandGroup>
                                    {EnquiryResponses.map((item) => (
                                      <CommandItem
                                        key={`${field.name}-${item.id}`}
                                        className="cursor-pointer single-select-option"
                                        value={String(item.id)}
                                        searchValue={item.name}
                                        onSelect={() => {
                                          field.onChange(String(item.id));
                                          handlePopoverOpenChange(
                                            `${index}-response_reason_id`,
                                            false,
                                          );
                                          setCaseCardResponses((prev: any) => ({
                                            ...prev,
                                            [`${name}.${index}`]: item,
                                          }));
                                        }}
                                      >
                                        <span
                                          className={
                                            String(item.id) ===
                                            String(field.value)
                                              ? 'font-semibold'
                                              : ''
                                          }
                                        >
                                          {item.name}
                                        </span>
                                      </CommandItem>
                                    ))}
                                  </CommandGroup>
                                </Command>
                              </PopoverContent>
                            </Popover>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                    )}
                  </TableCell>
                )}

                {enquiryType !== '2' && (
                  <TableCell>
                    {commissionData.response !== '' ? (
                      <Badge variant="secondary" className="text-xs">
                        {commissionData.commission_date
                          ? formatDate(
                              commissionData.commission_date,
                              'DD-MM-YYYY',
                            )
                          : '-'}
                      </Badge>
                    ) : (
                      <FormField
                        control={control}
                        name={`${name}.${index}.commission_date`}
                        render={({ field }) => (
                          <FormItem className="space-y-2 w-full rounded-full">
                            <FormControl className="input-pl-50">
                              <Input
                                {...field}
                                type="text"
                                inputMode="numeric"
                                maxLength={10}
                                placeholder="DD/MM/YYYY"
                                className="rounded-full border-gray-600 shadow-none focus-within:shadow-none hover:shadow-none focus:shadow-none"
                                value={field.value || ''}
                                onChange={(e) => {
                                  const maskedValue = handleDateMask(
                                    e.target.value,
                                  );
                                  field.onChange(maskedValue);
                                }}
                              />
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                    )}
                  </TableCell>
                )}
              </TableRow>
            </TableBody>
          </Table>
        </div>

        <div className="space-y-4 mt-2">
          <Table>
            <TableHeader>
              <TableRow>
                {enquiryType === '2' && (
                  <>
                    <TableHead className="w-[180px]">(MA) Comm. Type</TableHead>
                    <TableHead className="w-[150px]">(MA) Comm. %</TableHead>
                    <TableHead className="w-[180px]">(MA) Comm. Amt.</TableHead>
                  </>
                )}
                {enquiryType === '2' && (
                  <TableHead className="w-[130px]">Response</TableHead>
                )}
                {enquiryType === '2' && (
                  <TableHead className="w-[130px]">Date</TableHead>
                )}
              </TableRow>
            </TableHeader>
            <TableBody>
              <TableRow>
                {enquiryType === '2' && (
                  <>
                    <TableCell>
                      <div className="space-y-1">
                        <div className="font-medium">
                          {String(
                            VC_COMMISSION_TYPE.find(
                              (item) =>
                                String(item.id) ===
                                String(commissionData.ma_commission_type || ''),
                            )?.name || '',
                          )}
                        </div>
                      </div>
                    </TableCell>
                    <TableCell className="font-medium">
                      {commissionData.commission_percentage
                        ? `${commissionData.ma_commission_percentage}%`
                        : '-'}
                    </TableCell>
                    <TableCell className="font-medium">
                      <div className="flex items-center gap-1">
                        <span>
                          {formatCurrency(commissionData.ma_commission_amount)}
                        </span>
                        <Badge variant="secondary" className="text-xs">
                          {commissionData.commission_currency || 'USD'}
                        </Badge>
                      </div>
                    </TableCell>
                  </>
                )}

                {enquiryType === '2' && (
                  <TableCell>
                    {commissionData.response !== '' ? (
                      <div className="font-medium">
                        {String(
                          EnquiryResponses.find(
                            (item) =>
                              String(item.id) ===
                              String(commissionData.response || ''),
                          )?.name || '',
                        )}
                      </div>
                    ) : (
                      <FormField
                        control={control}
                        name={`${name}.${index}.response`}
                        render={({ field }) => (
                          <FormItem className="w-full">
                            <Popover
                              open={
                                popoverOpenStates[`${index}-response` as any] ||
                                false
                              }
                              onOpenChange={(open) =>
                                handlePopoverOpenChange(
                                  `${index}-response`,
                                  open,
                                )
                              }
                              modal
                            >
                              <PopoverTrigger asChild>
                                <Button
                                  className="w-full text-left flex justify-between button-text-length"
                                  variant="outline"
                                  aria-expanded={
                                    popoverOpenStates[
                                      `${index}-response` as any
                                    ]
                                  }
                                >
                                  <span>
                                    {EnquiryResponses.find(
                                      (item) =>
                                        String(item.id) ===
                                        String(field.value || ''),
                                    )?.name || 'Choose Response'}
                                  </span>
                                  <DropIcon />
                                </Button>
                              </PopoverTrigger>
                              <PopoverContent className="p-0 select-picker-widget-popover">
                                <Command>
                                  <CommandInput placeholder="Search Response..." />
                                  <CommandEmpty>No record found</CommandEmpty>
                                  <CommandGroup>
                                    {EnquiryResponses.map((item) => (
                                      <CommandItem
                                        key={`${field.name}-${item.id}`}
                                        className="cursor-pointer single-select-option"
                                        value={String(item.id)}
                                        searchValue={item.name}
                                        onSelect={() => {
                                          field.onChange(String(item.id));
                                          handlePopoverOpenChange(
                                            `${index}-response`,
                                            false,
                                          );
                                          setCaseCardResponses((prev: any) => ({
                                            ...prev,
                                            [`${name}.${index}`]: item,
                                          }));
                                        }}
                                      >
                                        <span
                                          className={
                                            String(item.id) ===
                                            String(field.value)
                                              ? 'font-semibold'
                                              : ''
                                          }
                                        >
                                          {item.name}
                                        </span>
                                      </CommandItem>
                                    ))}
                                  </CommandGroup>
                                </Command>
                              </PopoverContent>
                            </Popover>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                    )}
                  </TableCell>
                )}

                {enquiryType === '2' && (
                  <TableCell>
                    {commissionData.response !== '' ? (
                      <Badge variant="secondary" className="text-xs">
                        {commissionData.commission_date
                          ? formatDate(
                              commissionData.commission_date,
                              'DD-MM-YYYY',
                            )
                          : '-'}
                      </Badge>
                    ) : (
                      <FormField
                        control={control}
                        name={`${name}.${index}.commission_date`}
                        render={({ field }) => (
                          <FormItem className="space-y-2 w-full rounded-full">
                            <FormControl className="input-pl-50">
                              <Input
                                {...field}
                                type="text"
                                inputMode="numeric"
                                maxLength={10}
                                placeholder="DD/MM/YYYY"
                                className="rounded-full border-gray-600 shadow-none focus-within:shadow-none hover:shadow-none focus:shadow-none"
                                value={field.value || ''}
                                onChange={(e) => {
                                  const maskedValue = handleDateMask(
                                    e.target.value,
                                  );
                                  field.onChange(maskedValue);
                                }}
                              />
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                    )}
                  </TableCell>
                )}
              </TableRow>
            </TableBody>
          </Table>
          {(String(commissionData.response) === '2' ||
            String(commissionData.response) === '3') && (
            <Table>
              <TableBody>
                {String(commissionData.response) === '2' && (
                  <TableRow>
                    <TableCell className="font-medium w-1/4">
                      <div className="flex items-center gap-1 text-muted-foreground">
                        <span>Difference : </span>
                        <Badge variant="secondary" className="text-xs">
                          {formatCurrency(commissionData.difference)}{' '}
                          {commissionData.tuition_fees_currency || 'USD'}
                        </Badge>
                      </div>
                    </TableCell>
                    <TableCell className="font-medium w-1/4">
                      <div className="flex items-center gap-1 text-muted-foreground">
                        <span>
                          Reason:{' '}
                          <Badge variant="secondary" className="text-xs">
                            {commissionData.difference_reason}
                          </Badge>
                        </span>
                      </div>
                    </TableCell>
                    <TableCell className="font-medium w-2/4">
                      <div className="flex items-center gap-1 text-muted-foreground">
                        <span>
                          Remarks:{' '}
                          <Badge variant="secondary" className="text-xs">
                            {commissionData.remarks}
                          </Badge>
                        </span>
                      </div>
                    </TableCell>
                  </TableRow>
                )}
                {String(commissionData.response) === '3' && (
                  <TableRow>
                    <TableCell className="font-medium">
                      <div className="flex items-center gap-1 text-muted-foreground">
                        <span>
                          Rejected Reason:{' '}
                          <Badge variant="secondary" className="text-xs">
                            {commissionData.response_reason}
                          </Badge>
                        </span>
                      </div>
                    </TableCell>
                  </TableRow>
                )}
              </TableBody>
            </Table>
          )}
        </div>

        {(caseCardResponses[`${name}.${index}` as any]?.id === '2' ||
          caseCardResponses[`${name}.${index}` as any]?.id === '3') && (
          <Separator className="mb-20 mt-5" />
        )}

        {caseCardResponses[`${name}.${index}` as any]?.id === '2' && (
          <EditableCommissionFieldsRow
            index={index}
            name={name}
            control={control}
            instanceSelected={instanceSelected}
            records={records}
            popoverOpenStates={popoverOpenStates}
            handlePopoverOpenChange={handlePopoverOpenChange}
            handleTuitionFeesOnChange={handleTuitionFeesOnChange}
            handleCommissionTypeOnChange={handleCommissionTypeOnChange}
            handleCommissionPercentageOnChange={
              handleCommissionPercentageOnChange
            }
            getValues={getValues}
            handleCommissionAmountOnChange={handleCommissionAmountOnChange}
            differenceReasons={differenceReasons}
            enquiryType={enquiryType}
          />
        )}
        {caseCardResponses[`${name}.${index}` as any]?.id === '3' && (
          <div className="flex flex-row items-end gap-4">
            <FormField
              control={control}
              name={`${name}.${index}.response_reason_id`}
              render={({ field }) => (
                <FormItem className="w-1/3">
                  <FormLabel className="font-bold">
                    <span className="text-red-600 pl-1">*</span>
                    Response Reason
                  </FormLabel>
                  <Popover
                    open={
                      popoverOpenStates[`${index}-response_reason_id` as any] ||
                      false
                    }
                    onOpenChange={(open) =>
                      handlePopoverOpenChange(
                        `${index}-response_reason_id`,
                        open,
                      )
                    }
                    modal
                  >
                    <PopoverTrigger asChild>
                      <Button
                        className="w-full text-left flex justify-between button-text-length"
                        variant="outline"
                        aria-expanded={
                          popoverOpenStates[
                            `${index}-response_reason_id` as any
                          ]
                        }
                      >
                        <span>
                          {reasons.find(
                            (item) =>
                              String(item.id) === String(field.value || ''),
                          )?.name || 'Choose Response Reason'}
                        </span>
                        <DropIcon />
                      </Button>
                    </PopoverTrigger>
                    <PopoverContent className="p-0 select-picker-widget-popover">
                      <Command>
                        <CommandInput placeholder="Search Response Reason..." />
                        <CommandEmpty>No record found</CommandEmpty>
                        <CommandGroup>
                          {reasons.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}-response_reason_id`,
                                  false,
                                );
                              }}
                            >
                              <span
                                className={
                                  String(item.id) === String(field.value)
                                    ? 'font-semibold'
                                    : ''
                                }
                              >
                                {item.name}
                              </span>
                            </CommandItem>
                          ))}
                        </CommandGroup>
                      </Command>
                    </PopoverContent>
                  </Popover>
                  <FormMessage />
                </FormItem>
              )}
            />
          </div>
        )}
      </CardContent>
    </Card>
  );
}
