// components/PaymentReceipt.tsx

import { useEffect, useRef, useState } from "react";
import { useParams, useSearchParams } from 'react-router-dom';
import logo from '../../../assets/images/auth/fav_icon.png';
import IconPhone from "../../../components/Icon/IconPhone";
import IconMail from "../../../components/Icon/IconMail";
import api from '../../../api/axios';
import { toast } from "react-toastify";

export const numberToWords = (num: number) => {
    if (num === 0) return "Zero Rupees Only";

    const a = [
        "",
        "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten",
        "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen",
    ];

    const b = [
        "", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety",
    ];

    const toWords = (n: number): string => {
        if (n < 20) return a[n];
        if (n < 100) return b[Math.floor(n / 10)] + (n % 10 ? " " + a[n % 10] : "");
        if (n < 1000) return a[Math.floor(n / 100)] + " Hundred " + (n % 100 ? toWords(n % 100) : "");
        if (n < 100000) return toWords(Math.floor(n / 1000)) + " Thousand " + toWords(n % 1000);
        if (n < 10000000) return toWords(Math.floor(n / 100000)) + " Lakh " + toWords(n % 100000);
        return toWords(Math.floor(n / 10000000)) + " Crore " + toWords(n % 10000000);
    };

    return toWords(num).trim() + " Rupees Only";
};

const PaymentReceipt = () => {
    const [searchParams] = useSearchParams();
    const invoiceNo = searchParams.get('invoice_no');
    const [receipt, setReceipt] = useState<any>(null);
    const [loading, setLoading] = useState(true);
    const printRef = useRef<HTMLDivElement>(null);

    useEffect(() => {
        if (invoiceNo) {
            fetchInvoiceData(invoiceNo);
        }
    }, [invoiceNo]);

    const fetchInvoiceData = async (invoiceNo: string) => {
        try {
            const response = await api.get(`/invoice/${invoiceNo}`);
            if (response.data.status) {
                setReceipt(response.data.data);
            }
        } catch (error) {
            console.error('Error fetching invoice:', error);
            toast.error('Failed to load invoice');
        } finally {
            setLoading(false);
        }
    };

    const handleDownloadPDF = async () => {
        try {
            const response = await api.get(`/invoice/${invoiceNo}/download`, {
                responseType: 'blob'
            });

            const url = window.URL.createObjectURL(new Blob([response.data]));
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', `invoice_${invoiceNo}.pdf`);
            document.body.appendChild(link);
            link.click();
            link.remove();
            window.URL.revokeObjectURL(url);

            toast.success('Invoice downloaded successfully');
        } catch (error) {
            console.error('Error downloading invoice:', error);
            toast.error('Failed to download invoice');
        }
    };

    const handlePrint = () => {
        window.print();
    };

    const formatDate = (dateStr: string) => {
        if (!dateStr) return '';
        const date = new Date(dateStr);
        const day = String(date.getDate()).padStart(2, '0');
        const monthNames = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
        const month = monthNames[date.getMonth()];
        const year = date.getFullYear();
        return `${day}-${month}-${year}`;
    };

    if (loading) {
        return (
            <div className="flex items-center justify-center min-h-screen">
                <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary"></div>
            </div>
        );
    }

    if (!receipt) {
        return (
            <div className="flex items-center justify-center min-h-screen">
                <div className="text-center">
                    <h2 className="text-xl font-bold text-gray-600">No Data Found</h2>
                    <p className="text-gray-500 mt-2">The requested invoice could not be found.</p>
                </div>
            </div>
        );
    }

    return (
        <div className="bg-gray-100 min-h-screen py-8">
            {/* Action Buttons */}
            {/* <div className="max-w-3xl mx-auto mb-4 flex justify-end gap-3 no-print">
                <button
                    onClick={handlePrint}
                    className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 flex items-center gap-2"
                >
                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 17h2a2 2 0 002-2v-4a2 2 0 00-2-2H5a2 2 0 00-2 2v4a2 2 0 002 2h2m2 4h6a2 2 0 002-2v-4a2 2 0 00-2-2H9a2 2 0 00-2 2v4a2 2 0 002 2zm8-12V5a2 2 0 00-2-2H9a2 2 0 00-2 2v4h10z" />
                    </svg>
                    Print
                </button>
                <button
                    onClick={handleDownloadPDF}
                    className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 flex items-center gap-2"
                >
                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                    </svg>
                    Download PDF
                </button>
            </div> */}

            {/* Invoice Content */}
            <div ref={printRef} className="max-w-3xl mx-auto bg-white border print-area rounded-lg shadow-lg p-8">
                <div className="flex justify-between items-center border-b pb-4 mb-6">
                    <div className="flex justify-start items-center gap-3">
                        <img src={logo} alt="Tesra Logo" className="w-14 h-14"/>
                        <h2 className="text-3xl text-primary font-bold mt-2">Tesra</h2>
                    </div>
                    <h2 className="text-3xl text-primary font-bold">INVOICE</h2>
                </div>

                <div className="mb-6 flex justify-between gap-3">
                    <div>
                        <h6 className="font-bold text-base">{receipt.student.name} ({receipt.student.id})</h6>
                        <div className="flex items-center justify-start gap-3">
                            <span className="flex items-center justify-start gap-2"><IconPhone/> {receipt.student.mobile}</span>
                            <span className="flex items-center justify-start gap-2"><IconMail/> {receipt.student.email}</span>
                        </div>
                        <span>{receipt.student.address}</span>
                    </div>
                    <div className="flex flex-col gap-2">
                        <span><b>Invoice ID:</b> {receipt.invoice_no}</span>
                        <span><b>Date:</b> {receipt.date && formatDate(receipt.date)}</span>
                    </div>
                </div>

                <hr className="my-4" />

                <div className="my-4 flex justify-between gap-3">
                    <div>
                        <h6 className="font-bold text-base">{receipt.company.name}</h6>
                        <div className="flex items-center justify-start gap-3">
                            <span className="flex items-center justify-start gap-2"><IconPhone/> {receipt.company.mobile}</span>
                            <span className="flex items-center justify-start gap-2"><IconMail/> {receipt.company.email}</span>
                        </div>
                        <span>{receipt.company.address}</span>
                    </div>
                    <div className="flex flex-col gap-2">
                        <span><b>GSTIN:</b> {receipt.company.gstin}</span>
                        <span><b>PAN:</b> {receipt.company.pan}</span>
                    </div>
                </div>

                <hr className="my-4" />

                {receipt.course && (
                    <div className="my-4 flex justify-between gap-3">
                        <div className="flex flex-col gap-0">
                            <span><b>Course Title:</b> {receipt.course.title}</span>
                            <span><b>Course Code:</b> {receipt.course.code}</span>
                            <span><b>Course Duration:</b> {receipt.course.duration}</span>
                            <span><b>Tech Support Centre:</b> {receipt.course.center}</span>
                        </div>
                    </div>
                )}

                <div className="my-4">
                    <table className="w-full border border-gray-200 text-sm mb-2">
                        <thead className="text-white">
                            <tr>
                                <th className="p-2 bg-[#D82942] text-left w-2/5">Type</th>
                                <th className="p-2 bg-[#D82942] text-center w-1/6">HSN/SAC</th>
                                <th className="p-2 bg-[#D82942] text-center w-1/6">Price</th>
                                <th className="p-2 bg-[#D82942] text-center w-1/12">CGST</th>
                                <th className="p-2 bg-[#D82942] text-center w-1/12">SGST</th>
                                <th className="p-2 bg-[#D82942] text-center w-1/6">Amount</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr className="border-t">
                                <td className="p-2">{receipt.payment.type}</td>
                                <td className="p-2 text-center">{receipt.payment.hsn}</td>
                                <td className="p-2 text-center">₹ {receipt.payment.price?.toLocaleString()}</td>
                                <td className="p-2 text-center">₹ {receipt.payment.cgst?.toLocaleString()}</td>
                                <td className="p-2 text-center">₹ {receipt.payment.sgst?.toLocaleString()}</td>
                                <td className="p-2 text-center font-semibold">₹ {receipt.payment.amount?.toLocaleString()}</td>
                            </tr>
                        </tbody>
                    </table>
                </div>

                <div className="flex justify-between items-end gap-4 my-4">
                    <div className="flex flex-col gap-0">
                        <label className="flex items-center justify-start gap-2">
                            <span>Received Rs (in Words)</span>
                            <span>:</span>
                            <span className="font-semibold">{numberToWords(receipt.payment.amount)}</span>
                        </label>
                        <label className="flex items-center justify-start gap-2">
                            <span>Mode of Payment</span>
                            <span>:</span>
                            <span className="font-semibold">{receipt.payment.method}</span>
                        </label>
                    </div>
                    <label className="flex items-center justify-start gap-2">
                        <span>Total</span>
                        <span>:</span>
                        <span className="text-xl text-danger font-bold">₹ {receipt.payment.amount?.toLocaleString()}</span>
                    </label>
                </div>

                <hr className="my-4" />

                <div className="text-xs">
                    <label className="text-xl text-black text-center font-semibold block mb-2">Terms of Service Offered</label>
                    <p className="mb-1">1. Payment made through cheque is subject to realization. In case the cheque is returned / dishonoured for any reason, handling charges of Rs. 500/- along with the charges by the bank for return of the cheque will be collected from student by the centre.</p>
                    <p className="mb-1">2. The student should strictly adhere to the batch / schedule timings specified by the centre. All breaks must be pre-approved in writing and not exceeding 2 months continuously</p>
                    <p className="mb-1">3. Transfer from Centre to Centre will be done at the student's request, provided the course is available and the course timing is suitable in the transferee centre.</p>
                    <p className="mb-1">5. This receipt should be kept safe for future reference to be produced at the time of collecting the course completion certificate.</p>
                    <p className="mb-1">8. Fee once paid cannot be refunded, However the fee could be transferred for another course at CADD Centre, within 3 days from the date of payment.</p>
                    <p className="mb-1">11. Any dispute on this course, and its performance, shall be governed within the jurisdiction of courts in Chennai.</p>
                    <p className="mb-1">12. The student must complete the course within the defined course duration (or within 24 months whichever is longer), from the date of joining.</p>
                </div>

                <div className="mt-8 text-xs">
                    <label className="text-sm text-black text-center font-semibold block mb-4">
                        <i>I have read and agreed the terms and conditions furnished in the Student Obligation Booklet</i>
                    </label>
                    <div className="flex justify-between gap-4">
                        <div className="flex flex-col">
                            <span className="text-sm text-dark font-bold">Signature of the Student</span>
                            <span className="text-sm text-black mt-8">{receipt.student.name}</span>
                        </div>
                        <div className="flex flex-col">
                            <span className="text-sm text-dark font-bold">Signature of the Staff</span>
                            <span className="text-sm text-black mt-8">{receipt.course?.staff_name || 'Staff'}</span>
                        </div>
                    </div>
                </div>
            </div>

            <style>
                {`
                    @media print {
                        .no-print {
                            display: none !important;
                        }
                        body {
                            background: white;
                        }
                        .print-area {
                            box-shadow: none !important;
                            border: none !important;
                        }
                    }
                `}
            </style>
        </div>
    );
};

export default PaymentReceipt;
