import React, { useState, useEffect } from 'react';
import billingService from '../services/billingService';
import {
    FileText,
    Plus,
    Download,
    Send,
    Printer,
    CheckCircle,
    Clock,
    AlertCircle,
    MoreVertical,
    ExternalLink,
    Edit2,
    Trash2
} from 'lucide-react';
import { clsx } from 'clsx';
import DocumentEditor from '../components/DocumentEditor';
import settingsService from '../services/settingsService';
import bankService from '../services/bankService';
import {
    X,
    Building2,
    CreditCard,
    DollarSign,
    Zap,
    History
} from 'lucide-react';

const InvoiceList = () => {
    const [invoices, setInvoices] = useState([]);
    const [loading, setLoading] = useState(true);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [editingInvoice, setEditingInvoice] = useState(null);
    const [currency, setCurrency] = useState('KES');
    const [isPaymentModalOpen, setIsPaymentModalOpen] = useState(false);
    const [paymentData, setPaymentData] = useState({
        invoiceId: '',
        amount: 0,
        paymentMethod: 'Bank',
        bankAccountId: '',
        transactionReference: ''
    });
    const [accounts, setAccounts] = useState([]);

    useEffect(() => {
        fetchInvoices();
        fetchSettings();
        fetchAccounts();
    }, []);

    const fetchAccounts = async () => {
        try {
            const res = await bankService.getAccounts();
            setAccounts(res.data);
            if (res.data.length > 0) {
                const def = res.data.find(a => a.isDefault) || res.data[0];
                setPaymentData(prev => ({ ...prev, bankAccountId: def.id }));
            }
        } catch (err) {
            console.error(err);
        }
    };

    const fetchSettings = async () => {
        try {
            const res = await settingsService.getSettings();
            if (res.data.DEFAULT_CURRENCY) setCurrency(res.data.DEFAULT_CURRENCY);
        } catch (err) {
            console.error(err);
        }
    };

    const fetchInvoices = async () => {
        try {
            const res = await billingService.getInvoices();
            setInvoices(res.data);
        } catch (err) {
            console.error(err);
        } finally {
            setLoading(false);
        }
    };

    const handleCreate = () => {
        setEditingInvoice(null);
        setIsModalOpen(true);
    };

    const handleEdit = (inv) => {
        setEditingInvoice(inv);
        setIsModalOpen(true);
    };

    const handleMarkPaid = (inv) => {
        setPaymentData({
            invoiceId: inv.id,
            amount: inv.balanceDue,
            paymentMethod: 'Bank',
            bankAccountId: accounts.find(a => a.isDefault)?.id || (accounts[0]?.id || ''),
            transactionReference: ''
        });
        setIsPaymentModalOpen(true);
    };

    const submitPayment = async (e) => {
        e.preventDefault();
        try {
            await billingService.markAsPaid(paymentData.invoiceId, paymentData);
            setIsPaymentModalOpen(false);
            fetchInvoices();
        } catch (err) {
            alert(err.response?.data?.error || 'Error recording payment');
        }
    };

    const handleDelete = async (id) => {
        if (window.confirm('Are you sure you want to delete this invoice? This action cannot be undone.')) {
            try {
                await billingService.deleteInvoice(id);
                fetchInvoices();
            } catch (err) {
                alert(err.response?.data?.error || 'Error deleting invoice');
            }
        }
    };

    const StatusBadge = ({ status }) => {
        const styles = {
            'Paid': 'bg-emerald-500/10 text-emerald-500 border-emerald-500/20',
            'Sent': 'bg-blue-500/10 text-blue-500 border-blue-500/20',
            'Overdue': 'bg-rose-500/10 text-rose-500 border-rose-500/20 shadow-sm shadow-rose-500/10',
            'Draft': 'bg-slate-500/10 text-slate-500 border-slate-500/20',
        };
        const icons = {
            'Paid': <CheckCircle className="w-3 h-3" />,
            'Sent': <Send className="w-3 h-3" />,
            'Overdue': <AlertCircle className="w-3 h-3" />,
            'Draft': <Clock className="w-3 h-3" />,
        };
        return (
            <div className={clsx("inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-[9px] font-black uppercase tracking-widest border transition-all duration-300", styles[status] || styles['Draft'])}>
                {icons[status] || icons['Draft']}
                {status}
            </div>
        );
    };

    return (
        <div className="space-y-10 animate-slide-up">
            {/* Premium Header */}
            <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-6">
                <div className="flex items-center gap-4 sm:gap-5 min-w-0">
                    <div className="p-3 sm:p-4 bg-primary rounded-2xl text-white shadow-xl shadow-primary/20 shrink-0">
                        <FileText className="w-6 h-6 sm:w-8 sm:h-8 shrink-0" />
                    </div>
                    <div className="min-w-0">
                        <h1 className="text-xl sm:text-2xl font-extrabold text-slate-800 dark:text-white tracking-tight leading-none truncate">Invoices</h1>
                        <div className="flex items-center gap-2 mt-1">
                            <span className="text-[10px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest whitespace-nowrap">Revenue Management</span>
                            <div className="w-1 h-1 bg-slate-300 dark:bg-slate-700 rounded-full shrink-0"></div>
                            <span className="text-[10px] font-black text-primary uppercase tracking-widest whitespace-nowrap">{invoices.length} Invoices</span>
                        </div>
                    </div>
                </div>
                <div className="flex items-center gap-3 w-full md:w-auto">
                    <button
                        onClick={handleCreate}
                        className="btn-primary w-full md:w-auto flex items-center justify-center gap-2 px-8 h-12 lg:h-14"
                    >
                        <Plus className="w-4 h-4 shrink-0" />
                        <span className="text-[10px] sm:text-[11px] font-black uppercase tracking-widest whitespace-nowrap">Create Invoice</span>
                    </button>
                </div>
            </div>

            {/* Invoices Table Section */}
            <div className="premium-card overflow-hidden">
                <div className="overflow-x-auto overflow-y-hidden">
                    <table className="w-full text-left min-w-[1100px]">
                        <thead>
                            <tr className="bg-slate-50/50 dark:bg-slate-900/40 border-b border-slate-100 dark:border-slate-800">
                                <th className="px-6 sm:px-8 py-5 text-[11px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest">Invoice Number</th>
                                <th className="px-6 sm:px-8 py-5 text-[11px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest">Client</th>
                                <th className="px-6 sm:px-8 py-5 text-[11px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest text-center">Date</th>
                                <th className="px-6 sm:px-8 py-5 text-[11px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest text-center">Status</th>
                                <th className="px-6 sm:px-8 py-5 text-[11px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest text-right">Amount</th>
                                <th className="px-6 sm:px-8 py-5 text-[11px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest text-right">Actions</th>
                            </tr>
                        </thead>
                        <tbody className="divide-y divide-slate-100 dark:divide-slate-800/50">
                            {loading ? (
                                <tr>
                                    <td colSpan="6" className="p-24 text-center">
                                        <div className="flex flex-col items-center gap-4">
                                            <div className="w-12 h-12 border-4 border-primary/20 border-t-primary rounded-full animate-spin"></div>
                                            <p className="text-[11px] font-black text-slate-400 uppercase tracking-[0.2em]">Loading invoices...</p>
                                        </div>
                                    </td>
                                </tr>
                            ) : invoices.length === 0 ? (
                                <tr>
                                    <td colSpan="6" className="p-12 sm:p-24 text-center">
                                        <div className="max-w-xs mx-auto space-y-4">
                                            <div className="w-16 h-16 bg-slate-50 dark:bg-slate-900 rounded-3xl flex items-center justify-center mx-auto shrink-0">
                                                <FileText className="w-8 h-8 text-slate-200 dark:text-slate-800 shrink-0" />
                                            </div>
                                            <h3 className="text-sm font-extrabold text-slate-800 dark:text-white uppercase tracking-tight">No Invoices Found</h3>
                                            <p className="text-[11px] text-slate-500 dark:text-slate-500 leading-relaxed font-bold uppercase tracking-widest">Create your first invoice to get started.</p>
                                        </div>
                                    </td>
                                </tr>
                            ) : (
                                invoices.map((inv) => (
                                    <tr key={inv.id} className="group hover:bg-slate-50/50 dark:hover:bg-slate-900/30 transition-all duration-300">
                                        <td className="px-6 sm:px-8 py-6">
                                            <div className="flex items-center gap-3 whitespace-nowrap">
                                                <div className="w-2 h-2 rounded-full bg-primary/20 shadow-[0_0_8px_rgba(var(--color-primary),0.2)] shrink-0"></div>
                                                <span className="text-sm font-black text-slate-800 dark:text-white tracking-tight">{inv.invoiceNumber}</span>
                                            </div>
                                        </td>
                                        <td className="px-6 sm:px-8 py-6">
                                            <div className="flex flex-col gap-0.5 min-w-0">
                                                <span className="text-sm font-extrabold text-slate-700 dark:text-slate-300 capitalize truncate">{inv.Client?.name}</span>
                                                <span className="text-[10px] font-bold text-slate-400 dark:text-slate-600 uppercase tracking-widest truncate">{inv.Client?.email || 'No Email Record'}</span>
                                            </div>
                                        </td>
                                        <td className="px-6 sm:px-8 py-6 text-center whitespace-nowrap">
                                            <div className="flex flex-col gap-1 items-center">
                                                <span className="text-[11px] font-extrabold text-slate-600 dark:text-slate-400">{inv.issueDate}</span>
                                                <div className="flex items-center gap-2">
                                                    <div className="h-px w-3 bg-slate-200 dark:bg-slate-800 shrink-0"></div>
                                                    <span className="text-[10px] font-black text-slate-400 dark:text-slate-600 uppercase tracking-tighter">Due {inv.dueDate}</span>
                                                </div>
                                            </div>
                                        </td>
                                        <td className="px-6 sm:px-8 py-6 text-center">
                                            <StatusBadge status={inv.status} />
                                        </td>
                                        <td className="px-6 sm:px-8 py-6 text-right whitespace-nowrap">
                                            <div className="flex flex-col items-end gap-1">
                                                <span className="text-sm font-black text-slate-900 dark:text-white tracking-tight">
                                                    <span className="text-[10px] text-primary/60 dark:text-primary/40 mr-1 shrink-0">{currency}</span>
                                                    {Number(inv.total).toLocaleString()}
                                                </span>
                                                {inv.balanceDue > 0 && (
                                                    <span className="text-[10px] font-black text-rose-500/80 uppercase tracking-tighter">
                                                        Bal: {currency} {Number(inv.balanceDue).toLocaleString()}
                                                    </span>
                                                )}
                                            </div>
                                        </td>
                                        <td className="px-6 sm:px-8 py-6 text-right">
                                            <div className="flex justify-end items-center gap-1.5 lg:opacity-0 group-hover:opacity-100 transition-all lg:translate-x-2 group-hover:translate-x-0 duration-300">
                                                <button
                                                    onClick={() => handleEdit(inv)}
                                                    className="p-2.5 text-slate-400 hover:text-primary hover:bg-primary/5 dark:hover:bg-primary/10 rounded-xl transition-all shrink-0"
                                                    title="Edit Invoice"
                                                >
                                                    <Edit2 className="w-4 h-4 shrink-0" />
                                                </button>
                                                <div className="flex items-center gap-1.5 px-1.5 border-x border-slate-100 dark:border-slate-800 mx-1 shrink-0">
                                                    <a
                                                        href={billingService.getInvoicePDF(inv.id, 'download')}
                                                        target="_blank"
                                                        rel="noreferrer"
                                                        className="p-2 text-slate-400 hover:text-blue-500 hover:bg-blue-50 dark:hover:bg-blue-500/10 rounded-xl transition-all shrink-0"
                                                        title="Download PDF"
                                                    >
                                                        <Download className="w-4 h-4 shrink-0" />
                                                    </a>
                                                    <a
                                                        href={billingService.getInvoicePDF(inv.id, 'view')}
                                                        target="_blank"
                                                        rel="noreferrer"
                                                        className="p-2 text-slate-400 hover:text-emerald-500 hover:bg-emerald-50 dark:hover:bg-emerald-500/10 rounded-xl transition-all shrink-0"
                                                        title="Print Invoice"
                                                    >
                                                        <Printer className="w-4 h-4 shrink-0" />
                                                    </a>
                                                </div>
                                                {inv.status !== 'Paid' && (
                                                    <button
                                                        onClick={() => handleMarkPaid(inv)}
                                                        className="p-2.5 text-emerald-500 hover:bg-emerald-50 dark:hover:bg-emerald-500/10 rounded-xl transition-all shadow-sm shadow-emerald-500/0 hover:shadow-emerald-500/10 shrink-0"
                                                        title="Record Payment"
                                                    >
                                                        <CheckCircle className="w-4 h-4 shrink-0" />
                                                    </button>
                                                )}
                                                <button
                                                    onClick={async () => {
                                                        try {
                                                            await billingService.sendInvoice(inv.id);
                                                            alert('Invoice dispatched successfully!');
                                                            fetchInvoices();
                                                        } catch (err) {
                                                            alert('Transmission failure');
                                                        }
                                                    }}
                                                    className="p-2.5 text-slate-400 hover:text-blue-500 hover:bg-blue-50 dark:hover:bg-blue-500/10 rounded-xl transition-all shrink-0"
                                                    title="Send to Client"
                                                >
                                                    <Send className="w-4 h-4 shrink-0" />
                                                </button>
                                                <button
                                                    onClick={() => handleDelete(inv.id)}
                                                    className="p-2.5 text-slate-300 hover:text-rose-500 hover:bg-rose-50 dark:hover:bg-rose-500/10 rounded-xl transition-all shrink-0"
                                                    title="Delete Invoice"
                                                >
                                                    <Trash2 className="w-4 h-4 shrink-0" />
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                ))
                            )}
                        </tbody>
                    </table>
                </div>
            </div>
            <DocumentEditor
                isOpen={isModalOpen}
                onClose={() => setIsModalOpen(false)}
                onRefresh={fetchInvoices}
                type="Invoice"
                initialData={editingInvoice}
            />

            {/* Record Payment Modal */}
            {isPaymentModalOpen && (
                <div className="fixed inset-0 z-[60] flex items-center justify-center p-4 bg-slate-900/60 backdrop-blur-sm animate-in fade-in duration-300">
                    <div className="bg-white dark:bg-slate-900 w-full max-w-md rounded-[2.5rem] overflow-hidden relative animate-in zoom-in-95 duration-300 shadow-4xl premium-card flex flex-col max-h-[95vh]">
                        <div className="p-6 sm:p-8 border-b border-slate-100 dark:border-slate-800 flex justify-between items-center bg-slate-50/30 dark:bg-slate-900/20 shrink-0">
                            <h2 className="text-base sm:text-lg font-black text-slate-800 dark:text-white uppercase tracking-tight flex items-center gap-3 min-w-0">
                                <DollarSign className="w-5 h-5 sm:w-6 sm:h-6 text-emerald-500 p-1 bg-emerald-500/10 rounded-lg shrink-0" />
                                <span className="truncate">Record Payment</span>
                            </h2>
                            <button onClick={() => setIsPaymentModalOpen(false)} className="p-2 hover:bg-slate-100 dark:hover:bg-slate-800 rounded-xl transition-all shrink-0">
                                <X className="w-4 h-4 text-slate-400 shrink-0" />
                            </button>
                        </div>
                        <form onSubmit={submitPayment} className="p-6 sm:p-8 space-y-8 overflow-y-auto custom-scrollbar">
                            <div className="space-y-2">
                                <label className="premium-label">Payment Method</label>
                                <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
                                    {['Bank', 'MPesa', 'Cash'].map(m => (
                                        <button
                                            key={m}
                                            type="button"
                                            onClick={() => setPaymentData({ ...paymentData, paymentMethod: m })}
                                            className={clsx(
                                                "py-3 rounded-2xl text-[9px] sm:text-[10px] font-black uppercase tracking-widest transition-all border-2 h-12 sm:h-14",
                                                paymentData.paymentMethod === m
                                                    ? "bg-primary border-primary text-white shadow-lg shadow-primary/20"
                                                    : "bg-white dark:bg-slate-900/40 border-slate-100 dark:border-slate-800 text-slate-400 hover:border-slate-200 dark:hover:border-slate-700"
                                            )}
                                        >
                                            {m}
                                        </button>
                                    ))}
                                </div>
                            </div>

                            {(paymentData.paymentMethod === 'Bank' || paymentData.paymentMethod === 'MPesa') && (
                                <div className="space-y-2">
                                    <label className="premium-label">Deposit Account</label>
                                    <select
                                        required
                                        className="premium-input !appearance-auto h-12 sm:h-14"
                                        value={paymentData.bankAccountId}
                                        onChange={e => setPaymentData({ ...paymentData, bankAccountId: e.target.value })}
                                    >
                                        <option value="">Select Account</option>
                                        {accounts.map(acc => (
                                            <option key={acc.id} value={acc.id}>{acc.bankName} - {acc.accountNumber}</option>
                                        ))}
                                    </select>
                                </div>
                            )}

                            <div className="space-y-2">
                                <label className="premium-label">Payment Amount ({currency})</label>
                                <div className="relative group">
                                    <DollarSign className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-300 group-focus-within:text-primary transition-colors shrink-0" />
                                    <input
                                        type="number"
                                        required
                                        className="premium-input !pl-12 font-black text-lg sm:text-xl text-slate-900 dark:text-white h-12 sm:h-14"
                                        value={paymentData.amount}
                                        onChange={e => setPaymentData({ ...paymentData, amount: e.target.value })}
                                    />
                                </div>
                            </div>

                            <div className="space-y-2">
                                <label className="premium-label">Transaction Reference / ID</label>
                                <input
                                    className="premium-input h-12 sm:h-14"
                                    placeholder="e.g. TR-2024-X99"
                                    value={paymentData.transactionReference}
                                    onChange={e => setPaymentData({ ...paymentData, transactionReference: e.target.value })}
                                />
                            </div>

                            <button
                                type="submit"
                                className="btn-primary w-full py-4 text-[9px] sm:text-[11px] uppercase tracking-[0.2em] flex items-center justify-center gap-2 sm:gap-3 shadow-xl h-12 sm:h-14 shrink-0"
                            >
                                <Zap className="w-4 h-4 sm:w-5 sm:h-5 fill-white shrink-0" />
                                <span>Save Payment</span>
                            </button>
                        </form>
                    </div>
                </div>
            )}
        </div>
    );
};

export default InvoiceList;
