import React, { useState, useEffect } from 'react';
import {
    X, Plus, Trash2, Loader2, FileText, User, Calendar,
    Save, Send, Download, Eye, ChevronRight, Hash, Search,
    Info, Settings, MoreHorizontal, Printer, Copy, Clock, RefreshCw,
    CheckCircle, Shield, Zap, Globe, Cpu, Layout, Layers, ChevronDown
} from 'lucide-react';
import { clsx } from 'clsx';
import billingService from '../services/billingService';
import settingsService from '../services/settingsService';

const DocumentEditor = ({ isOpen, onClose, onRefresh, type = 'Invoice', initialData = null }) => {
    const [loading, setLoading] = useState(false);
    const [clients, setClients] = useState([]);
    const [formData, setFormData] = useState({
        clientId: '',
        documentNumber: '',
        issueDate: new Date().toISOString().split('T')[0],
        dueDate: new Date(Date.now() + 15 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
        status: 'Draft',
        notes: '',
        discount: 0,
        status: 'Draft',
        notes: '',
        discount: 0,
        items: [{ description: '', quantity: 1, unitPrice: 0, taxRate: 0, taxAmount: 0 }],
        isRecurring: false,
        recurringFrequency: 'Monthly',
        recurringInterval: 1,
        recurringStartDate: '',
        recurringEndDate: '',
        taxes: []
    });

    const [sysSettings, setSysSettings] = useState({});
    const [availableTaxRates, setAvailableTaxRates] = useState([]);
    const [fetchingTaxes, setFetchingTaxes] = useState(false);

    useEffect(() => {
        if (isOpen) {
            fetchClients();
            fetchSettings();
            if (initialData) {
                setFormData({
                    ...initialData,
                    clientId: initialData.clientId || '',
                    items: initialData.items || [{ description: '', quantity: 1, unitPrice: 0 }],
                    isRecurring: initialData.isRecurring || false,
                    recurringFrequency: initialData.recurringFrequency || 'Monthly',
                    recurringInterval: initialData.recurringInterval || 1,
                    recurringStartDate: initialData.recurringStartDate || '',
                    recurringEndDate: initialData.recurringEndDate || ''
                });
            } else {
                setFormData({
                    clientId: '',
                    documentNumber: 'AUTO',
                    issueDate: new Date().toISOString().split('T')[0],
                    dueDate: new Date(Date.now() + 15 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
                    status: 'Draft',
                    notes: '',
                    discount: 0,
                    theme: 'Professional',
                    items: [{ description: '', quantity: 1, unitPrice: 0, taxRate: 0, taxAmount: 0 }],
                    isRecurring: false,
                    recurringFrequency: 'Monthly',
                    recurringInterval: 1,
                    recurringStartDate: '',
                    recurringEndDate: '',
                    taxes: []
                });
            }
        }
    }, [isOpen, initialData]);

    useEffect(() => {
        if (isOpen) {
            fetchTaxRates();
        }
    }, [isOpen]);

    const fetchTaxRates = async () => {
        setFetchingTaxes(true);
        try {
            const res = await settingsService.getTaxRates();
            setAvailableTaxRates(res.data);
        } catch (err) {
            console.error('Failed to fetch tax rates', err);
        } finally {
            setFetchingTaxes(false);
        }
    };

    const fetchClients = async () => {
        try {
            const res = await billingService.getClients();
            setClients(res.data);
        } catch (err) {
            console.error(err);
        }
    };

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

    const calculateSubtotal = () => {
        return formData.items.reduce((sum, item) => sum + (Number(item.quantity) * Number(item.unitPrice)), 0);
    };

    const calculateItemTax = () => {
        return formData.items.reduce((sum, item) => sum + (Number(item.taxAmount) || 0), 0);
    };

    const calculateDocumentTax = () => {
        const subtotal = calculateSubtotal();
        return (formData.taxes || []).reduce((sum, t) => sum + (subtotal * (Number(t.percentage) / 100)), 0);
    };

    const calculateTax = () => {
        return calculateItemTax() + calculateDocumentTax();
    };

    const calculateTotal = () => {
        return calculateSubtotal() + calculateTax() - Number(formData.discount || 0);
    };

    const updateItem = (index, field, value) => {
        const newItems = [...formData.items];
        newItems[index][field] = value;

        if (field === 'quantity' || field === 'unitPrice' || field === 'taxRate') {
            const qty = Number(newItems[index].quantity) || 0;
            const price = Number(newItems[index].unitPrice) || 0;
            const rate = Number(newItems[index].taxRate) || 0;
            newItems[index].taxAmount = (qty * price) * (rate / 100);
            newItems[index].lineTotal = (qty * price) + newItems[index].taxAmount;
        }

        setFormData({ ...formData, items: newItems });
    };

    const toggleDocumentTax = (tax) => {
        const isSelected = formData.taxes.some(t => t.id === tax.id);
        if (isSelected) {
            setFormData({ ...formData, taxes: formData.taxes.filter(t => t.id !== tax.id) });
        } else {
            setFormData({ ...formData, taxes: [...formData.taxes, tax] });
        }
    };

    const removeItem = (index) => {
        const newItems = formData.items.filter((_, i) => i !== index);
        setFormData({ ...formData, items: newItems });
    };

    const addItem = () => {
        setFormData({
            ...formData,
            items: [...formData.items, { description: '', quantity: 1, unitPrice: 0, taxRate: 0, taxAmount: 0 }]
        });
    };

    const currencySymbol = sysSettings.DEFAULT_CURRENCY || 'KES';
    const taxRatePercent = sysSettings.COMPANY_TAX_RATE || '0';

    const handleSubmit = async (e, shouldSend = false) => {
        if (e) e.preventDefault();
        setLoading(true);
        try {
            const subtotal = calculateSubtotal();
            const tax = calculateTax();
            const total = calculateTotal();
            const data = {
                ...formData,
                subtotal,
                tax,
                total,
                balanceDue: total
            };

            let response;
            if (type === 'Invoice') {
                if (initialData) response = await billingService.updateInvoice(initialData.id, data);
                else response = await billingService.createInvoice(data);
            } else {
                if (initialData) response = await billingService.updateQuote(initialData.id, data);
                else response = await billingService.createQuote(data);
            }

            const documentId = initialData?.id || response.data.id;

            if (shouldSend) {
                if (type === 'Invoice') {
                    await billingService.sendInvoice(documentId);
                } else {
                    await billingService.sendQuote(documentId);
                }
            }

            onRefresh();
            onClose();
        } catch (err) {
            alert(err.response?.data?.error || `Error saving ${type}`);
        } finally {
            setLoading(false);
        }
    };

    if (!isOpen) return null;

    const selectedClient = clients.find(c => c.id === parseInt(formData.clientId));

    return (
        <div className="fixed inset-0 z-[150] flex flex-col bg-slate-50 dark:bg-slate-950 animate-in fade-in duration-500">
            {/* Top Navigation / Header */}
            <div className="h-auto min-h-[5rem] py-4 bg-white dark:bg-slate-900 border-b border-slate-200 dark:border-slate-800 px-4 sm:px-10 flex flex-col sm:flex-row items-center justify-between gap-4 shadow-xl shadow-slate-200/50 dark:shadow-none z-10">
                <div className="flex items-center gap-3 sm:gap-6 w-full sm:w-auto">
                    <button onClick={onClose} className="p-2 sm:p-3 hover:bg-slate-100 dark:hover:bg-slate-800 rounded-2xl transition-all group">
                        <X className="w-5 h-5 text-slate-400 group-hover:rotate-90 transition-transform" />
                    </button>
                    <div className="h-8 sm:h-10 w-[1px] bg-slate-100 dark:bg-slate-800" />
                    <div className="flex flex-col">
                        <div className="flex items-center gap-2">
                            <span className="text-sm sm:text-lg font-black text-slate-900 dark:text-white uppercase tracking-tight">{initialData ? 'Edit' : 'Create'} {type}</span>
                            <div className={clsx(
                                "px-2 py-0.5 rounded text-[8px] font-black uppercase tracking-widest",
                                initialData ? "bg-amber-500/10 text-amber-500" : "bg-emerald-500/10 text-emerald-500"
                            )}>
                                {initialData ? 'Existing' : 'New'}
                            </div>
                        </div>
                        <span className="text-[10px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-[0.3em] leading-none mt-1">
                            {formData.documentNumber === 'AUTO' ? 'Draft' : formData.documentNumber}
                        </span>
                    </div>
                </div>

                <div className="flex items-center gap-3 sm:gap-5 w-full sm:w-auto justify-end">
                    <div className="flex items-center gap-2">
                        <button
                            onClick={(e) => handleSubmit(e, false)}
                            className="px-4 sm:px-8 py-2.5 sm:py-3 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 text-slate-800 dark:text-white font-black text-[9px] sm:text-[10px] uppercase tracking-widest rounded-xl sm:rounded-2xl hover:border-primary transition-all flex items-center gap-2 sm:gap-3 shadow-sm"
                            disabled={loading}
                        >
                            {loading ? <Loader2 className="w-3 sm:w-4 h-3 sm:h-4 animate-spin text-primary" /> : <Save className="w-3 sm:w-4 h-3 sm:h-4 text-primary" />}
                            <span className="hidden xs:inline">Save</span>
                        </button>
                        <button
                            onClick={(e) => handleSubmit(e, true)}
                            className="px-4 sm:px-8 py-2.5 sm:py-3 bg-primary text-white font-black text-[9px] sm:text-[10px] uppercase tracking-widest rounded-xl sm:rounded-2xl hover:bg-indigo-700 shadow-xl shadow-primary/20 transition-all flex items-center gap-2 sm:gap-3"
                            disabled={loading}
                        >
                            {loading ? <Loader2 className="w-3 sm:w-4 h-3 sm:h-4 animate-spin" /> : <Send className="w-3 sm:w-4 h-3 sm:h-4" />}
                            <span className="hidden xs:inline">Send</span>
                        </button>
                    </div>
                </div>
            </div>

            {/* Main Content Area */}
            <div className="flex-1 overflow-y-auto bg-white dark:bg-slate-900/50 custom-scrollbar">
                <div className="max-w-6xl mx-auto p-6 sm:p-10 lg:p-16 space-y-12 sm:space-y-20">
                    {/* Section 1: Client & General Info */}
                    <section className="space-y-8 sm:space-y-12">
                        <div className="flex flex-col md:flex-row items-start justify-between gap-8 md:gap-12">
                            <div className="space-y-6 sm:space-y-8 flex-1 w-full">
                                <div className="space-y-3">
                                    <label className="premium-label !ml-1">Client*</label>
                                    <div className="flex gap-4">
                                        <div className="relative flex-1 group/input">
                                            <div className="absolute left-4 top-1/2 -translate-y-1/2 w-4 sm:w-5 h-4 sm:h-5 text-slate-300 dark:text-slate-700 group-focus-within/input:text-primary transition-colors">
                                                <User className="w-full h-full" />
                                            </div>
                                            <select
                                                required
                                                className="premium-input !pl-10 sm:!pl-12 !py-3 sm:!py-4 appearance-none !font-black !text-xs sm:!text-sm cursor-pointer"
                                                value={formData.clientId}
                                                onChange={(e) => setFormData({ ...formData, clientId: e.target.value })}
                                            >
                                                <option value="">Select Client...</option>
                                                {clients.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
                                            </select>
                                            <ChevronDown className="absolute right-4 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-300 pointer-events-none" />
                                        </div>
                                        <button type="button" className="p-3 sm:p-4 bg-primary/10 text-primary rounded-xl sm:rounded-2xl hover:bg-primary hover:text-white transition-all shadow-sm active:scale-95">
                                            <Search className="w-5 h-5 px-0.5" />
                                        </button>
                                    </div>
                                </div>

                                {selectedClient && (
                                    <div className="p-4 sm:p-6 bg-primary/5 dark:bg-primary/10 rounded-[2rem] border border-primary/10 flex items-start gap-4 sm:gap-5 animate-in slide-in-from-top-4 duration-500">
                                        <div className="p-2 sm:p-3 bg-white dark:bg-slate-900 rounded-lg sm:rounded-xl shadow-sm">
                                            <Info className="w-4 sm:w-5 h-4 sm:h-5 text-primary" />
                                        </div>
                                        <div className="text-[10px] sm:text-xs space-y-1 sm:space-y-2 font-medium">
                                            <p className="font-black text-slate-800 dark:text-white uppercase tracking-widest text-[9px] sm:text-[10px]">{selectedClient.name}</p>
                                            <div className="space-y-1 text-slate-500 dark:text-slate-400 italic">
                                                <p className="flex items-center gap-2"><Globe className="w-3 sm:w-3.5 h-3 sm:h-3.5" /> {selectedClient.billingAddress}</p>
                                                <p className="flex items-center gap-2"><Send className="w-3 sm:w-3.5 h-3 sm:h-3.5" /> {selectedClient.email}</p>
                                            </div>
                                        </div>
                                    </div>
                                )}
                            </div>

                            <div className="h-32 sm:h-44 w-full md:w-44 bg-slate-50 dark:bg-slate-900/40 border-2 border-dashed border-slate-200 dark:border-slate-800 rounded-[2rem] sm:rounded-[2.5rem] flex flex-col items-center justify-center gap-3 hover:border-primary/50 transition-all cursor-pointer text-slate-300 dark:text-slate-700 group relative overflow-hidden shrink-0">
                                {sysSettings.COMPANY_LOGO ? (
                                    <div className="w-full h-full p-4 sm:p-6 flex items-center justify-center transition-transform group-hover:scale-110 duration-700">
                                        <img
                                            src={`http://localhost:5000${sysSettings.COMPANY_LOGO}`}
                                            alt="Logo"
                                            className="max-w-full max-h-full object-contain filter dark:brightness-110"
                                        />
                                    </div>
                                ) : (
                                    <>
                                        <div className="p-3 sm:p-4 bg-white dark:bg-slate-800 rounded-xl sm:rounded-2xl shadow-lg group-hover:rotate-12 transition-transform duration-500">
                                            <Layout className="w-5 sm:w-6 h-5 sm:h-6 text-slate-300 dark:text-slate-600" />
                                        </div>
                                        <span className="text-[9px] sm:text-[10px] font-black uppercase tracking-widest opacity-40">Add Logo</span>
                                    </>
                                )}
                            </div>
                        </div>

                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-6 sm:gap-10">
                            <div className="space-y-3">
                                <label className="premium-label !ml-1">{type} Number*</label>
                                <div className="relative group/input">
                                    <Hash className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-300 group-focus-within/input:text-primary transition-colors" />
                                    <input
                                        className="premium-input !pl-12 !font-black !text-xs sm:!text-sm italic opacity-60"
                                        value={formData.documentNumber || 'AUTO-GENERATED'}
                                        readOnly
                                    />
                                </div>
                            </div>
                            <div className="space-y-3">
                                <label className="premium-label !ml-1">Purchase Order (PO#)</label>
                                <div className="relative group/input">
                                    <Zap className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-300 group-focus-within/input:text-primary transition-colors" />
                                    <input
                                        className="premium-input !pl-12 !font-bold !text-xs sm:!text-sm"
                                        placeholder="Enter PO Number"
                                        value={formData.orderNumber || ''}
                                        onChange={(e) => setFormData({ ...formData, orderNumber: e.target.value })}
                                    />
                                </div>
                            </div>
                        </div>

                        <div className="grid grid-cols-1 sm:grid-cols-3 gap-6 sm:gap-8">
                            <div className="space-y-3">
                                <label className="premium-label !ml-1">Issue Date*</label>
                                <div className="relative group/input">
                                    <Calendar className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-300 group-focus-within/input:text-primary transition-colors" />
                                    <input
                                        type="date"
                                        className="premium-input !pl-11 !text-xs sm:!text-sm"
                                        value={formData.issueDate}
                                        onChange={(e) => setFormData({ ...formData, issueDate: e.target.value })}
                                    />
                                </div>
                            </div>
                            <div className="space-y-3">
                                <label className="premium-label !ml-1">Payment Terms</label>
                                <div className="relative group/input">
                                    <Clock className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-300 group-focus-within/input:text-primary transition-colors" />
                                    <select
                                        className="premium-input !pl-11 appearance-none cursor-pointer !font-bold !text-xs sm:!text-sm"
                                        value={formData.paymentTerms || 'Due on Receipt'}
                                        onChange={(e) => setFormData({ ...formData, paymentTerms: e.target.value })}
                                    >
                                        <option>Due on Receipt</option>
                                        <option>Net 15 Days</option>
                                        <option>Net 30 Days</option>
                                        <option>Net 60 Days</option>
                                    </select>
                                    <ChevronDown className="absolute right-4 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-300 pointer-events-none" />
                                </div>
                            </div>
                            <div className="space-y-3">
                                <label className="premium-label !ml-1">Due Date</label>
                                <div className="relative group/input">
                                    <Calendar className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-300 group-focus-within/input:text-primary transition-colors" />
                                    <input
                                        type="date"
                                        className="premium-input !pl-11 !text-xs sm:!text-sm"
                                        value={formData.dueDate}
                                        onChange={(e) => setFormData({ ...formData, dueDate: e.target.value })}
                                    />
                                </div>
                            </div>
                        </div>
                    </section>

                    {/* Section 2: Line Items */}
                    <section className="space-y-6 sm:space-y-8">
                        <div className="flex items-center justify-between">
                            <h3 className="text-xs sm:text-sm font-black text-slate-800 dark:text-white uppercase tracking-[0.2em] flex items-center gap-2 sm:gap-3">
                                <div className="p-1.5 sm:p-2 bg-slate-900 rounded-lg text-white">
                                    <Layers className="w-3 sm:w-4 h-3 sm:h-4" />
                                </div>
                                Line Items
                            </h3>
                            <div className="flex gap-4">
                                <button
                                    type="button"
                                    onClick={addItem}
                                    className="px-4 sm:px-6 py-2 sm:py-2.5 bg-slate-900 text-white rounded-xl text-[8px] sm:text-[10px] font-black uppercase tracking-widest hover:bg-black transition-all flex items-center gap-2 sm:gap-3 shadow-xl shadow-slate-900/20 active:scale-95"
                                >
                                    <Plus className="w-3 sm:w-4 h-3 sm:h-4" /> Add Item
                                </button>
                            </div>
                        </div>

                        <div className="premium-card !p-0 overflow-hidden !rounded-[1.5rem] sm:!rounded-[2.5rem] border-slate-100 dark:border-slate-800/50">
                            <div className="overflow-x-auto no-scrollbar">
                                <table className="w-full min-w-[700px] sm:min-w-0">
                                    <thead>
                                        <tr className="bg-slate-50/50 dark:bg-slate-900/50 border-b border-slate-100 dark:border-slate-800">
                                            <th className="px-4 sm:px-8 py-4 sm:py-5 text-left text-[9px] sm:text-[10px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest">Description</th>
                                            <th className="px-3 sm:px-6 py-4 sm:py-5 text-center text-[9px] sm:text-[10px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest w-20 sm:w-28">Quantity</th>
                                            <th className="px-3 sm:px-6 py-4 sm:py-5 text-right text-[9px] sm:text-[10px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest w-32 sm:w-40">Unit Price</th>
                                            <th className="px-3 sm:px-6 py-4 sm:py-5 text-right text-[9px] sm:text-[10px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest w-32 sm:w-40">Tax</th>
                                            <th className="px-4 sm:px-8 py-4 sm:py-5 text-right text-[9px] sm:text-[10px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest w-32 sm:w-40">Total</th>
                                            <th className="px-2 sm:px-4 py-4 sm:py-5 w-10 sm:w-14"></th>
                                        </tr>
                                    </thead>
                                    <tbody className="divide-y divide-slate-50 dark:divide-slate-800/50">
                                        {formData.items.map((item, index) => (
                                            <tr key={index} className="group hover:bg-slate-50/50 dark:hover:bg-slate-900/30 transition-colors">
                                                <td className="p-2 sm:p-4 px-4 sm:px-8">
                                                    <textarea
                                                        rows="1"
                                                        placeholder="Enter item description..."
                                                        className="w-full p-2 sm:p-3 bg-transparent border-none rounded-lg sm:rounded-xl text-xs sm:text-sm font-bold text-slate-800 dark:text-white focus:ring-2 focus:ring-primary/10 outline-none resize-none italic"
                                                        value={item.description}
                                                        onChange={(e) => updateItem(index, 'description', e.target.value)}
                                                    />
                                                </td>
                                                <td className="p-2 sm:p-4 px-3 sm:px-6">
                                                    <input
                                                        type="number"
                                                        className="w-full p-2 sm:p-3 bg-slate-50/50 dark:bg-slate-800/50 text-center border-none rounded-lg sm:rounded-xl font-black text-xs sm:text-sm outline-none focus:ring-2 focus:ring-primary/10"
                                                        value={item.quantity}
                                                        onChange={(e) => updateItem(index, 'quantity', e.target.value)}
                                                    />
                                                </td>
                                                <td className="p-2 sm:p-4 px-3 sm:px-6 relative group/cell">
                                                    <span className="absolute left-6 top-1/2 -translate-y-1/2 text-slate-300 dark:text-slate-700 font-bold text-[10px] sm:text-xs">{currencySymbol}</span>
                                                    <input
                                                        type="number"
                                                        className="w-full p-2 sm:p-3 pl-8 sm:pl-10 bg-slate-50/50 dark:bg-slate-800/50 text-right font-black text-xs sm:text-sm outline-none rounded-lg sm:rounded-xl focus:ring-2 focus:ring-primary/10 text-primary italic"
                                                        value={item.unitPrice}
                                                        onChange={(e) => updateItem(index, 'unitPrice', e.target.value)}
                                                    />
                                                </td>
                                                <td className="p-2 sm:p-4 px-3 sm:px-6">
                                                    <div className="relative group/cell">
                                                        <select
                                                            className="w-full p-2 sm:p-3 pr-6 sm:pr-8 bg-slate-50/50 dark:bg-slate-800/50 border-none rounded-lg sm:rounded-xl text-right font-bold text-[10px] sm:text-xs outline-none appearance-none cursor-pointer focus:ring-2 focus:ring-primary/10 text-slate-500"
                                                            value={item.taxRate}
                                                            onChange={(e) => updateItem(index, 'taxRate', e.target.value)}
                                                        >
                                                            <option value="0">0%</option>
                                                            {availableTaxRates.map(t => <option key={t.id} value={t.percentage}>{t.name} ({t.percentage}%)</option>)}
                                                        </select>
                                                        <ChevronDown className="absolute right-2 sm:right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-300 pointer-events-none" />
                                                    </div>
                                                </td>
                                                <td className="p-2 sm:p-4 px-4 sm:px-8 text-right font-black text-xs sm:text-sm text-slate-800 dark:text-white tabular-nums">
                                                    <span className="text-[9px] sm:text-[10px] opacity-30 mr-1 font-medium">{currencySymbol}</span>
                                                    {((Number(item.quantity) * Number(item.unitPrice)) + (Number(item.taxAmount) || 0)).toLocaleString()}
                                                </td>
                                                <td className="p-2 sm:p-4 px-2 sm:px-4 text-center">
                                                    {formData.items.length > 1 && (
                                                        <button
                                                            type="button"
                                                            onClick={() => removeItem(index)}
                                                            className="p-2 sm:p-3 text-slate-300 dark:text-slate-700 hover:text-rose-500 hover:bg-rose-500/10 rounded-lg sm:rounded-xl transition-all opacity-100 sm:opacity-0 group-hover:opacity-100"
                                                        >
                                                            <Trash2 className="w-4 sm:w-5 h-4 sm:h-5" />
                                                        </button>
                                                    )}
                                                </td>
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </section>

                    {/* Section 3: Summary & Notes */}
                    <section className="flex flex-col md:flex-row gap-8 sm:gap-16 pt-8 sm:pt-16 border-t border-slate-100 dark:border-slate-800/50">
                        <div className="flex-1 space-y-4 sm:space-y-6">
                            <label className="premium-label !ml-1">Notes</label>
                            <textarea
                                className="premium-input !py-4 sm:!py-6 !text-xs sm:!text-sm !min-h-[150px] sm:!min-h-[220px] resize-none italic leading-relaxed"
                                placeholder="Enter additional notes here..."
                                value={formData.notes}
                                onChange={(e) => setFormData({ ...formData, notes: e.target.value })}
                            />
                            <div className="flex items-center gap-3 p-4 sm:p-5 bg-slate-50 dark:bg-slate-900/40 rounded-2xl text-[9px] sm:text-[10px] font-bold text-slate-400 dark:text-slate-600 uppercase tracking-widest italic border border-slate-100 dark:border-slate-800">
                                <Shield className="w-3.5 sm:w-4 h-3.5 sm:h-4" />
                                <span>Secure Document</span>
                            </div>
                        </div>

                        <div className="w-full md:w-[22rem] space-y-6 sm:space-y-8 bg-slate-900 dark:bg-slate-950 text-white p-6 sm:p-10 rounded-[2.5rem] sm:rounded-[3.5rem] shadow-4xl relative overflow-hidden group border border-white/5 mx-auto">
                            <div className="absolute top-0 right-0 w-64 h-64 -mr-32 -mt-32 bg-primary/20 rounded-full blur-[100px] animate-pulse duration-[8000ms]" />
                            <div className="absolute bottom-0 left-0 w-48 h-48 -ml-24 -mb-24 bg-emerald-500/10 rounded-full blur-[800px]" />

                            <div className="relative z-10 flex flex-col h-full">
                                <h4 className="text-[9px] sm:text-[10px] font-black uppercase tracking-[0.3em] text-slate-500 mb-6 sm:mb-10 pb-4 sm:pb-6 border-b border-white/5 flex items-center gap-3">
                                    <div className="w-1.5 h-1.5 rounded-full bg-primary animate-pulse" />
                                    Summary
                                </h4>

                                <div className="space-y-4 sm:space-y-6 font-medium">
                                    <div className="flex justify-between items-center text-xs sm:text-sm">
                                        <span className="text-slate-500 uppercase tracking-widest text-[8px] sm:text-[9px] font-black">Subtotal</span>
                                        <span className="font-bold tabular-nums italic text-slate-300">{currencySymbol} {calculateSubtotal().toLocaleString()}</span>
                                    </div>
                                    <div className="flex justify-between items-center text-xs sm:text-sm">
                                        <span className="text-slate-500 uppercase tracking-widest text-[8px] sm:text-[9px] font-black">Total Tax</span>
                                        <span className="font-bold tabular-nums italic text-slate-300">{currencySymbol} {calculateTax().toLocaleString()}</span>
                                    </div>

                                    <div className="space-y-2 sm:space-y-3 !mt-6 sm:!mt-10">
                                        <label className="text-[8px] sm:text-[9px] font-black text-slate-500 uppercase tracking-[0.2em] pl-1">Discount</label>
                                        <div className="relative group/input">
                                            <span className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-600 font-bold text-[10px]">{currencySymbol}</span>
                                            <input
                                                type="number"
                                                className="w-full pl-10 pr-4 py-2.5 sm:py-3 bg-white/5 border border-white/5 rounded-2xl text-xs sm:text-sm font-black outline-none focus:border-primary/50 transition-all text-rose-400 text-right"
                                                value={formData.discount}
                                                onChange={(e) => setFormData({ ...formData, discount: e.target.value })}
                                            />
                                        </div>
                                    </div>

                                    <div className="pt-4 sm:pt-6 border-t border-white/5 space-y-3 sm:space-y-4">
                                        <label className="text-[8px] sm:text-[9px] font-black text-slate-500 uppercase tracking-[0.2em] pl-1">Document Taxes</label>
                                        <div className="flex flex-wrap gap-2">
                                            {availableTaxRates.map(tax => (
                                                <button
                                                    key={tax.id}
                                                    type="button"
                                                    onClick={() => toggleDocumentTax(tax)}
                                                    className={clsx(
                                                        "px-3 sm:px-4 py-1.5 sm:py-2 rounded-lg sm:rounded-xl text-[8px] sm:text-[9px] font-black uppercase tracking-widest transition-all border whitespace-nowrap",
                                                        formData.taxes.some(t => t.id === tax.id)
                                                            ? "bg-primary border-primary text-white shadow-lg shadow-primary/20"
                                                            : "bg-white/5 border-white/5 text-slate-500 hover:text-slate-300 hover:bg-white/10"
                                                    )}
                                                >
                                                    {tax.name}
                                                </button>
                                            ))}
                                            {availableTaxRates.length === 0 && <span className="text-[9px] sm:text-[10px] text-slate-600 italic">No taxes configured</span>}
                                        </div>
                                    </div>

                                    <div className="pt-8 sm:pt-12 mt-auto flex flex-col gap-1 sm:gap-2">
                                        <span className="text-primary uppercase tracking-[0.4em] text-[8px] sm:text-[9px] font-black text-center mb-2">Total Amount</span>
                                        <div className="flex justify-center items-baseline gap-2">
                                            <span className="text-slate-500 text-xs sm:text-sm font-bold opacity-40">{currencySymbol}</span>
                                            <span className="text-3xl sm:text-5xl font-black italic tracking-tighter tabular-nums drop-shadow-xl">{calculateTotal().toLocaleString()}</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </section>
                </div>
            </div>
        </div>
    );
};

export default DocumentEditor;
