'use client';

import React, { 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';

const InvoicePDF: React.FC = () => {
  const invoiceRef = useRef<HTMLDivElement>(null);
  const [isGenerating, setIsGenerating] = useState(false);

  /**
   * 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,
        filename: 'invoice.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>
      <DialogTrigger asChild>
        <button className="pdf-modal-button">
          <CommonImage
            src="../../main/download-icn.webp"
            width={14}
            height={14}
            alt="cross icon"
            classname="cross-icon"
          />
        </button>
      </DialogTrigger>

      <DialogContent className="z-[9999] w-full max-w-7xl p-0 m-0 table-modal-settings modal-common-widget pdf-view-model-widget">
        <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 | Pending</h3>

                {/* Invoice Header */}
                <Table className="invoice-date-section">
                  <TableBody>
                    <TableRow>
                      <TableCell>
                        <b>Invoice No:</b> INV-2025-001
                      </TableCell>
                      <TableCell style={{ textAlign: 'right' }}>
                        <b>Date:</b> 03-Oct-2025
                      </TableCell>
                    </TableRow>
                  </TableBody>
                </Table>

                {/* From / To */}
                <Table className="invoice-date-section-from-to">
                  <TableBody>
                    <TableRow>
                      <TableCell>
                        <h5>From:</h5>
                        <Text>
                          Western Overseas Ltd
                          <br />
                          SCO 27-28, Ground and First Floor,
                          <br />
                          Ambala, Haryana, India
                          <br />
                          GST: 1234567
                          <br />
                          Phone: <a href="tel:+XXXXXXX">XXXXXXX</a>
                          <br />
                          Email:{' '}
                          <a href="mailto:accounts@westernoverseas.com">
                            accounts@westernoverseas.com
                          </a>
                        </Text>
                      </TableCell>
                      <TableCell>
                        <h5>To:</h5>
                        <Text>
                          University of Auckland
                          <br />
                          New Zealand
                          <br />
                          Tax ID: 87654321
                          <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> New Zealand | <b>Intake:</b> May 2023 |{' '}
                  <b>Commission Instance:</b> Instance 1 | <b>Currency:</b> NZD
                </Text>

                {/* Commission Table */}
                <Table className="invoice-info-secton">
                  <TableHeader>
                    <TableRow>
                      {[
                        'Sr.',
                        'Student Name',
                        'ERP Case No. / Student ID',
                        'Course',
                        'Intake',
                        'Tuition Fees',
                        'Commission Type',
                        '% / Fixed',
                        'Commission Amount',
                      ].map((th, i) => (
                        <TableHead key={i}>{th}</TableHead>
                      ))}
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {[
                      [
                        '1',
                        'John Doe',
                        'CASE876464 / 65856',
                        'MBA',
                        'May 2023',
                        'NZD 15,000',
                        'Percent',
                        '10%',
                        'NZD 1,500',
                      ],
                      [
                        '2',
                        'Jamie Morgan',
                        'CASE876465 / 85699',
                        'B.Sc',
                        'May 2023',
                        'NZD 15,000',
                        'Fixed',
                        '-',
                        'NZD 1,500',
                      ],
                    ].map((row, i) => (
                      <TableRow key={i}>
                        {row.map((cell, j) => (
                          <TableCell key={j}>{cell}</TableCell>
                        ))}
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>

                {/* Summary */}
                <Text className="summary">
                  <Text>
                    <b>Subtotal:</b> NZD 3,000
                  </Text>
                  <Text>
                    <b>Tax:</b> NZD 0
                  </Text>
                  <Text>
                    <b>Total Payable:</b> NZD 3,000 (Three Thousand New Zealand
                    Dollars Only)
                  </Text>
                </Text>

                {/* Bank Details */}
                <Text className="bank-details">
                  <b>Bank Details</b>
                  <Text>
                    Bank: ANZ Bank New Zealand
                    <br />
                    Account Holder: Western Overseas Ltd
                    <br />
                    Account No: 123456789
                    <br />
                    SWIFT: ANZBNZ22
                  </Text>
                </Text>

                {/* Terms & Contact */}
                <Text className="terms-contact">
                  <Table className="terms-contact-section">
                    <TableBody>
                      <TableRow>
                        <TableCell>
                          <h5>Terms & Conditions:</h5>
                          <p>Payment due within 30 days of invoice date.</p>
                        </TableCell>
                        <TableCell>
                          <p>
                            For any queries, contact:{' '}
                            <a href="mailto:wo.growth@western-oveseas.com">
                              wo.growth@western-oveseas.com
                            </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 InvoicePDF;
