import { useQuery } from '@tanstack/react-query';
import { useAuth } from '../context/AuthContext';
import { reports } from '../services/api';
import { cn } from '../lib/utils';
import { AreaChart, Area, BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer, CartesianGrid } from 'recharts';
import { Download, Calendar, TrendingUp, Clock, CheckCircle2, AlertTriangle, BarChart3, Loader2 } from 'lucide-react';
import { useState } from 'react';

const CustomTooltip = ({ active, payload, label }) => {
    if (!active || !payload) return null;
    return (
        <div className="bg-gray-900 border border-gray-700 rounded-lg px-3 py-2 shadow-xl text-xs">
            <p className="text-gray-400 mb-1">{label}</p>
            {payload.map((item, i) => (
                <p key={i} className="text-white font-medium">
                    <span className="inline-block w-2 h-2 rounded-full mr-1.5" style={{ backgroundColor: item.color }} />
                    {item.name}: {item.value}
                </p>
            ))}
        </div>
    );
};

export default function Reports() {
    const { currentOrg } = useAuth();
    const [days, setDays] = useState(30);

    const { data, isLoading } = useQuery({
        queryKey: ['report-summary', currentOrg?.id, days],
        queryFn: () => reports.summary(currentOrg.id, days),
        enabled: !!currentOrg
    });

    const handleExport = async () => {
        try {
            const response = await reports.exportCsv(currentOrg.id, days);
            const url = URL.createObjectURL(new Blob([response.data]));
            const a = document.createElement('a');
            a.href = url;
            a.download = `report-${currentOrg.name}-${days}days.csv`;
            a.click();
            URL.revokeObjectURL(url);
        } catch (err) { console.error(err); }
    };

    if (!currentOrg) return <div className="flex items-center justify-center h-full p-8"><p className="text-gray-500">Select an organization</p></div>;

    const r = data?.data || {};

    const summaryCards = [
        { label: 'Total Processed', value: r.total_issues || 0, icon: BarChart3, color: 'text-indigo-400', bg: 'bg-indigo-500/10' },
        { label: 'Success Rate', value: r.success_rate ? `${(r.success_rate * 100).toFixed(0)}%` : 'N/A', icon: CheckCircle2, color: 'text-emerald-400', bg: 'bg-emerald-500/10' },
        { label: 'Avg Resolution', value: r.avg_resolution_hours ? `${r.avg_resolution_hours.toFixed(1)}h` : 'N/A', icon: Clock, color: 'text-amber-400', bg: 'bg-amber-500/10' },
        { label: 'Error Rate', value: r.error_rate ? `${(r.error_rate * 100).toFixed(1)}%` : '0%', icon: AlertTriangle, color: 'text-red-400', bg: 'bg-red-500/10' },
    ];

    return (
        <div className="p-6 animate-fade-in">
            <div className="page-header">
                <div>
                    <h1 className="page-title">Reports & Analytics</h1>
                    <p className="page-subtitle">Performance metrics and insights</p>
                </div>
                <div className="flex items-center gap-2">
                    <div className="flex items-center gap-1 bg-gray-900 border border-gray-800 rounded-lg p-0.5">
                        {[7, 14, 30, 90].map(d => (
                            <button
                                key={d}
                                onClick={() => setDays(d)}
                                className={cn("px-3 py-1.5 rounded-md text-xs font-medium transition-all",
                                    days === d ? "bg-indigo-600 text-white" : "text-gray-400 hover:text-white")}
                            >
                                {d}d
                            </button>
                        ))}
                    </div>
                    <button onClick={handleExport} className="btn btn-secondary btn-sm">
                        <Download size={14} /> Export CSV
                    </button>
                </div>
            </div>

            {/* Summary */}
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
                {summaryCards.map(stat => {
                    const Icon = stat.icon;
                    return (
                        <div key={stat.label} className="stat-card">
                            <div className="flex items-center justify-between relative z-10">
                                <div>
                                    <p className="text-xs font-medium text-gray-400 uppercase tracking-wide">{stat.label}</p>
                                    <p className="text-2xl font-bold text-white mt-1">{isLoading ? '—' : stat.value}</p>
                                </div>
                                <div className={cn("w-11 h-11 rounded-xl flex items-center justify-center", stat.bg)}>
                                    <Icon size={20} className={stat.color} />
                                </div>
                            </div>
                        </div>
                    );
                })}
            </div>

            {/* Charts */}
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
                <div className="card">
                    <div className="card-header">
                        <h3 className="text-sm font-semibold">Daily Volume</h3>
                    </div>
                    <div className="card-body">
                        <div className="h-64">
                            {isLoading ? (
                                <div className="skeleton h-full w-full rounded-lg" />
                            ) : (
                                <ResponsiveContainer width="100%" height="100%">
                                    <AreaChart data={r.daily_breakdown || []}>
                                        <defs>
                                            <linearGradient id="rptTotal" x1="0" y1="0" x2="0" y2="1">
                                                <stop offset="5%" stopColor="#6366f1" stopOpacity={0.3} />
                                                <stop offset="95%" stopColor="#6366f1" stopOpacity={0} />
                                            </linearGradient>
                                        </defs>
                                        <CartesianGrid strokeDasharray="3 3" stroke="#1e1e2a" />
                                        <XAxis dataKey="date" tick={{ fill: '#5a5a70', fontSize: 11 }} tickLine={false} axisLine={false} />
                                        <YAxis tick={{ fill: '#5a5a70', fontSize: 11 }} tickLine={false} axisLine={false} />
                                        <Tooltip content={<CustomTooltip />} />
                                        <Area type="monotone" dataKey="total" stroke="#6366f1" fill="url(#rptTotal)" strokeWidth={2} name="Issues" />
                                    </AreaChart>
                                </ResponsiveContainer>
                            )}
                        </div>
                    </div>
                </div>

                <div className="card">
                    <div className="card-header">
                        <h3 className="text-sm font-semibold">Resolution by Source</h3>
                    </div>
                    <div className="card-body">
                        <div className="h-64">
                            {isLoading ? (
                                <div className="skeleton h-full w-full rounded-lg" />
                            ) : (
                                <ResponsiveContainer width="100%" height="100%">
                                    <BarChart data={Object.entries(r.by_source || {}).map(([name, value]) => ({
                                        name: name.replace('_', ' ').replace(/\b\w/g, l => l.toUpperCase()),
                                        value
                                    }))} layout="vertical">
                                        <CartesianGrid strokeDasharray="3 3" stroke="#1e1e2a" horizontal={false} />
                                        <XAxis type="number" tick={{ fill: '#5a5a70', fontSize: 11 }} tickLine={false} axisLine={false} />
                                        <YAxis type="category" dataKey="name" tick={{ fill: '#8888a0', fontSize: 12 }} width={100} tickLine={false} axisLine={false} />
                                        <Tooltip content={<CustomTooltip />} />
                                        <Bar dataKey="value" fill="#6366f1" radius={[0, 6, 6, 0]} barSize={20} name="Issues" />
                                    </BarChart>
                                </ResponsiveContainer>
                            )}
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
}
