import React, { useState, useEffect } from 'react';
import { subscriptionService } from '../services/phase4Services';
import billingService from '../services/billingService';
import settingsService from '../services/settingsService';
import {
    Repeat,
    Plus,
    Clock,
    CheckCircle,
    XCircle,
    PauseCircle,
    Calendar,
    Zap,
    Edit2,
    Trash2,
    ArrowRightLeft,
    DollarSign,
    Box
} from 'lucide-react';
import { clsx } from 'clsx';

const SubscriptionList = () => {
    const [subscriptions, setSubscriptions] = useState([]);
    const [loading, setLoading] = useState(true);
    const [clients, setClients] = useState([]);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [editingSub, setEditingSub] = useState(null);
    const [formData, setFormData] = useState({
        name: '',
        clientId: '',
        billingCycle: 'Monthly',
        startDate: new Date().toISOString().split('T')[0],
        nextBillingDate: new Date().toISOString().split('T')[0],
        amount: '',
        status: 'Active',
        autoSendInvoice: true,
        prorateFirstMonth: false,
        dueDays: 7
    });

    const [selectedClient, setSelectedClient] = useState('');
    const [clientInvoices, setClientInvoices] = useState([]);
    const [targetInvoice, setTargetInvoice] = useState(null);
    const [currency, setCurrency] = useState('KES');

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

    const fetchSettings = async () => {
        try {
            const res = await settingsService.getSettings();
            const settings = res.data.reduce((acc, curr) => ({ ...acc, [curr.key]: curr.value }), {});
            if (settings.DEFAULT_CURRENCY) setCurrency(settings.DEFAULT_CURRENCY);
        } catch (err) {
            console.error(err);
        }
    };

    useEffect(() => {
        if (selectedClient) {
            fetchClientInvoices(selectedClient);
        } else {
            setClientInvoices([]);
        }
    }, [selectedClient]);

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

    const fetchClientInvoices = async (clientId) => {
        try {
            const res = await billingService.getInvoices();
            // Filter invoices by client manually if backend doesn't support query
            const filtered = res.data.filter(inv => inv.clientId === clientId && inv.status !== 'Draft');
            setClientInvoices(filtered);
        } catch (err) {
            console.error(err);
        }
    };

    const fetchSubscriptions = async () => {
        try {
            const res = await subscriptionService.getAll();
            setSubscriptions(res.data);
        } catch (err) {
            console.error(err);
        } finally {
            setLoading(false);
        }
    };

    const handleRunScheduler = async () => {
        if (window.confirm('Run the recurring invoice scheduler manually?')) {
            try {
                const res = await subscriptionService.runScheduler();
                alert(`Processed ${res.data.processed.length} subscriptions.`);
                fetchSubscriptions();
            } catch (err) {
                alert('Scheduler failed.');
            }
        }
    };

    const handleMarkRecurrent = (inv) => {
        setTargetInvoice(inv);
        setEditingSub(null);
        setFormData({
            name: `Recurring: ${inv.invoiceNumber}`,
            clientId: inv.clientId,
            billingCycle: 'Monthly',
            startDate: new Date().toISOString().split('T')[0],
            nextBillingDate: new Date().toISOString().split('T')[0],
            amount: inv.total,
            status: 'Active',
            autoSendInvoice: true
        });
        setIsModalOpen(true);
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        setIsSubmitting(true);
        try {
            if (targetInvoice) {
                await subscriptionService.createFromInvoice(targetInvoice.id, formData);
            } else if (editingSub) {
                await subscriptionService.update(editingSub.id, formData);
            } else {
                await subscriptionService.create(formData);
            }
            setIsModalOpen(false);
            setEditingSub(null);
            setTargetInvoice(null);
            fetchSubscriptions();
            setFormData({
                name: '',
                clientId: '',
                billingCycle: 'Monthly',
                startDate: new Date().toISOString().split('T')[0],
                nextBillingDate: new Date().toISOString().split('T')[0],
                amount: '',
                status: 'Active',
                autoSendInvoice: true,
                prorateFirstMonth: false,
                dueDays: 7
            });
        } catch (err) {
            alert(err.response?.data?.error || 'Failed to save subscription');
        } finally {
            setIsSubmitting(false);
        }
    };

    const handleEdit = (sub) => {
        setTargetInvoice(null);
        setEditingSub(sub);
        setFormData({
            name: sub.name,
            clientId: sub.clientId,
            billingCycle: sub.billingCycle,
            startDate: sub.startDate,
            nextBillingDate: sub.nextBillingDate,
            amount: sub.amount,
            status: sub.status,
            autoSendInvoice: sub.autoSendInvoice,
            prorateFirstMonth: false,
            dueDays: sub.dueDays || 7
        });
        setIsModalOpen(true);
    };

    const handleDelete = async (id) => {
        if (window.confirm('Are you sure you want to delete this subscription? No more invoices will be generated.')) {
            try {
                await subscriptionService.delete(id);
                fetchSubscriptions();
            } catch (err) {
                alert('Error deleting subscription');
            }
        }
    };

    const StatusBadge = ({ status }) => {
        const styles = {
            'Active': 'bg-emerald-500/10 text-emerald-500 border-emerald-500/20 shadow-sm shadow-emerald-500/5',
            'Paused': 'bg-amber-500/10 text-amber-500 border-amber-500/20 shadow-sm shadow-amber-500/5',
            'Cancelled': 'bg-rose-500/10 text-rose-500 border-rose-500/20 shadow-sm shadow-rose-500/5',
        };
        const icons = {
            'Active': <CheckCircle className="w-3.5 h-3.5" />,
            'Paused': <PauseCircle className="w-3.5 h-3.5" />,
            'Cancelled': <XCircle className="w-3.5 h-3.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['Active'])}>
                {icons[status] || icons['Active']}
                {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">
                        <Repeat 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">Subscriptions</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">Recurring Billing</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">{subscriptions.length} Subscriptions</span>
                        </div>
                    </div>
                </div>
                <div className="flex flex-col sm:flex-row items-center gap-3 w-full md:w-auto">
                    <button
                        onClick={handleRunScheduler}
                        className="btn-secondary px-6 flex items-center justify-center gap-2 w-full sm:w-auto h-12 lg:h-14"
                    >
                        <Zap className="w-4 h-4 text-amber-500 shrink-0" />
                        <span className="text-[10px] sm:text-[11px] font-black uppercase tracking-widest whitespace-nowrap">Run Scheduler</span>
                    </button>
                    <button
                        onClick={() => {
                            setEditingSub(null);
                            setTargetInvoice(null);
                            setIsModalOpen(true);
                        }}
                        className="btn-primary flex items-center justify-center gap-2 px-8 w-full sm:w-auto 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">New Subscription</span>
                    </button>
                </div>
            </div>

            {/* Quick Metrics */}
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6 sm:gap-8">
                <div className="premium-card p-6 sm:p-8 flex items-center gap-4 sm:gap-6 group hover:scale-[1.02] transition-all duration-500">
                    <div className="p-3.5 sm:p-4 bg-primary/10 rounded-2xl shrink-0 group-hover:rotate-12 transition-transform duration-500">
                        <Box className="w-5 h-5 sm:w-6 sm:h-6 text-primary shrink-0" />
                    </div>
                    <div className="min-w-0">
                        <p className="text-[9px] sm:text-[10px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-[0.15em] mb-1 truncate">Monthly Revenue (MRR)</p>
                        <h3 className="text-lg sm:text-xl font-black text-slate-800 dark:text-white tracking-tight leading-none flex items-baseline truncate">
                            <span className="text-[9px] sm:text-[10px] text-primary/60 dark:text-primary/40 mr-1 font-black shrink-0">{currency}</span>
                            {Number(subscriptions.reduce((acc, sub) => acc + (sub.status === 'Active' ? Number(sub.amount) : 0), 0)).toLocaleString()}
                        </h3>
                    </div>
                </div>
            </div>

            {/* Convert Section */}
            <div className="premium-card p-6 sm:p-8 flex flex-col gap-8">
                <div className="flex flex-col lg:flex-row justify-between items-start lg:items-center gap-6">
                    <div className="flex items-center gap-4 sm:gap-5 min-w-0">
                        <div className="p-3 sm:p-3.5 bg-indigo-500/10 rounded-2xl shrink-0">
                            <ArrowRightLeft className="w-5 h-5 sm:w-6 sm:h-6 text-indigo-500 shrink-0" />
                        </div>
                        <div className="min-w-0">
                            <h3 className="text-base sm:text-lg font-extrabold text-slate-800 dark:text-white tracking-tight truncate leading-none">Import from Invoice</h3>
                            <p className="text-[10px] sm:text-[11px] font-bold text-slate-400 dark:text-slate-500 uppercase tracking-widest mt-1 truncate">Create a subscription from an existing invoice</p>
                        </div>
                    </div>
                    <div className="w-full lg:w-80">
                        <select
                            className="premium-input !appearance-auto !py-3 sm:!py-3.5 !text-xs sm:!text-sm outline-none h-12 lg:h-14"
                            value={selectedClient}
                            onChange={(e) => setSelectedClient(e.target.value)}
                        >
                            <option value="">Select Client...</option>
                            {clients.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
                        </select>
                    </div>
                </div>

                {selectedClient && (
                    <div className="animate-in slide-in-from-top-4 duration-500">
                        {clientInvoices.length > 0 ? (
                            <div className="overflow-x-auto overflow-y-hidden border border-slate-100 dark:border-slate-800 rounded-2xl">
                                <table className="w-full text-left min-w-[700px]">
                                    <thead className="bg-slate-50/50 dark:bg-slate-900/40">
                                        <tr>
                                            <th className="px-6 sm:px-8 py-4 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-4 text-[11px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest">Date</th>
                                            <th className="px-6 sm:px-8 py-4 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-4 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">
                                        {clientInvoices.map(inv => (
                                            <tr key={inv.id} className="group hover:bg-white dark:hover:bg-slate-900 transition-colors">
                                                <td className="px-6 sm:px-8 py-5 text-sm font-black text-slate-800 dark:text-white truncate">{inv.invoiceNumber}</td>
                                                <td className="px-6 sm:px-8 py-5 text-[11px] font-black text-slate-400 dark:text-slate-600 uppercase tracking-widest whitespace-nowrap">{inv.issueDate}</td>
                                                <td className="px-6 sm:px-8 py-5 text-right font-black text-slate-900 dark:text-white tracking-tight whitespace-nowrap">
                                                    <span className="text-[10px] opacity-40 mr-1 shrink-0">{currency}</span>
                                                    {Number(inv.total).toLocaleString()}
                                                </td>
                                                <td className="px-6 sm:px-8 py-5 text-right">
                                                    <button
                                                        onClick={() => handleMarkRecurrent(inv)}
                                                        className="px-4 py-2 bg-indigo-500 text-white rounded-xl text-[10px] font-black uppercase tracking-widest hover:shadow-lg hover:shadow-indigo-500/20 transition-all active:scale-95 whitespace-nowrap"
                                                    >
                                                        Make Recurring
                                                    </button>
                                                </td>
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                            </div>
                        ) : (
                            <div className="p-12 text-center bg-slate-50/50 dark:bg-slate-900/20 rounded-3xl border border-dashed border-slate-200 dark:border-slate-800">
                                <Box className="w-12 h-12 text-slate-200 dark:text-slate-800 mx-auto mb-4 shrink-0" />
                                <h4 className="text-sm font-black text-slate-800 dark:text-white uppercase tracking-tight">No Invoices Found</h4>
                                <p className="text-[11px] font-bold text-slate-400 dark:text-slate-600 uppercase tracking-widest mt-1">This client has no existing invoices.</p>
                            </div>
                        )}
                    </div>
                )}
            </div>

            {/* Active Schedules Table */}
            <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">Subscription Name</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">Cycle</th>
                                <th className="px-6 sm:px-8 py-5 text-[11px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest">Next Billing</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">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="7" 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 subscriptions...</p>
                                        </div>
                                    </td>
                                </tr>
                            ) : subscriptions.length === 0 ? (
                                <tr>
                                    <td colSpan="7" 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">
                                                <Repeat 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 Subscriptions Found</h3>
                                            <p className="text-[11px] text-slate-500 dark:text-slate-500 leading-relaxed font-bold uppercase tracking-widest">Create your first subscription to start automating your billing.</p>
                                        </div>
                                    </td>
                                </tr>
                            ) : (
                                subscriptions.map((sub) => (
                                    <tr key={sub.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-4 min-w-0">
                                                <div className="w-10 h-10 bg-primary/10 rounded-xl flex items-center justify-center shrink-0">
                                                    <Repeat className="w-5 h-5 text-primary shrink-0" />
                                                </div>
                                                <span className="text-sm font-black text-slate-800 dark:text-white tracking-tight truncate">{sub.name}</span>
                                            </div>
                                        </td>
                                        <td className="px-6 sm:px-8 py-6">
                                            <span className="text-sm font-extrabold text-slate-700 dark:text-slate-300 capitalize truncate block">{sub.Client?.name}</span>
                                        </td>
                                        <td className="px-6 sm:px-8 py-6">
                                            <div className="inline-flex px-3 py-1 bg-slate-50 dark:bg-slate-800 border border-slate-100 dark:border-slate-700 rounded-full whitespace-nowrap">
                                                <span className="text-[10px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-[0.1em]">{sub.billingCycle}</span>
                                            </div>
                                        </td>
                                        <td className="px-6 sm:px-8 py-6">
                                            <div className="flex flex-col gap-0.5 whitespace-nowrap">
                                                <div className="flex items-center gap-2">
                                                    <Calendar className="w-3.5 h-3.5 text-slate-300 shrink-0" />
                                                    <span className="text-xs font-black text-slate-800 dark:text-slate-200 tracking-tight">{sub.nextBillingDate}</span>
                                                </div>
                                                <span className="text-[9px] font-black text-slate-400 uppercase tracking-tighter">Next Cycle</span>
                                            </div>
                                        </td>
                                        <td className="px-6 sm:px-8 py-6">
                                            <StatusBadge status={sub.status} />
                                        </td>
                                        <td className="px-6 sm:px-8 py-6 text-right whitespace-nowrap">
                                            <span className="text-sm font-black text-slate-900 dark:text-white">
                                                <span className="text-[10px] opacity-40 mr-1 shrink-0">{currency}</span>
                                                {Number(sub.amount).toLocaleString()}
                                            </span>
                                        </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(sub)} 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"><Edit2 className="w-4 h-4 shrink-0" /></button>
                                                <button onClick={() => handleDelete(sub.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"><Trash2 className="w-4 h-4 shrink-0" /></button>
                                            </div>
                                        </td>
                                    </tr>
                                ))
                            )}
                        </tbody>
                    </table>
                </div>
            </div>

            {/* Modal */}
            {isModalOpen && (
                <div className="fixed inset-0 z-50 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-xl rounded-[2.5rem] shadow-4xl relative overflow-hidden premium-card flex flex-col max-h-[95vh]">
                        <div className="absolute top-0 left-0 w-full h-2 bg-primary shadow-lg shadow-primary/20 shrink-0" />

                        <div className="p-6 sm:p-10 pb-4 flex items-center gap-5 shrink-0">
                            <div className="p-3.5 sm:p-4 bg-primary rounded-2xl text-white shadow-xl shadow-primary/20 shrink-0">
                                <Repeat className="w-6 h-6 sm:w-7 sm:h-7 shrink-0" />
                            </div>
                            <div className="min-w-0">
                                <h2 className="text-xl sm:text-2xl font-black text-slate-800 dark:text-white tracking-tight truncate">
                                    {editingSub ? 'Edit Subscription' : 'New Subscription'}
                                </h2>
                                <p className="text-[10px] font-black text-slate-400 uppercase tracking-widest mt-1">Enter subscription details</p>
                            </div>
                        </div>

                        <div className="flex-1 overflow-y-auto px-6 sm:px-10 py-6 custom-scrollbar">
                            <form onSubmit={handleSubmit} id="sub-form" className="space-y-8">
                                <div className="grid grid-cols-1 sm:grid-cols-2 gap-x-6 gap-y-8">
                                    <div className="sm:col-span-2 space-y-2">
                                        <label className="premium-label">Subscription Name</label>
                                        <div className="relative group">
                                            <Box 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
                                                required
                                                placeholder="e.g. Monthly Retainer"
                                                className="premium-input !pl-12 h-12 sm:h-14"
                                                value={formData.name}
                                                onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                                            />
                                        </div>
                                    </div>

                                    <div className="sm:col-span-2 space-y-2">
                                        <label className="premium-label">Client</label>
                                        <select
                                            required
                                            className="premium-input !appearance-auto h-12 sm:h-14 outline-none"
                                            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>
                                    </div>

                                    <div className="space-y-2">
                                        <label className="premium-label">Billing Cycle</label>
                                        <select
                                            required
                                            className="premium-input !appearance-auto h-12 sm:h-14 outline-none"
                                            value={formData.billingCycle}
                                            onChange={(e) => setFormData({ ...formData, billingCycle: e.target.value })}
                                        >
                                            <option value="Monthly">Monthly</option>
                                            <option value="Quarterly">Quarterly</option>
                                            <option value="Yearly">Yearly</option>
                                        </select>
                                    </div>

                                    <div className="space-y-2">
                                        <label className="premium-label">Amount</label>
                                        <div className="relative group">
                                            <span className="absolute left-4 top-1/2 -translate-y-1/2 text-xs font-black text-primary/40 shrink-0">{currency}</span>
                                            <input
                                                required
                                                type="number"
                                                step="0.01"
                                                className="premium-input !pl-14 text-lg !font-black !tracking-tight h-12 sm:h-14"
                                                value={formData.amount}
                                                onChange={(e) => setFormData({ ...formData, amount: e.target.value })}
                                            />
                                        </div>
                                    </div>

                                    <div className="space-y-2">
                                        <label className="premium-label">Start Date</label>
                                        <input
                                            required
                                            type="date"
                                            className="premium-input h-12 sm:h-14"
                                            value={formData.startDate}
                                            onChange={(e) => setFormData({ ...formData, startDate: e.target.value })}
                                        />
                                    </div>

                                    <div className="space-y-2">
                                        <label className="premium-label">Next Billing Date</label>
                                        <input
                                            required
                                            type="date"
                                            className="premium-input border-primary/20 bg-primary/5 h-12 sm:h-14"
                                            value={formData.nextBillingDate}
                                            onChange={(e) => setFormData({ ...formData, nextBillingDate: e.target.value })}
                                        />
                                    </div>

                                    <div className="space-y-2 sm:col-span-2">
                                        <label className="premium-label">Due Days</label>
                                        <div className="relative group">
                                            <Clock 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
                                                required
                                                type="number"
                                                placeholder="Standard: 7 Days"
                                                className="premium-input !pl-12 h-12 sm:h-14"
                                                value={formData.dueDays}
                                                onChange={(e) => setFormData({ ...formData, dueDays: e.target.value })}
                                            />
                                        </div>
                                    </div>
                                </div>

                                <div className="space-y-4 pt-4">
                                    <label className="flex items-center gap-4 p-4 sm:p-5 bg-slate-50/50 dark:bg-slate-900/40 border border-slate-100 dark:border-slate-800 rounded-[1.5rem] cursor-pointer hover:bg-white dark:hover:bg-slate-900 transition-all group shrink-0">
                                        <div className="relative flex items-center shrink-0">
                                            <input
                                                type="checkbox"
                                                className="w-5 h-5 rounded-lg border-2 border-slate-200 dark:border-slate-700 text-primary focus:ring-primary/20 cursor-pointer transition-all shrink-0"
                                                checked={formData.autoSendInvoice}
                                                onChange={(e) => setFormData({ ...formData, autoSendInvoice: e.target.checked })}
                                            />
                                        </div>
                                        <div className="flex flex-col min-w-0">
                                            <span className="text-sm font-extrabold text-slate-800 dark:text-white tracking-tight truncate">Auto-Send Invoice</span>
                                            <span className="text-[10px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest mt-0.5 truncate">Automatically email the invoice to the user</span>
                                        </div>
                                    </label>

                                    {!editingSub && !targetInvoice && (
                                        <label className="flex items-center gap-4 p-4 sm:p-5 bg-emerald-500/5 dark:bg-emerald-500/10 border border-emerald-500/10 rounded-[1.5rem] cursor-pointer hover:bg-emerald-500/10 transition-all group shrink-0">
                                            <div className="relative flex items-center shrink-0">
                                                <input
                                                    type="checkbox"
                                                    className="w-5 h-5 rounded-lg border-2 border-emerald-500/20 text-emerald-500 focus:ring-emerald-500/20 cursor-pointer transition-all shrink-0"
                                                    checked={formData.prorateFirstMonth}
                                                    onChange={(e) => setFormData({ ...formData, prorateFirstMonth: e.target.checked })}
                                                />
                                            </div>
                                            <div className="flex flex-col min-w-0">
                                                <span className="text-sm font-extrabold text-emerald-600 dark:text-emerald-400 tracking-tight truncate">Prorate First Month</span>
                                                <span className="text-[10px] font-black text-emerald-500/60 uppercase tracking-widest mt-0.5 truncate">Calculate partial amount for first month</span>
                                            </div>
                                        </label>
                                    )}
                                </div>
                            </form>
                        </div>

                        <div className="p-6 sm:p-10 pt-4 border-t border-slate-100 dark:border-slate-800 shrink-0">
                            <div className="flex flex-col sm:flex-row gap-3 sm:gap-4">
                                <button
                                    type="button"
                                    onClick={() => setIsModalOpen(false)}
                                    className="flex-1 py-4 text-[11px] font-black text-slate-400 uppercase tracking-widest hover:bg-slate-50 dark:hover:bg-slate-900 rounded-2xl transition-all order-2 sm:order-1 h-12 sm:h-14 flex items-center justify-center shrink-0"
                                >
                                    Cancel
                                </button>
                                <button
                                    onClick={handleSubmit}
                                    disabled={isSubmitting}
                                    className="btn-primary flex-[1.5] py-4 shadow-2xl disabled:opacity-50 flex items-center justify-center gap-2 order-1 sm:order-2 h-12 sm:h-14 shrink-0"
                                >
                                    {isSubmitting ? (
                                        <div className="w-4 h-4 border-2 border-white/20 border-t-white rounded-full animate-spin shrink-0"></div>
                                    ) : (
                                        <Zap className="w-4 h-4 shrink-0" />
                                    )}
                                    <span className="text-[10px] sm:text-[11px] font-black uppercase tracking-widest whitespace-nowrap">{editingSub ? 'Save Changes' : 'Create Subscription'}</span>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
};

export default SubscriptionList;
