'use client';

import React, { useState } from 'react';
import {
  Dialog,
  DialogTrigger,
  DialogContent,
  DialogTitle,
  DialogDescription,
  DialogClose,
} from '@/components/ui/dialog';
import CommonImage from '@/components/common/CommonImage';
import { Text } from '@/components/ui/text';
import { VisuallyHidden } from '@radix-ui/react-visually-hidden';
import { Button } from '@/components/ui/button';
import { UnknownRecord } from '@/types';
import { Card, CardContent } from '@/components/ui/card';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { API_ENDPOINTS, VC_COMMISSION_TYPE } from '@/constants';
import { Badge } from '@/components/ui/badge';
import { globalApiPost } from '@/services/global';
import { formatDate } from '@/utils/decorators';
import DataNotFound from '@/components/errors/DataNotFound';

interface ICommissionInfoDialog {
  record: UnknownRecord;
  enquiryType?: string;
}

const CommissionInfoDialog: React.FC<ICommissionInfoDialog> = ({
  record,
  enquiryType,
}) => {
  const [isOpen, setIsOpen] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [records, setRecords] = useState<UnknownRecord[]>([]);

  const handleOpenChange = async (open: boolean) => {
    setIsOpen(open);
    if (open) {
      setIsLoading(true);

      try {
        const res: any = await globalApiPost(
          API_ENDPOINTS.VC_ENQUIRY.COMMISSION_INFO,
          {
            association_type: Number(enquiryType),
            visa_case_id: Number(record.visa_case_id),
          },
        );
        setRecords(res ?? []);
      } catch (error) {
        console.error('Error loading dialog data:', error);
        setRecords([]);
      } finally {
        setIsLoading(false);
      }
    } else {
    }
  };

  return (
    <Dialog open={isOpen} onOpenChange={handleOpenChange}>
      <DialogTrigger asChild>
        <Button type="button" className="m-0">
          Commission Info
        </Button>
      </DialogTrigger>

      <DialogContent
        className="modal-common-widget w-full max-w-7xl p-0 m-0 table-modal-settings state-widget"
        onInteractOutside={(e) => e.preventDefault()}
        onEscapeKeyDown={(e) => e.preventDefault()}
        onClick={(e) => e.stopPropagation()}
      >
        <div className="p-5 modal-header flex justify-between items-center">
          <DialogTitle>Commission Info</DialogTitle>
          <DialogClose asChild>
            <button
              className="rounded-sm opacity-70 transition-opacity hover:opacity-100 focus:outline-none"
              aria-label="Close"
            >
              <CommonImage
                src="/main/cross-arrow.webp"
                width={15}
                height={15}
                alt="Close"
                classname="dialog-close-img"
              />
            </button>
          </DialogClose>
        </div>

        <DialogDescription className="sr-only">
          Commission information dialog
        </DialogDescription>

        <VisuallyHidden>
          <DialogTitle>Hidden Title</DialogTitle>
        </VisuallyHidden>

        {records.length === 0 ? (
          <Text>
            <DataNotFound />
          </Text>
        ) : (
          <div className="p-6">
            <div className="flex justify-between items-center mb-2 pl-4">
              <h6 className="font-semibold text-lg">
                {record?.fname} {record?.lname} - {record?.student_uid} -{' '}
                {record?.case_uid}
              </h6>
            </div>
            <div className="flex flex-wrap p-2">
              <Card className="w-full">
                <CardContent className="space-y w-full">
                  <div className="space-y-4">
                    <Table>
                      <TableHeader>
                        <TableRow>
                          <TableHead className="w-[200px]">
                            {enquiryType == '3'
                              ? 'Commission Received'
                              : 'Tuition Fees'}
                          </TableHead>
                          <TableHead className="w-[180px]">
                            Comm. Type
                          </TableHead>
                          <TableHead className="w-[150px]">Comm. %</TableHead>
                          <TableHead className="w-[180px]">
                            Comm. Amt.
                          </TableHead>
                          {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>
                            </>
                          )}
                          <TableHead className="w-[150px]">Date</TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {records?.length > 0
                          ? records.map((row: UnknownRecord, index: number) => (
                              <TableRow key={index}>
                                <TableCell className="font-medium">
                                  <div className="flex items-center gap-1">
                                    <span>{row?.tuition_fees || '-'}</span>
                                    <Badge
                                      variant="secondary"
                                      className="text-xs"
                                    >
                                      {row?.currency || enquiryType == '3'
                                        ? 'INR'
                                        : 'USD'}
                                    </Badge>
                                  </div>
                                </TableCell>

                                <TableCell>
                                  <div className="font-medium">
                                    {String(
                                      VC_COMMISSION_TYPE.find(
                                        (item) =>
                                          String(item.id) ===
                                          String(
                                            row?.our_commission_type || '',
                                          ),
                                      )?.name || '-',
                                    )}
                                  </div>
                                </TableCell>

                                <TableCell className="font-medium">
                                  {row?.our_commission_percentage !==
                                    undefined &&
                                  row?.our_commission_percentage !== '' &&
                                  row?.our_commission_percentage !== null &&
                                  Number(row?.our_commission_percentage) > 0
                                    ? `${row.our_commission_percentage}%`
                                    : '-'}
                                </TableCell>

                                <TableCell className="font-medium">
                                  <div className="flex items-center gap-1">
                                    <span>
                                      {row?.our_commission_amount || '-'}
                                    </span>
                                    <Badge
                                      variant="secondary"
                                      className="text-xs"
                                    >
                                      {row?.currency || enquiryType == '3'
                                        ? 'INR'
                                        : 'USD'}
                                    </Badge>
                                  </div>
                                </TableCell>

                                {enquiryType == '2' && (
                                  <>
                                    <TableCell>
                                      <div className="font-medium">
                                        {String(
                                          VC_COMMISSION_TYPE.find(
                                            (item) =>
                                              String(item.id) ===
                                              String(
                                                row?.ma_commission_type || '',
                                              ),
                                          )?.name || '-',
                                        )}
                                      </div>
                                    </TableCell>

                                    <TableCell className="font-medium">
                                      {row?.ma_commission_percentage !==
                                        undefined &&
                                      row?.ma_commission_percentage !== '' &&
                                      row?.ma_commission_percentage !== null
                                        ? `${row.ma_commission_percentage}%`
                                        : '-'}
                                    </TableCell>

                                    <TableCell className="font-medium">
                                      <div className="flex items-center gap-1">
                                        <span>
                                          {row?.ma_commission_amount || '-'}
                                        </span>
                                        {row?.ma_commission_amount && (
                                          <Badge
                                            variant="secondary"
                                            className="text-xs"
                                          >
                                            {row?.currency || 'USD'}
                                          </Badge>
                                        )}
                                      </div>
                                    </TableCell>
                                  </>
                                )}

                                <TableCell className="font-medium">
                                  {row?.created
                                    ? formatDate(row.created, 'DD-MM-YYYY')
                                    : '-'}
                                </TableCell>
                              </TableRow>
                            ))
                          : null}
                      </TableBody>
                    </Table>
                  </div>
                </CardContent>
              </Card>
            </div>
          </div>
        )}
      </DialogContent>
    </Dialog>
  );
};

export default CommissionInfoDialog;
