import React, { useEffect, useState } from 'react';
import toast from 'react-hot-toast';
import { reportApi } from '@/services/api';
import type { DashboardStats } from '@/types';
import {
    BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer,
    PieChart, Pie, Cell,
} from 'recharts';

const MONTHS = [
    'January', 'February', 'March', 'April', 'May', 'June',
    'July', 'August', 'September', 'October', 'November', 'December',
];

export default function Reports() {
    const now = new Date();
    const [dateFrom, setDateFrom] = useState(new Date(now.getFullYear(), now.getMonth(), 1).toISOString().slice(0, 10));
    const [dateTo, setDateTo] = useState(now.toISOString().slice(0, 10));
    const [data, setData] = useState<any>(null);
    const [loading, setLoading] = useState(true);

    const loadReport = async () => {
        setLoading(true);
        try {
            const res = await reportApi.summary({ date_from: dateFrom, date_to: dateTo });
            setData(res.data);
        } catch {
            // ignore
        } finally {
            setLoading(false);
        }
    };

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

    const handleExportCsv = async () => {
        try {
            const res = await reportApi.exportCsv({ date_from: dateFrom, date_to: dateTo });
            const url = URL.createObjectURL(new Blob([res.data]));
            const a = document.createElement('a');
            a.href = url;
            a.download = `expenses-${dateFrom}-to-${dateTo}.csv`;
            a.click();
            URL.revokeObjectURL(url);
        } catch {
            toast.error('Export failed');
        }
    };

    const handleExportPdf = async () => {
        try {
            const res = await reportApi.exportPdf({ date_from: dateFrom, date_to: dateTo });
            const url = URL.createObjectURL(new Blob([res.data]));
            const a = document.createElement('a');
            a.href = url;
            a.download = `expenses-${dateFrom}-to-${dateTo}.pdf`;
            a.click();
            URL.revokeObjectURL(url);
        } catch {
            toast.error('Export failed');
        }
    };

    const totalExpense = data?.total_expense || 0;
    const totalTxns = data?.total_transactions || 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">Reports</h1>
                    <p className="text-gray-400 dark:text-gray-500 text-sm mt-1">Expense analysis & export</p>
                </div>
            </div>

            <div className="bg-white/70 dark:bg-gray-800/70 backdrop-blur-sm rounded-2xl p-5 border border-gray-100/50 dark:border-gray-700/30">
                <div className="flex flex-col sm:flex-row gap-3 items-end">
                    <div className="flex-1 w-full">
                        <label className="block text-xs font-medium text-gray-400 dark:text-gray-500 uppercase tracking-wider mb-1.5">From</label>
                        <input type="date" value={dateFrom} onChange={(e) => setDateFrom(e.target.value)} className="w-full px-4 py-2.5 bg-white/70 dark:bg-gray-800/70 border border-gray-200/60 dark:border-gray-700/40 rounded-xl text-sm text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-teal-500/30 focus:border-teal-500/50 transition-all" />
                    </div>
                    <div className="flex-1 w-full">
                        <label className="block text-xs font-medium text-gray-400 dark:text-gray-500 uppercase tracking-wider mb-1.5">To</label>
                        <input type="date" value={dateTo} onChange={(e) => setDateTo(e.target.value)} className="w-full px-4 py-2.5 bg-white/70 dark:bg-gray-800/70 border border-gray-200/60 dark:border-gray-700/40 rounded-xl text-sm text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-teal-500/30 focus:border-teal-500/50 transition-all" />
                    </div>
                    <div className="flex gap-2 w-full sm:w-auto">
                        <button onClick={loadReport} className="flex-1 sm:flex-none 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]">Apply</button>
                        <button onClick={handleExportCsv} className="px-4 py-2.5 bg-white/70 dark:bg-gray-800/70 border border-gray-200/60 dark:border-gray-700/40 rounded-xl text-sm text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 hover:border-gray-300 transition-all" title="Export CSV">📄</button>
                        <button onClick={handleExportPdf} className="px-4 py-2.5 bg-white/70 dark:bg-gray-800/70 border border-gray-200/60 dark:border-gray-700/40 rounded-xl text-sm text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 hover:border-gray-300 transition-all" title="Export PDF">📑</button>
                    </div>
                </div>
            </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>
            ) : (
                <>
                    <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
                        {[
                            { label: 'Total Expense', value: totalExpense.toLocaleString(undefined, { minimumFractionDigits: 0 }), accent: 'bg-red-50 dark:bg-red-900/20' },
                            { label: 'Transactions', value: String(totalTxns), accent: 'bg-blue-50 dark:bg-blue-900/20' },
                            { label: 'From', value: new Date(dateFrom).toLocaleDateString('en-GB', { day: 'numeric', month: 'short' }), accent: 'bg-teal-50 dark:bg-teal-900/20' },
                            { label: 'To', value: new Date(dateTo).toLocaleDateString('en-GB', { day: 'numeric', month: 'short' }), accent: 'bg-gray-50 dark:bg-gray-800/50' },
                        ].map((card, i) => (
                            <div key={i} className="bg-white/70 dark:bg-gray-800/70 backdrop-blur-sm rounded-2xl p-5 border border-gray-100/50 dark:border-gray-700/30">
                                <p className="text-xs font-medium text-gray-400 dark:text-gray-500 uppercase tracking-wider mb-2">{card.label}</p>
                                <p className="text-xl lg:text-2xl font-bold text-gray-800 dark:text-gray-100">{card.value}</p>
                            </div>
                        ))}
                    </div>

                    <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
                        {data?.daily_breakdown && data.daily_breakdown.length > 0 && (
                            <div className="bg-white/70 dark:bg-gray-800/70 backdrop-blur-sm rounded-2xl p-5 border border-gray-100/50 dark:border-gray-700/30">
                                <p className="text-xs font-medium text-gray-400 dark:text-gray-500 uppercase tracking-wider mb-4">Daily Trend</p>
                                <div className="h-48 lg:h-64">
                                    <ResponsiveContainer width="100%" height="100%">
                                        <BarChart data={data.daily_breakdown}>
                                            <CartesianGrid strokeDasharray="3 3" className="stroke-gray-100 dark:stroke-gray-700/50" />
                                            <XAxis dataKey="date" tick={{ fontSize: 10, fill: '#9ca3af' }} axisLine={false} tickLine={false} tickFormatter={(val) => { const d = new Date(val); return `${d.getDate()}/${d.getMonth() + 1}`; }} />
                                            <YAxis tick={{ fontSize: 10, fill: '#9ca3af' }} axisLine={false} tickLine={false} />
                                            <Tooltip
                                                contentStyle={{ borderRadius: '14px', border: '1px solid #e5e7eb', boxShadow: '0 8px 24px rgba(0,0,0,0.08)', background: 'rgba(255,255,255,0.95)' }}
                                                formatter={(value: number) => [value.toLocaleString(), 'Total']}
                                            />
                                            <Bar dataKey="total" fill="#0d9488" radius={[4, 4, 0, 0]} maxBarSize={32} />
                                        </BarChart>
                                    </ResponsiveContainer>
                                </div>
                            </div>
                        )}

                        {data?.category_breakdown && data.category_breakdown.length > 0 && (
                            <div className="bg-white/70 dark:bg-gray-800/70 backdrop-blur-sm rounded-2xl p-5 border border-gray-100/50 dark:border-gray-700/30">
                                <p className="text-xs font-medium text-gray-400 dark:text-gray-500 uppercase tracking-wider mb-4">Category Breakdown</p>
                                <div className="h-48 lg:h-64">
                                    <ResponsiveContainer width="100%" height="100%">
                                        <PieChart>
                                            <Pie data={data.category_breakdown} dataKey="total" nameKey="category" cx="50%" cy="50%" innerRadius={55} outerRadius={80} paddingAngle={3}>
                                                {data.category_breakdown.map((entry: any, i: number) => (<Cell key={i} fill={entry.color} />))}
                                            </Pie>
                                            <Tooltip
                                                contentStyle={{ borderRadius: '14px', border: '1px solid #e5e7eb', boxShadow: '0 8px 24px rgba(0,0,0,0.08)', background: 'rgba(255,255,255,0.95)' }}
                                                formatter={(value: number, name: string) => [value.toLocaleString(), name]}
                                            />
                                        </PieChart>
                                    </ResponsiveContainer>
                                </div>
                                <div className="mt-4 space-y-2">
                                    {data.category_breakdown.map((item: any, i: number) => (
                                        <div key={i} className="flex items-center justify-between text-sm">
                                            <div className="flex items-center gap-2">
                                                <span className="text-base">{item.icon}</span>
                                                <span className="text-gray-600 dark:text-gray-300">{item.category}</span>
                                            </div>
                                            <div className="flex items-center gap-3">
                                                <div className="w-16 h-1.5 bg-gray-100 dark:bg-gray-700/50 rounded-full overflow-hidden">
                                                    <div className="h-full rounded-full" style={{ width: `${item.percentage}%`, background: item.color }} />
                                                </div>
                                                <span className="text-xs text-gray-400 w-8 text-right">{item.percentage}%</span>
                                                <span className="font-medium text-gray-800 dark:text-gray-200 w-20 text-right">{item.total.toLocaleString()}</span>
                                            </div>
                                        </div>
                                    ))}
                                </div>
                            </div>
                        )}
                    </div>

                    {data?.expenses && data.expenses.length > 0 && (
                        <div className="bg-white/70 dark:bg-gray-800/70 backdrop-blur-sm rounded-2xl p-5 border border-gray-100/50 dark:border-gray-700/30">
                            <p className="text-xs font-medium text-gray-400 dark:text-gray-500 uppercase tracking-wider mb-4">All Transactions ({data.expenses.length})</p>
                            <div className="max-h-80 overflow-y-auto space-y-0.5">
                                {data.expenses.map((expense: any) => (
                                    <div key={expense.id} className="flex items-center justify-between py-2 px-2 rounded-xl hover:bg-gray-50 dark:hover:bg-gray-700/20 transition-colors">
                                        <div className="flex items-center gap-3 min-w-0">
                                            <span className="text-lg">{expense.category?.icon || '📦'}</span>
                                            <div className="min-w-0">
                                                <p className="text-sm text-gray-700 dark:text-gray-200 truncate">{expense.note || expense.category?.name || 'Expense'}</p>
                                                <p className="text-xs text-gray-400">{expense.date}</p>
                                            </div>
                                        </div>
                                        <span className="text-sm font-semibold text-expense whitespace-nowrap ml-2">{expense.amount.toLocaleString()}</span>
                                    </div>
                                ))}
                            </div>
                        </div>
                    )}
                </>
            )}
        </div>
    );
}
