import React, { useState, useEffect } from 'react';
import clientPortalService from '../services/clientPortalService';
import billingService from '../services/billingService';
import {
    Download,
    CheckCircle,
    Clock,
    AlertCircle,
    FileText,
    Calendar,
    Search,
    ArrowUpRight
} from 'lucide-react';
import { clsx } from 'clsx';

const ClientInvoiceList = () => {
    const [invoices, setInvoices] = useState([]);
    const [loading, setLoading] = useState(true);
    const [searchTerm, setSearchTerm] = useState('');

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

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

    const StatusBadge = ({ status }) => {
        const styles = {
            'Paid': 'bg-emerald-500/10 text-emerald-500 border-emerald-500/20 shadow-sm shadow-emerald-500/5',
            'Sent': 'bg-blue-500/10 text-blue-500 border-blue-500/20 shadow-sm shadow-blue-500/5',
            'Overdue': 'bg-rose-500/10 text-rose-500 border-rose-500/20 shadow-sm shadow-rose-500/5',
            'Draft': 'bg-slate-500/10 text-slate-500 border-slate-500/20 shadow-sm shadow-slate-500/5',
        };
        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'])}>
                {status === 'Paid' && <CheckCircle className="w-3.5 h-3.5" />}
                {status === 'Overdue' && <AlertCircle className="w-3.5 h-3.5" />}
                {status}
            </div>
        );
    };

    const filteredInvoices = invoices.filter(inv =>
        inv.invoiceNumber.toLowerCase().includes(searchTerm.toLowerCase())
    );

    return (
        <div className="space-y-10 animate-slide-up pb-20">
            {/* 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">All Invoices</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 truncate">{invoices.length} Invoices</span>
                        </div>
                    </div>
                </div>
            </div>

            {/* Main Table Card */}
            <div className="premium-card overflow-hidden">
                <div className="p-4 sm:p-6 border-b border-slate-100 dark:border-slate-800/50 flex flex-col md:flex-row justify-between items-center gap-6">
                    <div className="relative flex-1 w-full group">
                        <Search 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="text"
                            placeholder="Find invoice by number..."
                            value={searchTerm}
                            onChange={(e) => setSearchTerm(e.target.value)}
                            className="w-full !pl-12 !py-3 !bg-slate-50/50 dark:!bg-slate-900/40 border-slate-100 dark:border-slate-800/50 outline-none rounded-2xl text-sm"
                        />
                    </div>
                </div>

                <div className="overflow-x-auto overflow-y-hidden">
                    <table className="w-full text-left min-w-[900px]">
                        <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 #</th>
                                <th className="px-6 sm:px-8 py-5 text-[11px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest">Dates</th>
                                <th className="px-6 sm:px-8 py-5 text-[11px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest">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">Balance Due</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">Total 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>
                            ) : filteredInvoices.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>\n                                            <p className="text-[11px] text-slate-500 dark:text-slate-500 leading-relaxed font-bold uppercase tracking-widest">No invoices are currently available in your account.</p>
                                        </div>
                                    </td>
                                </tr>
                            ) : (
                                filteredInvoices.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">
                                            <span className="text-sm font-black text-slate-800 dark:text-white tracking-tight truncate whitespace-nowrap">#{inv.invoiceNumber}</span>
                                        </td>
                                        <td className="px-6 sm:px-8 py-6">
                                            <div className="flex flex-col gap-1 min-w-0">
                                                <div className="flex items-center gap-2 text-[10px] font-bold text-slate-400 dark:text-slate-600 uppercase tracking-widest truncate whitespace-nowrap">
                                                    <Calendar className="w-3 h-3 shrink-0" /> {new Date(inv.issueDate).toLocaleDateString()}
                                                </div>
                                                <div className="flex items-center gap-2 text-[10px] font-black text-rose-500/60 uppercase tracking-widest truncate whitespace-nowrap">
                                                    <Clock className="w-3 h-3 shrink-0" /> Due: {new Date(inv.dueDate).toLocaleDateString()}
                                                </div>
                                            </div>
                                        </td>
                                        <td className="px-6 sm:px-8 py-6">
                                            <StatusBadge status={inv.status} />
                                        </td>
                                        <td className="px-6 sm:px-8 py-6 text-right">
                                            <span className={clsx(
                                                "text-sm font-black tracking-tight whitespace-nowrap",
                                                Number(inv.balanceDue) > 0 ? "text-rose-500" : "text-emerald-500 opacity-60"
                                            )}>
                                                <span className="text-[9px] mr-1 opacity-60 shrink-0">$</span>
                                                {Number(inv.balanceDue).toLocaleString()}
                                            </span>
                                        </td>
                                        <td className="px-6 sm:px-8 py-6 text-right">
                                            <span className="text-sm font-black text-slate-800 dark:text-white tracking-tight whitespace-nowrap">
                                                <span className="text-[9px] mr-1 opacity-60 shrink-0">$</span>
                                                {Number(inv.total).toLocaleString()}
                                            </span>
                                        </td>
                                        <td className="px-6 sm:px-8 py-6 text-right">
                                            <div className="flex justify-end items-center gap-2 opacity-100 lg:opacity-0 lg:group-hover:opacity-100 transition-all lg:translate-x-2 lg:group-hover:translate-x-0 duration-300">
                                                <a
                                                    href={billingService.getInvoicePDF(inv.id)}
                                                    target="_blank"
                                                    rel="noreferrer"
                                                    className="inline-flex items-center gap-2 px-4 py-2 bg-primary/5 hover:bg-primary text-primary hover:text-white rounded-xl text-[10px] font-black uppercase tracking-widest transition-all duration-300 hover:scale-105 active:scale-95 whitespace-nowrap shrink-0 h-10 flex items-center justify-center px-4"
                                                >
                                                    <Download className="w-3.5 h-3.5 shrink-0" />
                                                    Export PDF
                                                </a>
                                            </div>
                                        </td>
                                    </tr>
                                ))
                            )}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    );
};

export default ClientInvoiceList;
