'use client';

import React, { ReactNode, useRef, useState } from 'react';
import CommonImage from '@/components/common/CommonImage';
import { Text } from '@/components/ui/text';
import { Button } from '@/components/ui/button';
import {
  Dialog,
  DialogTrigger,
  DialogContent,
  DialogTitle,
  DialogClose,
} from '@/components/ui/dialog';
import {
  Table,
  TableHead,
  TableHeader,
  TableBody,
  TableRow,
  TableCell,
} from '@/components/ui/table';
import { globalApiPost } from '@/services/global';
import { API_ENDPOINTS } from '@/constants';
import { BucketProp, UnknownRecord } from '@/types';
import {
  INVOICE_COMPANY,
  INVOICE_EMAIL,
  INVOICE_ENQUIRY_EMAIL,
  INVOICE_PHONE,
  INVOICE_T_N_C,
} from '@/config/site-config';
import { getMonthShortName } from '@/utils/formatDate';
import {
  CURRENCY_MAP,
  currencyToWords,
  formatAmount,
  formatDateToDDMMMYYYY,
  padWithZeros,
} from '@/utils/formatting';
import { ResponseAcceptStatuses } from '@/components/visa-commission/enquiry/forms/operations';

interface InvoicePdfButtonProps {
  record: UnknownRecord;
  bucketId: string;
}

const InvoicePdfButton: React.FC<InvoicePdfButtonProps> = ({
  record,
  bucketId,
}) => {
  const invoiceRef = useRef<HTMLDivElement>(null);
  const [isGenerating, setIsGenerating] = useState(false);
  const [isOpen, setIsOpen] = useState(false);
  const [cases, setCases] = useState<UnknownRecord[]>([]);
  const invoiceTitle = record?.invoice?.invoice_no;
  let totalAmount = 0;
  /**
   * Function to be called when dialog opens
   */
  const handleDialogOpen = async () => {
    const details = await globalApiPost(
      API_ENDPOINTS.VC_ENQUIRY.DETAILS_BY_ID,
      {
        id: String(record.id),
        association_type:
          bucketId === 'VISA_COMMISSION_INSTITUTE_ENQUIRY' ? '1' : '2',
        commission_response_status_id: true,
      },
    );

    setCases(Array.isArray(details) ? details : []);
  };

  /**
   * Handles dialog open/close state changes
   */
  const handleOpenChange = (open: boolean) => {
    setIsOpen(open);
    if (open) {
      handleDialogOpen();
    }
  };

  /**
   * Handles client-side PDF download.
   * Dynamically imports `html2pdf.js` to avoid SSR reference errors.
   */
  const handleDownload = async () => {
    if (!invoiceRef.current) return;
    setIsGenerating(true);

    try {
      // 👇 Dynamically import only on the client
      const html2pdf = (await import('html2pdf.js')).default;

      const options: any = {
        margin: [0.4, 0.2, 0.8, 0.2], // [top, left, bottom, right] in inches
        filename: `${invoiceTitle}.pdf`,
        image: { type: 'jpeg', quality: 0.98 },
        html2canvas: { scale: 2 },
        jsPDF: { unit: 'in', format: 'a4', orientation: 'portrait' },
      };

      await html2pdf().set(options).from(invoiceRef.current).save();
    } catch (error) {
      console.error('PDF generation failed:', error);
    } finally {
      setIsGenerating(false);
    }
  };

  return (
    <Dialog open={isOpen} onOpenChange={handleOpenChange}>
      <DialogTrigger asChild>
        <Button className="button-action">
          <CommonImage
            src={'/main/download-icn.webp'}
            width={15}
            height={15}
            alt={'Generate Pdf'}
            classname="info-icon"
          />
        </Button>
      </DialogTrigger>

      <DialogContent
        aria-describedby={undefined}
        className="z-[9999] w-full max-w-7xl p-0 m-0 table-modal-settings modal-common-widget pdf-view-model-widget"
        onInteractOutside={(e) => e.preventDefault()}
        onEscapeKeyDown={(e) => e.preventDefault()}
        onClick={(e) => e.stopPropagation()}
      >
        <DialogTitle className="p-5 modal-header">
          Invoice PDF Preview
        </DialogTitle>

        {/* PDF Preview Section */}
        <Text className="modal-main-container">
          <Text className="main-scroll-widget">
            <div ref={invoiceRef} className="pdf-view-ui">
              <Text className="container">
                <Text className="header-logo">
                  <img src="/main/logo-wide.png" alt="Logo" />
                </Text>
              </Text>

              <Text className="content">
                <Text className="invoice-header">
                  <Text>
                    <b>
                      (FORMERLY KNOWN AS{' '}
                      <span>
                        WESTERN OVERSEAS STUDY ABROAD PRIVATE LIMITED)
                      </span>
                    </b>
                  </Text>
                  {/* <Text>
                    <b>GSTIN – 06AABCW4521G1ZL</b>
                  </Text> */}
                  <Text>
                    <b>
                      REGISTERED OFFICE: SCF – 27-28, GROUND FLOOR – FIRST
                      FLOOR, SHOPPING COMPLEX, VIKAS VIHAR, AMBALA CITY –
                      134003, HARYANA
                    </b>
                  </Text>
                </Text>

                <h3>
                  Commission Invoice |{' '}
                  {ResponseAcceptStatuses[
                    record?.accept_status as keyof typeof ResponseAcceptStatuses
                  ] ?? 'Pending'}
                </h3>

                {/* Invoice Header */}
                <Table className="invoice-date-section">
                  <TableBody>
                    <TableRow>
                      <TableCell>
                        <b>Invoice No:</b> {invoiceTitle}
                      </TableCell>
                      <TableCell style={{ textAlign: 'right' }}>
                        <b>Date:</b> {formatDateToDDMMMYYYY(new Date())}
                      </TableCell>
                    </TableRow>
                  </TableBody>
                </Table>

                {/* From / To */}
                <Table className="invoice-date-section-from-to">
                  <TableBody>
                    <TableRow>
                      <TableCell>
                        <h5>From:</h5>
                        <Text>
                          {INVOICE_COMPANY}
                          <br />
                          {record?.branch?.address_line_1}
                          <br />
                          GST: {record?.branch?.tax_number ?? '-'}
                          <br />
                          Phone:{' '}
                          <a href={`tel:${INVOICE_PHONE}`}>{INVOICE_PHONE}</a>
                          <br />
                          Email:{' '}
                          <a href={`mailto:${INVOICE_EMAIL}`}>
                            {INVOICE_EMAIL}
                          </a>
                        </Text>
                      </TableCell>
                      <TableCell>
                        <h5>To:</h5>
                        <Text>
                          {record?.institute?.institueName}
                          <br />
                          {record?.visa_country?.name}
                          <br /> <br />{' '}
                          {/* Email:{' '}
                          <a href="mailto:finance@auckland.ac.nz">
                            finance@auckland.ac.nz
                          </a> */}
                        </Text>
                      </TableCell>
                    </TableRow>
                  </TableBody>
                </Table>

                {/* Invoice Details */}
                <Text className="commission-instance-secton">
                  <b>Country:</b> {record?.visa_country?.name} | <b>Intake:</b>{' '}
                  {getMonthShortName(record?.intake?.intakemonth, false)}{' '}
                  {record?.intake?.intakeyear} | <b>Commission Instance:</b>{' '}
                  Instance {record?.instance?.instance} | <b>Currency:</b>{' '}
                  {record?.currency}
                </Text>

                {/* Commission Table */}
                <Table className="invoice-info-secton">
                  <TableHeader>
                    <TableRow>
                      <TableHead>Sr.</TableHead>
                      <TableHead>Student - UID</TableHead>
                      <TableHead>Case ID / Course</TableHead>
                      <TableHead>Tuition Fees</TableHead>
                      <TableHead>% / Fixed</TableHead>
                      <TableHead>Comm. Amt.</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {(() => {
                      totalAmount = 0;

                      return (
                        <>
                          {cases.map((row, index) => {
                            const commissionAmount = parseFloat(
                              row.commission_amount as string,
                            );

                            totalAmount += commissionAmount;

                            return (
                              <TableRow key={row.id || index}>
                                <TableCell>{index + 1}</TableCell>

                                <TableCell>
                                  {`${row.fname} ${row.lname} - ${row.student_uid}`}
                                </TableCell>

                                <TableCell>
                                  {`${row.case_uid} / ${row.course_name}`}
                                </TableCell>

                                <TableCell>
                                  {parseFloat(
                                    row.tuition_fees as string,
                                  ).toLocaleString('en-US', {
                                    minimumFractionDigits: 2,
                                    maximumFractionDigits: 2,
                                  })}
                                </TableCell>

                                <TableCell>
                                  {(row.commission_type as string) === '2'
                                    ? `${row.commission_percentage}%`
                                    : 'Fixed'}
                                </TableCell>

                                <TableCell>
                                  {commissionAmount.toLocaleString('en-US', {
                                    minimumFractionDigits: 2,
                                    maximumFractionDigits: 2,
                                  })}
                                </TableCell>
                              </TableRow>
                            );
                          })}

                          {/* Total Row */}
                          <TableRow>
                            <TableCell
                              colSpan={5}
                              className="text-right font-bold"
                            >
                              Total
                            </TableCell>

                            <TableCell className="font-bold">
                              {totalAmount.toLocaleString('en-US', {
                                minimumFractionDigits: 2,
                                maximumFractionDigits: 2,
                              })}
                            </TableCell>
                          </TableRow>
                        </>
                      );
                    })()}
                  </TableBody>
                </Table>

                {/* Summary */}
                <Text className="summary">
                  <Text>
                    <b>Subtotal:</b> {record?.currency}{' '}
                    {formatAmount(totalAmount)}
                  </Text>
                  <Text>
                    <b>Tax:</b> {record?.currency} 0
                  </Text>
                  <Text>
                    <b>Total Payable:</b> {record?.currency}{' '}
                    {formatAmount(totalAmount)} (
                    {currencyToWords(totalAmount, {
                      currency: CURRENCY_MAP[record?.currency],
                    })}
                    )
                  </Text>
                </Text>

                {/* Bank Details */}
                <Text className="bank-details">
                  <b>Bank Details</b>
                  <Text>
                    Bank: {record?.bank?.bank_name}
                    <br />
                    Account Holder: {record?.bank?.acc_holder}
                    <br />
                    Account No: {record?.bank?.acc_number}
                    <br />
                    SWIFT: {record?.bank?.swift_code}
                  </Text>
                </Text>

                {/* Terms & Contact */}
                <Text className="terms-contact">
                  <Table className="terms-contact-section">
                    <TableBody>
                      <TableRow>
                        <TableCell>
                          <h5>Terms & Conditions:</h5>
                          <p>{INVOICE_T_N_C}</p>
                        </TableCell>
                        <TableCell>
                          <p>
                            For any queries, contact:{' '}
                            <a href={`mailto:${INVOICE_ENQUIRY_EMAIL}`}>
                              {INVOICE_ENQUIRY_EMAIL}
                            </a>
                          </p>
                        </TableCell>
                      </TableRow>
                    </TableBody>
                  </Table>
                </Text>
              </Text>
            </div>
          </Text>
        </Text>

        {/* Footer with Download Button */}
        <Text className="modal-footer flex justify-end items-end footer-modal text-right gap-2 m-0 pr-4 p-2">
          <DialogClose asChild>
            <Button
              type="button"
              className="m-0 filter-search-btn tracking-wider w-40 primary-button"
            >
              Cancel
            </Button>
          </DialogClose>

          <Button
            onClick={handleDownload}
            disabled={isGenerating}
            className="m-0 filter-search-btn tracking-wider w-40 primary-button"
          >
            {isGenerating ? 'Generating PDF…' : 'Download PDF'}
          </Button>
        </Text>
      </DialogContent>
    </Dialog>
  );
};

export default InvoicePdfButton;
