"use client";

import { API_BASE_URL, getAuthHeaders } from "@/lib/api";
import React, { useEffect, useState } from "react";
import { useParams } from "next/navigation";
import { Loader2 } from "lucide-react";

export default function ContractMasterReceiptPage() {
    const { id } = useParams();
    const [data, setData] = useState<any>(null);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        async function fetchContractData() {
            try {
                const [contRes, payRes, compRes] = await Promise.all([
                    fetch(`${API_BASE_URL}/contracts/${id}/`, { headers: getAuthHeaders() }),
                    fetch(`${API_BASE_URL}/payments/?contract=${id}`, { headers: getAuthHeaders() }),
                    fetch(`${API_BASE_URL}/companies/`, { headers: getAuthHeaders() })
                ]);

                if (!contRes.ok) throw new Error("Contract not found");

                const contract = await contRes.json();
                const paymentsList = await payRes.json();
                const companies = await compRes.json();
                const company = (companies.results || companies)[0];

                setData({
                    contract,
                    payments: paymentsList.results || paymentsList,
                    company
                });
            } catch (err) {
                console.error(err);
            } finally {
                setLoading(false);
            }
        }
        fetchContractData();
    }, [id]);

    useEffect(() => {
        if (data) {
            const timer = setTimeout(() => {
                window.print();
            }, 3000);
            return () => clearTimeout(timer);
        }
    }, [data]);

    if (loading) return <div className="p-12 text-center animate-pulse">Generating Master Payment Summary...</div>;
    if (!data) return <div className="p-12 text-center text-red-500">Error loading data.</div>;

    const { contract, payments, company } = data;
    const client = contract.client_detail;
    const asset = contract.asset_detail;

    return (
        <div style={{ backgroundColor: 'white', minHeight: '100vh', margin: 0, padding: 0 }}>
            {/* Inject fonts and styles to match contract_receipt.html EXACTLY */}
            <style jsx global>{`
                @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap');
                
                body {
                    margin: 0;
                    padding: 0;
                    background-color: white !important;
                }

                #contract-receipt-body {
                    font-family: 'Poppins', Arial, sans-serif;
                    background-color: white;
                    font-size: 9px;
                    border: 10px double #2563eb;
                    position: relative;
                    padding: 20px;
                    min-height: calc(100vh - 40px);
                    /* Subtle geometric dot-grid texture */
                    background-image:
                        radial-gradient(circle, #2563eb18 1px, transparent 1px);
                    background-size: 24px 24px;
                }

                /* Diagonal watermark */
                #contract-receipt-body::before {
                    content: 'PAYMENT SUMMARY';
                    position: absolute;
                    top: 50%;
                    left: 50%;
                    transform: translate(-50%, -50%) rotate(-35deg);
                    font-size: 64px;
                    font-weight: 900;
                    color: #2563eb07;
                    white-space: nowrap;
                    pointer-events: none;
                    z-index: 0;
                    letter-spacing: 6px;
                    font-family: 'Poppins', Arial, sans-serif;
                }

                .receipt-container {
                    max-width: 800px;
                    margin: 0 auto;
                    padding: 30px;
                }

                .header-section {
                    display: grid;
                    grid-template-columns: 1fr 2fr 1fr;
                    gap: 20px;
                    margin-bottom: 5px;
                    border-bottom: 2px solid #2563eb;
                    padding-bottom: 5px;
                }

                .logo-section { text-align: center; }
                .logo-placeholder {
                    width: 70px; height: 70px;
                    background-color: #f8fafc;
                    border: 1px solid #e2e8f0;
                    border-radius: 8px;
                    display: flex; align-items: center; justify-content: center;
                    margin: 0 auto 10px;
                    overflow: hidden;
                }

                .company-section { text-align: center; }
                .company-name { font-size: 15px; font-weight: bold; color: #2563eb; margin: 0 0 5px 0; }
                .company-details { font-size: 10px; color: #64748b; line-height: 1.3; }

                .receipt-section { text-align: right; }
                .receipt-number { font-size: 12px; font-weight: bold; color: #1e293b; }
                .receipt-date { font-size: 8px; color: #64748b; margin-top: 2px; }

                .receipt-title { font-size: 13px; font-weight: bold; color: #1e293b; margin: 10px 0; text-align: center; text-transform: uppercase; }

                .middle-section { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 12px; }
                .client-info, .asset-info { background-color: #f8fafc; padding: 10px; border-radius: 8px; border: 1px solid #e2e8f0; }

                .info-title { font-weight: bold; color: #1e293b; margin-bottom: 10px; font-size: 12px; border-bottom: 1px solid #cbd5e1; padding-bottom: 5px; }
                .info-item { margin-bottom: 5px; font-size: 10px; }
                .info-label { font-weight: bold; color: #64748b; display: inline-block; width: 120px; }
                .info-value { color: #1e293b; }

                .contract-details { background-color: #f8fafc; padding: 15px; border-radius: 8px; border: 1px solid #e2e8f0; margin-bottom: 8px; }
                .contract-details-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 15px; }

                .payments-table { width: 100%; border-collapse: collapse; margin: 20px 0; border: 1px solid #e2e8f0; }
                .payments-table th, .payments-table td { border: 1px solid #e2e8f0; padding: 5px; text-align: left; font-size: 10px; }
                .payments-table th { background-color: #f1f5f9; font-weight: bold; color: #334155; }

                .payment-type-badge { display: inline-block; padding: 2px 8px; border-radius: 12px; font-size: 8px; font-weight: bold; text-transform: uppercase; margin-left: 5px; }
                .payment-type-installment { background-color: #dbeafe; color: #1e40af; }
                .payment-type-down_payment { background-color: #dcfce7; color: #166534; }
                .payment-type-early_payment { background-color: #fef3c7; color: #92400e; }
                .payment-type-partial_payment { background-color: #ede9fe; color: #6d28d9; }
                .payment-type-penalty { background-color: #fee2e2; color: #b91c1c; }

                .footer-section { margin-top: 20px; padding-top: 5px; border-top: 1px solid #e2e8f0; display: grid; grid-template-columns: 1fr auto 1fr; gap: 20px; align-items: center; }
                .signature-section { text-align: center; }
                .signature-line { border-top: 1px solid #64748b; width: 120px; margin: 0 auto 5px; }
                .signature-name { font-size: 9px; font-weight: bold; color: #1e293b; }

                .qrcode-section { text-align: center; }
                .qrcode-placeholder { 
                    width: 70px; height: 70px; 
                    background-color: white; 
                    border: 1px solid #2563eb; 
                    border-radius: 4px; 
                    display: flex; align-items: center; justify-content: center; 
                    margin: 0 auto 5px;
                    overflow: hidden;
                }
                .qrcode-img {
                    width: 100%;
                    height: 100%;
                    object-fit: contain;
                }

                .footer-text { text-align: center; color: #64748b; font-size: 8px; margin-top: 10px; }

                @media print {
                    body { margin: 0; padding: 0; }
                    #contract-receipt-body { border: none; padding: 0; }
                    .receipt-container { box-shadow: none; border: none; margin: 0; padding: 10px; }
                }
            `}</style>

            <div id="contract-receipt-body">
                <div className="receipt-container">
                    {/* Header Part */}
                    <div className="header-section">
                        <div className="logo-section">
                            <div className="logo-placeholder">
                                {company?.logo ? (
                                    <img src={company.logo} alt="Company Logo" style={{ height: '100%', width: 'auto', objectFit: 'contain', borderRadius: '50%' }} />
                                ) : (
                                    <span style={{ fontSize: '8px' }}>Logo</span>
                                )}
                            </div>
                        </div>

                        <div className="company-section">
                            <div className="company-name">{company?.name || "Doha Homes and Property Limited"}</div>
                            <div className="company-details">
                                {company?.address ? company.address.split('\n').map((line: string, i: number) => <div key={i}>{line}</div>) : (
                                    <>
                                        123 Anywhere street, Maitama layout, new me<br />
                                        Abuja, Nigeria
                                    </>
                                )}
                                <br />
                                Phone: {company?.contact_phone || "+234-9164601810"}<br />
                                Email: {company?.contact_email || "info@dohahomesandproperty.com"}
                            </div>
                        </div>

                        <div className="receipt-section">
                            <div className="receipt-number">Contract No.: <br /> {contract.contract_number}</div>
                            <div className="receipt-date">Generated: {new Date(contract.updated_at).toLocaleString('en-US', { month: 'long', day: 'numeric', year: 'numeric', hour: 'numeric', minute: '2-digit', hour12: true })}</div>
                        </div>
                    </div>

                    <div className="receipt-title">PAYMENT SUMMARY</div>

                    {/* Information Grid */}
                    <div className="middle-section">
                        <div className="client-info">
                            <div className="info-title">Client Information</div>
                            <div className="info-item"><span className="info-label">Name:</span> <span className="info-value">{client?.full_name}</span></div>
                            <div className="info-item"><span className="info-label">Phone:</span> <span className="info-value">{client?.phone_number}</span></div>
                            <div className="info-item"><span className="info-label">Address:</span> <span className="info-value">{client?.address || "-"}</span></div>
                            <div className="info-item"><span className="info-label">ID Type:</span> <span className="info-value">{client?.id_type}: {client?.id_number}</span></div>
                            <div className="info-item"><span className="info-label">Gender:</span> <span className="info-value">{client?.gender === 'M' ? 'Male' : client?.gender === 'F' ? 'Female' : 'Other'}</span></div>
                        </div>

                        <div className="asset-info">
                            <div className="info-title">Asset Information</div>
                            <div className="info-item"><span className="info-label">Asset:</span> <span className="info-value">{asset?.name}</span></div>
                            <div className="info-item"><span className="info-label">Type:</span> <span className="info-value">{asset?.asset_type_name || "Plot"}</span></div>
                            <div className="info-item"><span className="info-label">Location:</span> <span className="info-value">{asset?.location || "-"}</span></div>
                            <div className="info-item"><span className="info-label">Price:</span> <span className="info-value">₦{parseFloat(asset?.price || "0").toLocaleString()}</span></div>
                            <div className="info-item"><span className="info-label">Info:</span> <span className="info-value">{contract.notes || "-"}</span></div>
                        </div>
                    </div>

                    {/* Contract Details */}
                    <div className="contract-details">
                        <div className="info-title">Contract Information</div>
                        <div className="contract-details-grid">
                            <div>
                                <div className="info-item"><span className="info-label">Contract #:</span> <span className="info-value">{contract.contract_number}</span></div>
                                <div className="info-item"><span className="info-label">Start Date:</span> <span className="info-value">{new Date(contract.start_date).toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' })}</span></div>
                                <div className="info-item"><span className="info-label">End Date:</span> <span className="info-value">{new Date(contract.end_date).toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' })}</span></div>
                                <div className="info-item"><span className="info-label">Status:</span> <span className="info-value" style={{ textTransform: 'capitalize' }}>{contract.status}</span></div>
                            </div>
                            <div>
                                <div className="info-item"><span className="info-label">Total Price:</span> <span className="info-value">₦{parseFloat(contract.total_price).toLocaleString()}</span></div>
                                <div className="info-item"><span className="info-label">Down Payment:</span> <span className="info-value">₦{parseFloat(contract.down_payment).toLocaleString()}</span></div>
                                <div className="info-item"><span className="info-label">Installments:</span> <span className="info-value">{contract.installment_count}</span></div>
                                <div className="info-item"><span className="info-label">Agent:</span> <span className="info-value">{contract.assigned_sales_agent_name || "Not Assigned"}</span></div>
                            </div>
                        </div>
                    </div>

                    {/* Payment Records Table */}
                    <div className="info-title">All Payment Records</div>
                    <table className="payments-table">
                        <thead>
                            <tr>
                                <th>Receipt #</th>
                                <th>Date</th>
                                <th>Amount</th>
                                <th>Method</th>
                                <th>Type</th>
                                <th>Recorded By</th>
                            </tr>
                        </thead>
                        <tbody>
                            {payments.length > 0 ? payments.map((p: any, i: number) => (
                                <tr key={i}>
                                    <td>{p.reference_number || `REC-${p.id.toString().padStart(6, '0')}`}</td>
                                    <td>{new Date(p.payment_date).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}</td>
                                    <td>₦{parseFloat(p.amount).toLocaleString()}</td>
                                    <td style={{ textTransform: 'capitalize' }}>{p.payment_method.replace('_', ' ')}</td>
                                    <td>
                                        <span style={{ textTransform: 'capitalize' }}>{p.payment_type.replace('_', ' ')}</span>
                                        <span className={`payment-type-badge payment-type-${p.payment_type}`}>
                                            {p.payment_type.replace('_', ' ')}
                                        </span>
                                    </td>
                                    <td>{p.recorded_by_name || "Staff"}</td>
                                </tr>
                            )) : (
                                <tr>
                                    <td colSpan={6} style={{ textAlign: 'center', color: '#64748b' }}>No payments recorded yet</td>
                                </tr>
                            )}
                        </tbody>
                    </table>

                    {/* Footer / Signatures */}
                    <div className="footer-section">
                        <div className="signature-section">
                            <div className="signature-line"></div>
                            <div className="signature-name">MANAGER SIGNATURE</div>
                        </div>

                        <div className="qrcode-section">
                            <div className="qrcode-placeholder">
                                <img
                                    src={`https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(
                                        (() => {
                                            const totalPaid = payments.reduce((sum: number, p: any) => sum + parseFloat(p.amount || 0), 0);
                                            const outstanding = parseFloat(contract.total_price) - totalPaid;
                                            return [
                                                `CONTRACT: ${contract.contract_number}`,
                                                `CLIENT: ${client?.full_name || '-'}`,
                                                `ASSET: ${asset?.name || '-'}`,
                                                `TOTAL PRICE: NGN ${parseFloat(contract.total_price).toLocaleString()}`,
                                                `TOTAL PAID: NGN ${totalPaid.toLocaleString()}`,
                                                `OUTSTANDING: NGN ${outstanding.toLocaleString()}`,
                                                `INSTALLMENTS: ${contract.installment_count}`,
                                                `STATUS: ${contract.status?.toUpperCase()}`,
                                                `AGENT: ${contract.assigned_sales_agent_name || 'Not Assigned'}`,
                                                `START: ${new Date(contract.start_date).toLocaleDateString('en-GB')}`,
                                                `END: ${new Date(contract.end_date).toLocaleDateString('en-GB')}`,
                                                `GENERATED: ${new Date().toLocaleDateString('en-GB')}`,
                                            ].join('\n');
                                        })()
                                    )}`}
                                    alt="Verification QR"
                                    className="qrcode-img"
                                />
                            </div>
                            <div style={{ fontSize: '7px', color: '#2563eb', fontWeight: 'bold' }}>OFFICIAL SEAL</div>
                        </div>

                        <div className="signature-section">
                            <div className="signature-line"></div>
                            <div className="signature-name">CUSTOMER</div>
                        </div>
                    </div>

                    <div className="footer-text">
                        <p>This is a computer-generated receipt. No signature required. |
                            Generated on {new Date().toLocaleString('en-US', { month: 'long', day: 'numeric', year: 'numeric', hour: 'numeric', minute: '2-digit', hour12: true })}</p>
                    </div>
                </div>
            </div>
        </div>
    );
}
