import { useState, useEffect } from 'react';
import Head from 'next/head';
import Layout from '../components/Layout';
import { scanAPI, licenseAPI } from '../services/api';
import { useAuth } from '../hooks/useAuth';
import {
    BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer,
    AreaChart, Area, PieChart, Pie, Cell,
} from 'recharts';

const COLORS = ['#3b82f6', '#10b981', '#f59e0b', '#ef4444', '#8b5cf6', '#06b6d4'];

interface ScanHistoryItem {
    id: string;
    marketplace: string;
    keyword: string | null;
    totalProducts: number;
    avgPrice: number | null;
    medianPrice: number | null;
    createdAt: string;
    aiRecommendation: any;
}

export default function DashboardPage() {
    const { user, isPro } = useAuth();
    const [stats, setStats] = useState({ totalScans: 0, license: null as any });
    const [recentScans, setRecentScans] = useState<ScanHistoryItem[]>([]);
    const [loading, setLoading] = useState(true);

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

    const loadDashboard = async () => {
        try {
            const [scanRes, licenseRes] = await Promise.all([
                scanAPI.getHistory({ page: '1', limit: '10' }),
                licenseAPI.getMy().catch(() => ({ data: { data: null } })),
            ]);

            setRecentScans(scanRes.data.data.scans || []);
            setStats({
                totalScans: scanRes.data.data.total || 0,
                license: licenseRes.data.data,
            });
        } catch (err) {
            console.error('Dashboard load error:', err);
        }
        setLoading(false);
    };

    const formatIDR = (n: number) => new Intl.NumberFormat('id-ID', { style: 'currency', currency: 'IDR', maximumFractionDigits: 0 }).format(n);

    // Chart data from recent scans
    const chartData = recentScans.slice(0, 7).reverse().map((s) => ({
        date: new Date(s.createdAt).toLocaleDateString('id-ID', { day: '2-digit', month: 'short' }),
        avg: s.avgPrice || 0,
        median: s.medianPrice || 0,
        products: s.totalProducts,
    }));

    const marketplaceData = recentScans.reduce((acc, s) => {
        const existing = acc.find((a) => a.name === s.marketplace);
        if (existing) existing.value++;
        else acc.push({ name: s.marketplace, value: 1 });
        return acc;
    }, [] as { name: string; value: number }[]);

    return (
        <>
            <Head>
                <title>Dashboard – MarketScope</title>
            </Head>
            <Layout>
                <div className="animate-fade-in">
                    {/* Header */}
                    <div className="flex items-center justify-between mb-8">
                        <div>
                            <h1 className="text-2xl font-bold">Dashboard</h1>
                            <p className="text-gray-500">Welcome back, {user?.name} 👋</p>
                        </div>
                        <div className={`px-4 py-2 rounded-full text-sm font-bold ${isPro ? 'bg-gradient-to-r from-yellow-500 to-orange-500 text-black' : 'bg-dark-hover text-gray-400'}`}>
                            {isPro ? '⭐ PRO' : '🆓 FREE'}
                        </div>
                    </div>

                    {/* Stat Cards */}
                    <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-8">
                        <div className="stat-card">
                            <p className="text-gray-500 text-xs uppercase tracking-wider">Total Scans</p>
                            <p className="text-3xl font-bold text-brand-primary mt-1">{stats.totalScans}</p>
                        </div>
                        <div className="stat-card">
                            <p className="text-gray-500 text-xs uppercase tracking-wider">Plan</p>
                            <p className="text-3xl font-bold text-yellow-500 mt-1">{stats.license?.plan || 'FREE'}</p>
                        </div>
                        <div className="stat-card">
                            <p className="text-gray-500 text-xs uppercase tracking-wider">Max Scan</p>
                            <p className="text-3xl font-bold text-green-500 mt-1">
                                {stats.license?.maxScan === -1 ? '∞' : stats.license?.maxScan || 50}
                            </p>
                        </div>
                        <div className="stat-card">
                            <p className="text-gray-500 text-xs uppercase tracking-wider">License Key</p>
                            <p className="text-sm font-mono text-cyan-400 mt-2 break-all">{stats.license?.key || '-'}</p>
                        </div>
                    </div>

                    {/* Charts Row */}
                    <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-8">
                        {/* Price Trend */}
                        <div className="card col-span-2">
                            <h3 className="text-sm font-bold text-gray-400 uppercase tracking-wider mb-4">📈 Trend Harga Scan Terakhir</h3>
                            <div className="h-64">
                                <ResponsiveContainer width="100%" height="100%">
                                    <AreaChart data={chartData}>
                                        <defs>
                                            <linearGradient id="avgGrad" x1="0" y1="0" x2="0" y2="1">
                                                <stop offset="5%" stopColor="#3b82f6" stopOpacity={0.3} />
                                                <stop offset="95%" stopColor="#3b82f6" stopOpacity={0} />
                                            </linearGradient>
                                        </defs>
                                        <CartesianGrid strokeDasharray="3 3" stroke="#334155" />
                                        <XAxis dataKey="date" tick={{ fill: '#94a3b8', fontSize: 11 }} />
                                        <YAxis tick={{ fill: '#94a3b8', fontSize: 11 }} tickFormatter={(v) => `${(v / 1000).toFixed(0)}k`} />
                                        <Tooltip contentStyle={{ background: '#1e293b', border: '1px solid #334155', borderRadius: 8, color: '#e2e8f0' }} />
                                        <Area type="monotone" dataKey="avg" stroke="#3b82f6" fill="url(#avgGrad)" name="Avg Price" />
                                        <Area type="monotone" dataKey="median" stroke="#8b5cf6" fill="none" strokeDasharray="5 5" name="Median" />
                                    </AreaChart>
                                </ResponsiveContainer>
                            </div>
                        </div>

                        {/* Marketplace Distribution */}
                        <div className="card">
                            <h3 className="text-sm font-bold text-gray-400 uppercase tracking-wider mb-4">🏪 Marketplace</h3>
                            <div className="h-64">
                                <ResponsiveContainer width="100%" height="100%">
                                    <PieChart>
                                        <Pie data={marketplaceData} dataKey="value" nameKey="name" cx="50%" cy="50%" innerRadius={50} outerRadius={80} paddingAngle={4}>
                                            {marketplaceData.map((_, i) => (
                                                <Cell key={i} fill={COLORS[i % COLORS.length]} />
                                            ))}
                                        </Pie>
                                        <Tooltip contentStyle={{ background: '#1e293b', border: '1px solid #334155', borderRadius: 8, color: '#e2e8f0' }} />
                                    </PieChart>
                                </ResponsiveContainer>
                                <div className="flex justify-center gap-4 -mt-4">
                                    {marketplaceData.map((m, i) => (
                                        <div key={m.name} className="flex items-center gap-1.5">
                                            <div className="w-2.5 h-2.5 rounded-full" style={{ background: COLORS[i % COLORS.length] }} />
                                            <span className="text-xs text-gray-400">{m.name}</span>
                                        </div>
                                    ))}
                                </div>
                            </div>
                        </div>
                    </div>

                    {/* Recent Scans Table */}
                    <div className="card">
                        <h3 className="text-sm font-bold text-gray-400 uppercase tracking-wider mb-4">🔍 Scan Terakhir</h3>
                        <div className="overflow-x-auto">
                            <table className="w-full">
                                <thead>
                                    <tr className="text-left text-xs text-gray-500 uppercase border-b border-dark-border">
                                        <th className="pb-3 pr-4">Marketplace</th>
                                        <th className="pb-3 pr-4">Keyword</th>
                                        <th className="pb-3 pr-4">Products</th>
                                        <th className="pb-3 pr-4">Avg Price</th>
                                        <th className="pb-3 pr-4">Median</th>
                                        <th className="pb-3">Date</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {recentScans.map((scan) => (
                                        <tr key={scan.id} className="border-b border-dark-border/50 hover:bg-dark-hover/30 transition-colors">
                                            <td className="py-3 pr-4">
                                                <span className="px-2 py-1 rounded-md bg-brand-primary/10 text-brand-primary text-xs font-medium">
                                                    {scan.marketplace}
                                                </span>
                                            </td>
                                            <td className="py-3 pr-4 text-sm">{scan.keyword || '-'}</td>
                                            <td className="py-3 pr-4 text-sm font-medium">{scan.totalProducts}</td>
                                            <td className="py-3 pr-4 text-sm text-blue-400">{scan.avgPrice ? formatIDR(scan.avgPrice) : '-'}</td>
                                            <td className="py-3 pr-4 text-sm text-purple-400">{scan.medianPrice ? formatIDR(scan.medianPrice) : '-'}</td>
                                            <td className="py-3 text-xs text-gray-500">{new Date(scan.createdAt).toLocaleDateString('id-ID')}</td>
                                        </tr>
                                    ))}
                                    {recentScans.length === 0 && (
                                        <tr>
                                            <td colSpan={6} className="py-8 text-center text-gray-500">
                                                Belum ada scan. Gunakan Chrome Extension untuk mulai scanning.
                                            </td>
                                        </tr>
                                    )}
                                </tbody>
                            </table>
                        </div>
                    </div>

                    {/* AI Recommendation Summary */}
                    {isPro && recentScans.length > 0 && recentScans[0].aiRecommendation && (
                        <div className="card mt-4">
                            <h3 className="text-sm font-bold text-gray-400 uppercase tracking-wider mb-4">🤖 AI Recommendation (Latest Scan)</h3>
                            <div className="grid grid-cols-3 gap-4">
                                <div className="bg-green-500/10 border border-green-500/20 rounded-lg p-4 text-center">
                                    <p className="text-xs text-gray-500 uppercase">Entry Price</p>
                                    <p className="text-xl font-bold text-green-400 mt-1">{formatIDR(recentScans[0].aiRecommendation.entryPrice)}</p>
                                </div>
                                <div className="bg-blue-500/10 border border-blue-500/20 rounded-lg p-4 text-center">
                                    <p className="text-xs text-gray-500 uppercase">Competitive</p>
                                    <p className="text-xl font-bold text-blue-400 mt-1">{formatIDR(recentScans[0].aiRecommendation.competitivePrice)}</p>
                                </div>
                                <div className="bg-yellow-500/10 border border-yellow-500/20 rounded-lg p-4 text-center">
                                    <p className="text-xs text-gray-500 uppercase">Premium</p>
                                    <p className="text-xl font-bold text-yellow-400 mt-1">{formatIDR(recentScans[0].aiRecommendation.premiumPrice)}</p>
                                </div>
                            </div>
                        </div>
                    )}
                </div>
            </Layout>
        </>
    );
}
