import React, { useEffect, useState } from 'react';
import toast from 'react-hot-toast';
import { recurringExpenseApi } from '@/services/api';
import RecurringExpenseModal from '@/components/RecurringExpenseModal';
import type { PaginatedResponse } from '@/types';

export default function RecurringExpenses() {
    const [items, setItems] = useState<any[]>([]);
    const [loading, setLoading] = useState(true);
    const [page, setPage] = useState(1);
    const [hasMore, setHasMore] = useState(false);
    const [modalOpen, setModalOpen] = useState(false);
    const [editItem, setEditItem] = useState<any>(null);

    const loadItems = async (pageNum: number = 1, append: boolean = false) => {
        setLoading(true);
        try {
            const res = await recurringExpenseApi.getAll({ page: pageNum, per_page: 20 });
            const data: PaginatedResponse<any> = res.data;
            setItems(prev => append ? [...prev, ...data.data] : data.data);
            setHasMore(data.current_page < data.last_page);
            setPage(pageNum);
        } catch {
            // ignore
        } finally {
            setLoading(false);
        }
    };

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

    const handleDelete = async (id: number) => {
        if (!confirm('Delete this recurring expense?')) return;
        try {
            await recurringExpenseApi.delete(id);
            loadItems();
        } catch (err: any) {
            toast.error(err.response?.data?.message || 'Failed to delete recurring expense');
        }
    };

    const handleMarkPaid = async (id: number) => {
        if (!confirm('Mark as paid? An expense entry will be created.')) return;
        try {
            await recurringExpenseApi.markPaid(id);
            toast.success('Marked as paid');
            loadItems();
        } catch (err: any) {
            toast.error(err.response?.data?.message || 'Failed to mark as paid');
        }
    };

    const totalMonthly = items.filter(i => i.is_active).reduce((sum, i) => sum + i.amount, 0);

    return (
        <div className="space-y-6">
            <div className="flex items-center justify-between">
                <div>
                    <h1 className="text-3xl lg:text-4xl font-bold text-gray-900 dark:text-gray-100 tracking-tight">Recurring</h1>
                    {items.length > 0 && (
                        <p className="text-gray-400 dark:text-gray-500 text-sm mt-1">
                            {items.filter(i => i.is_active).length} active &middot; Monthly total: <span className="font-semibold text-expense">{totalMonthly.toLocaleString()}</span>
                        </p>
                    )}
                </div>
                <button onClick={() => { setEditItem(null); setModalOpen(true); }} className="hidden lg:inline-flex items-center gap-2 px-5 py-2.5 bg-teal-600 hover:bg-teal-700 text-white text-sm font-medium rounded-xl transition-all hover:shadow-lg hover:shadow-teal-200/50 dark:hover:shadow-teal-900/30 active:scale-[0.97]">
                    <span className="text-base">+</span> Add Recurring
                </button>
            </div>

            {loading ? (
                <div className="flex items-center justify-center min-h-[40vh]">
                    <div className="w-8 h-8 border-2 border-teal-600 border-t-transparent rounded-full animate-spin" />
                </div>
            ) : items.length === 0 ? (
                <div className="bg-white/70 dark:bg-gray-800/70 backdrop-blur-sm rounded-2xl border border-gray-100/50 dark:border-gray-700/30 text-center py-16">
                    <p className="text-5xl mb-4">🔄</p>
                    <p className="text-gray-400 dark:text-gray-500 mb-4">No recurring expenses</p>
                    <button onClick={() => { setEditItem(null); setModalOpen(true); }} className="btn-primary">Add One</button>
                </div>
            ) : (
                <>
                    <div className="hidden lg:block bg-white/70 dark:bg-gray-800/70 backdrop-blur-sm rounded-2xl border border-gray-100/50 dark:border-gray-700/30 overflow-hidden">
                        <table className="w-full">
                            <thead>
                                <tr className="border-b border-gray-100 dark:border-gray-700/50">
                                    <th className="text-left px-5 py-3.5 text-xs font-semibold text-gray-400 dark:text-gray-500 uppercase tracking-wider">Category</th>
                                    <th className="text-left px-5 py-3.5 text-xs font-semibold text-gray-400 dark:text-gray-500 uppercase tracking-wider">Frequency</th>
                                    <th className="text-left px-5 py-3.5 text-xs font-semibold text-gray-400 dark:text-gray-500 uppercase tracking-wider">Next Due</th>
                                    <th className="text-left px-5 py-3.5 text-xs font-semibold text-gray-400 dark:text-gray-500 uppercase tracking-wider">Note</th>
                                    <th className="text-left px-5 py-3.5 text-xs font-semibold text-gray-400 dark:text-gray-500 uppercase tracking-wider">Status</th>
                                    <th className="text-right px-5 py-3.5 text-xs font-semibold text-gray-400 dark:text-gray-500 uppercase tracking-wider">Amount</th>
                                    <th className="text-right px-5 py-3.5 text-xs font-semibold text-gray-400 dark:text-gray-500 uppercase tracking-wider">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                {items.map((item) => (
                                    <tr key={item.id} className={`border-b border-gray-50 dark:border-gray-700/20 hover:bg-gray-50/50 dark:hover:bg-gray-700/20 transition-colors last:border-0 ${item.is_overdue ? 'bg-red-50/30 dark:bg-red-900/10' : ''}`}>
                                        <td className="px-5 py-3.5">
                                            <div className="flex items-center gap-2">
                                                <span className="text-lg">{item.category?.icon || '📦'}</span>
                                                <span className="text-sm font-medium text-gray-700 dark:text-gray-200">{item.category?.name || 'Unknown'}</span>
                                            </div>
                                        </td>
                                        <td className="px-5 py-3.5 text-sm text-gray-500">{item.frequency === 'monthly' ? '📅 Monthly' : '📅 Weekly'}</td>
                                        <td className="px-5 py-3.5 text-sm text-gray-700 dark:text-gray-200 whitespace-nowrap">
                                            {new Date(item.next_due_date).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' })}
                                            {item.is_overdue && <span className="ml-1.5 text-red-500 text-xs">⚠️</span>}
                                        </td>
                                        <td className="px-5 py-3.5 text-sm text-gray-400 dark:text-gray-500 max-w-[180px] truncate">
                                            {item.note || '—'}
                                        </td>
                                        <td className="px-5 py-3.5">
                                            {item.is_active ? (
                                                <span className="text-xs bg-green-50 dark:bg-green-900/30 text-green-700 dark:text-green-400 px-2.5 py-1 rounded-full font-medium">Active</span>
                                            ) : (
                                                <span className="text-xs bg-gray-100 dark:bg-gray-700/50 text-gray-500 dark:text-gray-400 px-2.5 py-1 rounded-full font-medium">Inactive</span>
                                            )}
                                        </td>
                                        <td className="px-5 py-3.5 text-right text-sm font-semibold text-expense whitespace-nowrap">
                                            {item.amount.toLocaleString()}
                                        </td>
                                        <td className="px-5 py-3.5 text-right">
                                            <div className="flex items-center justify-end gap-1">
                                                {item.is_active && (
                                                    <button onClick={() => handleMarkPaid(item.id)} className="text-xs bg-green-50 hover:bg-green-100 text-green-700 px-2.5 py-1.5 rounded-lg font-medium transition-all hover:shadow-sm">✓</button>
                                                )}
                                                <button onClick={() => { setEditItem(item); setModalOpen(true); }} className="p-1.5 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 text-gray-400 text-sm">✏️</button>
                                                <button onClick={() => handleDelete(item.id)} className="p-1.5 rounded-lg hover:bg-red-50 dark:hover:bg-red-900/30 text-gray-400 hover:text-red-500 text-sm">🗑️</button>
                                            </div>
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>

                    <div className="lg:hidden space-y-3">
                        {items.map((item) => (
                            <div key={item.id} className={`bg-white/70 dark:bg-gray-800/70 backdrop-blur-sm rounded-2xl p-4 border ${item.is_overdue ? 'border-red-200 dark:border-red-800/50 bg-red-50/20 dark:bg-red-900/10' : 'border-gray-100/50 dark:border-gray-700/30'}`}>
                                <div className="flex items-center justify-between mb-2">
                                    <div className="flex items-center gap-2.5">
                                        <span className="text-xl">{item.category?.icon || '📦'}</span>
                                        <div>
                                            <p className="text-sm font-medium text-gray-800 dark:text-gray-200">{item.category?.name || 'Unknown'}</p>
                                            <p className="text-xs text-gray-400">{item.frequency === 'monthly' ? '📅 Monthly' : '📅 Weekly'}{item.is_overdue && ' ⚠️ Overdue'}</p>
                                        </div>
                                    </div>
                                    <div className="text-right">
                                        <p className="text-sm font-semibold text-expense">{item.amount.toLocaleString()}</p>
                                        <p className="text-xs text-gray-400">Due {new Date(item.next_due_date).toLocaleDateString('en-GB', { day: 'numeric', month: 'short' })}</p>
                                    </div>
                                </div>
                                {item.note && <p className="text-xs text-gray-500 dark:text-gray-400 ml-11 mb-2">{item.note}</p>}
                                <div className="flex gap-2 ml-11">
                                    {item.is_active && (
                                        <button onClick={() => handleMarkPaid(item.id)} className="text-xs bg-green-50 hover:bg-green-100 text-green-700 px-3 py-1.5 rounded-lg font-medium transition-all">✓ Mark Paid</button>
                                    )}
                                    <button onClick={() => { setEditItem(item); setModalOpen(true); }} className="text-xs text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 px-2">✏️</button>
                                    <button onClick={() => handleDelete(item.id)} className="text-xs text-gray-400 hover:text-red-400 px-2">🗑️</button>
                                </div>
                            </div>
                        ))}
                    </div>
                </>
            )}

            {hasMore && (
                <button onClick={() => loadItems(page + 1, true)} disabled={loading} className="w-full py-3 text-sm font-medium text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 bg-white/50 dark:bg-gray-800/50 backdrop-blur-sm rounded-xl border border-gray-100/50 dark:border-gray-700/30 transition-all hover:bg-white/80 dark:hover:bg-gray-800/80">
                    {loading ? 'Loading...' : 'Load More'}
                </button>
            )}

            <RecurringExpenseModal open={modalOpen} onClose={() => { setModalOpen(false); setEditItem(null); }} onSaved={() => loadItems(1)} editItem={editItem} />
        </div>
    );
}
