import React, { useState, useMemo } from 'react';
import { Download, Filter, FileText, Search, Printer, Calendar } from 'lucide-react';
import { generateInvoicePDF } from '../utils/pdfGenerator';

const Reports = () => {
    const [searchTerm, setSearchTerm] = useState('');

    const allInvoices = useMemo(() => {
        return JSON.parse(localStorage.getItem('oman_invoices') || '[]');
    }, []);

    const filteredInvoices = useMemo(() => {
        if (!searchTerm) return allInvoices;
        const term = searchTerm.toLowerCase();
        return allInvoices.filter(inv =>
            inv.clientName.toLowerCase().includes(term) ||
            inv.clientPo.toLowerCase().includes(term) ||
            inv.invoiceNumber.toLowerCase().includes(term)
        );
    }, [allInvoices, searchTerm]);

    const taxTotals = useMemo(() => {
        return allInvoices.reduce((acc, inv) => ({
            getfund: acc.getfund + inv.totals.getfund,
            nhil: acc.nhil + inv.totals.nhil,
            vat: acc.vat + inv.totals.vat,
        }), { getfund: 0, nhil: 0, vat: 0 });
    }, [allInvoices]);

    const serviceIncome = useMemo(() => {
        return allInvoices.reduce((acc, inv) => acc + Number(inv.installation) + Number(inv.fixings), 0);
    }, [allInvoices]);

    return (
        <div style={{ display: 'flex', flexDirection: 'column', gap: '2rem' }}>

            {/* Header & Search */}
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <div style={{ position: 'relative', width: '400px' }}>
                    <Search size={18} style={{ position: 'absolute', left: '1rem', top: '50%', transform: 'translateY(-50%)', color: 'var(--text-secondary)' }} />
                    <input
                        type="text"
                        placeholder="Search Client or PO Number..."
                        className="input-field"
                        style={{ paddingLeft: '3rem' }}
                        value={searchTerm}
                        onChange={(e) => setSearchTerm(e.target.value)}
                    />
                </div>
                <button className="btn btn-outline">
                    <Download size={18} />
                    Export Ledger
                </button>
            </div>

            <div style={{ display: 'grid', gridTemplateColumns: '1fr 340px', gap: '1.5rem' }}>

                {/* Document History Table */}
                <div className="glass-panel" style={{ padding: '1.5rem' }}>
                    <h3 style={{ fontSize: '0.8rem', color: 'var(--text-secondary)', marginBottom: '1.5rem', letterSpacing: '2px' }}>DOCUMENT TRANSACTION HISTORY</h3>
                    <div style={{ overflowX: 'auto' }}>
                        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                            <thead>
                                <tr style={{ textAlign: 'left', borderBottom: '2px solid var(--border)', fontSize: '0.7rem' }}>
                                    <th style={{ padding: '1rem' }}>ID / PO</th>
                                    <th style={{ padding: '1rem' }}>CLIENT</th>
                                    <th style={{ padding: '1rem' }}>STATUS</th>
                                    <th style={{ padding: '1rem', textAlign: 'right' }}>NET TOTAL</th>
                                    <th style={{ padding: '1rem', textAlign: 'center' }}>ACTIONS</th>
                                </tr>
                            </thead>
                            <tbody>
                                {filteredInvoices.map((inv) => (
                                    <tr key={inv.invoiceNumber} style={{ borderBottom: '1px solid var(--border)' }}>
                                        <td style={{ padding: '1rem' }}>
                                            <div style={{ fontWeight: 800 }}>{inv.invoiceNumber}</div>
                                            <div style={{ fontSize: '0.75rem', color: 'var(--text-secondary)' }}>{inv.clientPo || 'NO PO'}</div>
                                        </td>
                                        <td style={{ padding: '1rem' }}>
                                            <div style={{ fontWeight: 600 }}>{inv.clientName}</div>
                                            <div style={{ fontSize: '0.75rem', color: 'var(--text-secondary)' }}>{new Date(inv.date).toLocaleDateString()}</div>
                                        </td>
                                        <td style={{ padding: '1rem' }}>
                                            <span className={`badge badge-${inv.status.toLowerCase()}`}>{inv.status}</span>
                                        </td>
                                        <td style={{ padding: '1rem', textAlign: 'right', fontWeight: 800 }}>
                                            GHS {inv.totals.grandTotal.toLocaleString(undefined, { minimumFractionDigits: 2 })}
                                        </td>
                                        <td style={{ padding: '1rem', textAlign: 'center' }}>
                                            <button className="btn btn-outline" style={{ padding: '0.4rem' }} onClick={() => alert('View details... disabled for now')}>
                                                <Printer size={14} />
                                            </button>
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                </div>

                {/* Sequential Tax Obligation Report */}
                <div className="glass-panel" style={{ padding: '1.5rem', height: 'fit-content' }}>
                    <h3 style={{ fontSize: '0.8rem', color: 'var(--text-secondary)', marginBottom: '1.5rem', letterSpacing: '2px' }}>TAX OBLIGATIONS</h3>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '1.25rem' }}>

                        <div style={{ padding: '1.25rem', background: '#f8fafc', border: '1px solid var(--border)', borderRadius: '8px' }}>
                            <p style={{ fontSize: '0.7rem', color: 'var(--text-secondary)', fontWeight: 800, marginBottom: '0.5rem' }}>GETFund (2.5%)</p>
                            <h4 style={{ fontSize: '1.3rem' }}>GHS {taxTotals.getfund.toLocaleString(undefined, { minimumFractionDigits: 2 })}</h4>
                        </div>

                        <div style={{ padding: '1.25rem', background: '#f8fafc', border: '1px solid var(--border)', borderRadius: '8px' }}>
                            <p style={{ fontSize: '0.7rem', color: 'var(--text-secondary)', fontWeight: 800, marginBottom: '0.5rem' }}>NHIL (2.5%)</p>
                            <h4 style={{ fontSize: '1.3rem' }}>GHS {taxTotals.nhil.toLocaleString(undefined, { minimumFractionDigits: 2 })}</h4>
                        </div>

                        <div style={{ padding: '1.25rem', background: 'var(--primary)', border: '1px solid rgba(0,0,0,0.05)', borderRadius: '8px' }}>
                            <p style={{ fontSize: '0.7rem', color: 'rgba(255,255,255,0.8)', fontWeight: 800, marginBottom: '0.5rem' }}>VAT CONTROL (15%)</p>
                            <h4 style={{ fontSize: '1.5rem', color: 'white' }}>GHS {taxTotals.vat.toLocaleString(undefined, { minimumFractionDigits: 2 })}</h4>
                        </div>

                        <div style={{ borderTop: '1px solid var(--border)', paddingTop: '1.25rem', marginTop: '1rem' }}>
                            <h3 style={{ fontSize: '0.8rem', color: 'var(--text-secondary)', marginBottom: '1rem', letterSpacing: '1.5px' }}>SERVICE REVENUE</h3>
                            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                                <span style={{ fontSize: '0.85rem' }}>Repair & Install</span>
                                <span style={{ fontWeight: 800, fontSize: '1.1rem' }}>GHS {serviceIncome.toLocaleString(undefined, { minimumFractionDigits: 2 })}</span>
                            </div>
                        </div>

                    </div>
                </div>

            </div>

            <div style={{ textAlign: 'center', opacity: 0.5, fontSize: '0.75rem', marginTop: '2rem' }}>
                "Legal Data: This ledger captures all financial obligations and complies with mandatory accounting layouts."
            </div>
        </div>
    );
};

export default Reports;
