import React, { useState, useEffect } from 'react';
import billingService from '../services/billingService';
import {
    FileCheck,
    Plus,
    Download,
    Send,
    RefreshCw,
    MoreVertical,
    CheckCircle2,
    XCircle,
    Edit2,
    Trash2,
    Printer,
    FileText,
    User,
    Calendar,
    Search
} from 'lucide-react';
import { clsx } from 'clsx';
import { useNavigate } from 'react-router-dom';
import DocumentEditor from '../components/DocumentEditor';
import settingsService from '../services/settingsService';

const QuoteList = () => {
    const [quotes, setQuotes] = useState([]);
    const [loading, setLoading] = useState(true);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [editingQuote, setEditingQuote] = useState(null);
    const [currency, setCurrency] = useState('KES');
    const [searchTerm, setSearchTerm] = useState('');
    const navigate = useNavigate();

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

    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 fetchQuotes = async () => {
        setLoading(true);
        try {
            const res = await billingService.getQuotes();
            setQuotes(res.data);
        } catch (err) {
            console.error(err);
        } finally {
            setLoading(false);
        }
    };

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

    const handleEdit = (quote) => {
        setEditingQuote(quote);
        setIsModalOpen(true);
    };

    const handleConvert = async (quoteId) => {
        if (window.confirm('Convert this Quote to an active Invoice?')) {
            try {
                const res = await billingService.convertQuote(quoteId);
                alert(`Successfully converted! Invoice ${res.data.invoiceNumber} created.`);
                navigate('/invoices');
            } catch (err) {
                alert(err.response?.data?.error || 'Error converting quote');
            }
        }
    };

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

    const StatusBadge = ({ status }) => {
        const styles = {
            'Accepted': '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',
            'Rejected': '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 === 'Accepted' && <CheckCircle2 className="w-3.5 h-3.5" />}
                {status === 'Sent' && <Send className="w-3.5 h-3.5" />}
                {status === 'Rejected' && <XCircle className="w-3.5 h-3.5" />}
                {status === 'Draft' && <FileText className="w-3.5 h-3.5" />}
                {status}
            </div>
        );
    };

    const filteredQuotes = quotes.filter(q =>
        q.quoteNumber.toLowerCase().includes(searchTerm.toLowerCase()) ||
        (q.Client?.name && q.Client.name.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">
                        <FileCheck 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">Quotes</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">Quote 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">{quotes.length} Quotes</span>
                        </div>
                    </div>
                </div>
                <button
                    onClick={handleCreate}
                    className="w-full md:w-auto btn-primary 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 Quote</span>
                </button>
            </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="Search quotes..."
                            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 rounded-2xl outline-none text-sm"
                        />
                    </div>
                </div>

                <div className="overflow-x-auto overflow-y-hidden">
                    <table className="w-full text-left min-w-[1000px]">
                        <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">Quote Number & 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">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">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">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="5" 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 quotes...</p>
                                        </div>
                                    </td>
                                </tr>
                            ) : filteredQuotes.length === 0 ? (
                                <tr>
                                    <td colSpan="5" 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">
                                                <FileCheck 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 Quotes Found</h3>
                                            <p className="text-[11px] text-slate-500 dark:text-slate-500 leading-relaxed font-bold uppercase tracking-widest">Create your first quote to get started.</p>
                                        </div>
                                    </td>
                                </tr>
                            ) : (
                                filteredQuotes.map((q) => (
                                    <tr key={q.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 flex-col min-w-0">
                                                <span className="text-sm font-black text-slate-800 dark:text-white tracking-tight">#{q.quoteNumber}</span>
                                                <div className="flex items-center gap-1.5 mt-1 text-[10px] font-black text-slate-400 dark:text-slate-600 uppercase tracking-widest truncate">
                                                    <User className="w-3 h-3 shrink-0" /> {q.Client?.name}
                                                </div>
                                            </div>
                                        </td>
                                        <td className="px-6 sm:px-8 py-6">
                                            <div className="flex items-center gap-2 text-xs font-bold text-slate-600 dark:text-slate-400 whitespace-nowrap">
                                                <Calendar className="w-3.5 h-3.5 text-slate-300 dark:text-slate-700 shrink-0" />
                                                {new Date(q.issueDate).toLocaleDateString()}
                                            </div>
                                        </td>
                                        <td className="px-6 sm:px-8 py-6">
                                            <StatusBadge status={q.status} />
                                        </td>
                                        <td className="px-6 sm:px-8 py-6 text-right whitespace-nowrap">
                                            <span className="text-sm font-black text-slate-800 dark:text-white tracking-tight">
                                                <span className="text-[9px] mr-1 opacity-60 shrink-0">{currency}</span>
                                                {Number(q.total).toLocaleString()}
                                            </span>
                                        </td>
                                        <td className="px-6 sm:px-8 py-6 text-right">
                                            <div className="flex justify-end items-center gap-1 lg:opacity-0 group-hover:opacity-100 transition-all lg:translate-x-2 group-hover:translate-x-0 duration-300">
                                                <button onClick={() => handleEdit(q)} 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 Quote"><Edit2 className="w-4 h-4 shrink-0" /></button>
                                                <a href={billingService.getQuotePDF(q.id, 'download')} target="_blank" rel="noreferrer" 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="Download PDF"><Download className="w-4 h-4 shrink-0" /></a>
                                                <a href={billingService.getQuotePDF(q.id, 'view')} target="_blank" rel="noreferrer" className="p-2.5 text-slate-400 hover:text-indigo-600 hover:bg-indigo-50 dark:hover:bg-indigo-500/10 rounded-xl transition-all shrink-0" title="Print Quote"><Printer className="w-4 h-4 shrink-0" /></a>

                                                {q.status !== 'Accepted' && (
                                                    <button onClick={() => handleConvert(q.id)} className="p-2.5 text-amber-500 hover:bg-amber-500/10 rounded-xl transition-all shrink-0" title="Convert to Invoice"><RefreshCw className="w-4 h-4 shrink-0" /></button>
                                                )}

                                                <button
                                                    onClick={async () => {
                                                        try {
                                                            await billingService.sendQuote(q.id);
                                                            alert('Quote email sent!');
                                                            fetchQuotes();
                                                        } catch (err) { alert('Failed to send email'); }
                                                    }}
                                                    className="p-2.5 text-blue-500 hover:bg-blue-500/10 rounded-xl transition-all shrink-0"
                                                    title="Send Email"
                                                >
                                                    <Send className="w-4 h-4 shrink-0" />
                                                </button>

                                                <button onClick={() => handleDelete(q.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 Quote"><Trash2 className="w-4 h-4 shrink-0" /></button>
                                            </div>
                                        </td>
                                    </tr>
                                ))
                            )}
                        </tbody>
                    </table>
                </div>
            </div>

            <DocumentEditor
                isOpen={isModalOpen}
                onClose={() => setIsModalOpen(false)}
                onRefresh={fetchQuotes}
                type="Quote"
                initialData={editingQuote}
            />
        </div>
    );
};

export default QuoteList;
