import React from 'react';
import { Search, Zap, CreditCard, MessageCircle, Smartphone, QrCode, ChevronRight, Loader2, CheckCircle2, TrendingUp, Calendar, ArrowRight, Flame } from 'lucide-react';
import HistoryCard from '@/components/common/HistoryCard';
import { AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts';

interface DashboardOverviewProps {
    user: {
        name: string;
        public_id: string;
        plan: string;
        plan_valid_until?: string;
    };
    stats: {
        totalCount: number;
        avgCals: number;
        currentStreak: number;
        longestStreak: number;
        chartData: any[];
    };
    loadingStats: boolean;
    history: any[];
    loadingHistory: boolean;
    planName: string;
    t: any;
    whatsappUrl: string;
    qrCodeUrl: string;
    whatsappNumber: string;
    setActiveTab: (tab: string) => void;
    fallbackImage: string;
}

const DashboardOverview: React.FC<DashboardOverviewProps> = ({
    user,
    stats,
    loadingStats,
    history,
    loadingHistory,
    planName,
    t,
    whatsappUrl,
    qrCodeUrl,
    whatsappNumber,
    setActiveTab,
    fallbackImage
}) => {
    return (
        <div className="max-w-7xl mx-auto animate-in fade-in duration-700 space-y-8">

            {/* 1. Hero Section (Glassmorphism / Dark Mode Concept) */}
            <div className="relative rounded-[2.5rem] bg-gray-900 p-8 md:p-12 overflow-hidden shadow-2xl text-white">
                {/* Background Blobs */}
                <div className="absolute top-0 right-0 w-[600px] h-[600px] bg-brand-600 rounded-full blur-[140px] opacity-20 translate-x-1/3 -translate-y-1/2"></div>
                <div className="absolute bottom-0 left-0 w-[500px] h-[500px] bg-blue-600 rounded-full blur-[120px] opacity-20 -translate-x-1/4 translate-y-1/3"></div>

                <div className="relative z-10 flex flex-col md:flex-row items-start justify-between gap-8">
                    <div>
                        <div className="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-white/10 backdrop-blur-md border border-white/10 text-xs font-bold uppercase tracking-widest mb-4 text-brand-300">
                            <CheckCircle2 size={12} /> {planName} Member
                        </div>
                        <h1 className="text-4xl md:text-5xl font-bold mb-4 tracking-tight leading-tight">
                            Olá, {user.name.split(' ')[0]} 👋
                        </h1>
                        <p className="text-gray-400 text-lg max-w-lg mb-8 leading-relaxed">
                            Vamos transformar sua saúde hoje? Acompanhe seu progresso e mantenha o foco nas suas metas.
                        </p>

                        <div className="flex flex-wrap gap-3">
                            <button
                                onClick={() => setActiveTab('coach')}
                                className="group bg-white text-gray-900 px-6 py-3 rounded-xl font-bold hover:bg-brand-50 transition-all flex items-center gap-2 shadow-lg hover:shadow-xl hover:-translate-y-0.5"
                            >
                                <Zap size={18} className="text-brand-600 group-hover:text-brand-700" fill="currentColor" />
                                Ver Meu Plano
                            </button>
                            <button
                                onClick={() => window.open(whatsappUrl, '_blank')}
                                className="px-6 py-3 rounded-xl font-bold border border-white/20 hover:bg-white/10 transition-all flex items-center gap-2 text-white backdrop-blur-sm"
                            >
                                <MessageCircle size={18} />
                                Novo Registro
                            </button>
                        </div>
                    </div>

                    {/* Quick Stats in Hero */}
                    <div className="grid grid-cols-2 lg:grid-cols-3 gap-4 w-full md:w-auto">
                        <div className="bg-white/5 backdrop-blur-md border border-white/10 p-5 rounded-2xl min-w-[140px]">
                            <p className="text-gray-400 text-xs font-bold uppercase tracking-wider mb-1 flex items-center gap-1"><Flame size={14} className="text-orange-500" /> Ofensiva</p>
                            <p className="text-3xl font-black text-white">{loadingStats ? '...' : stats.currentStreak} 🔥</p>
                            <div className="mt-2 text-[10px] text-orange-300 bg-orange-900/50 px-2 py-1 rounded inline-block">
                                Recorde: {stats.longestStreak}
                            </div>
                        </div>
                        <div className="bg-white/5 backdrop-blur-md border border-white/10 p-5 rounded-2xl min-w-[140px]">
                            <p className="text-gray-400 text-xs font-bold uppercase tracking-wider mb-1">{t.dashboard.statDishes}</p>
                            <p className="text-3xl font-black text-white">{loadingStats ? '...' : stats.totalCount}</p>
                            <div className="mt-2 text-[10px] text-brand-300 bg-brand-900/50 px-2 py-1 rounded inline-block">
                                Total de Análises
                            </div>
                        </div>
                        <div className="bg-white/5 backdrop-blur-md border border-white/10 p-5 rounded-2xl min-w-[140px] col-span-2 lg:col-span-1">
                            <p className="text-gray-400 text-xs font-bold uppercase tracking-wider mb-1">{t.dashboard.statCals}</p>
                            <p className="text-3xl font-black text-white">{loadingStats ? '...' : Math.round(stats.avgCals || 0)}</p>
                            <div className="mt-2 text-[10px] text-blue-300 bg-blue-900/50 px-2 py-1 rounded inline-block">
                                Média Histórica
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
                {/* 2. Main Column */}
                <div className="lg:col-span-2 space-y-8">

                    {/* Gamification Chart */}
                    <div className="bg-white rounded-[2rem] p-6 border border-gray-100 shadow-sm">
                        <div className="flex items-center justify-between mb-6">
                            <h2 className="text-xl font-bold text-gray-900">Evolução de Calorias (7 Dias)</h2>
                        </div>
                        <div className="h-[250px] w-full">
                            {loadingStats ? (
                                <div className="h-full flex items-center justify-center"><Loader2 className="animate-spin text-brand-500" /></div>
                            ) : stats.chartData && stats.chartData.length > 0 ? (
                                <ResponsiveContainer width="100%" height="100%">
                                    <AreaChart data={stats.chartData} margin={{ top: 10, right: 10, left: -20, bottom: 0 }}>
                                        <defs>
                                            <linearGradient id="colorCals" x1="0" y1="0" x2="0" y2="1">
                                                <stop offset="5%" stopColor="#4F46E5" stopOpacity={0.3} />
                                                <stop offset="95%" stopColor="#4F46E5" stopOpacity={0} />
                                            </linearGradient>
                                        </defs>
                                        <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#f3f4f6" />
                                        <XAxis dataKey="date" axisLine={false} tickLine={false} tick={{ fontSize: 12, fill: '#6B7280' }} dy={10} />
                                        <YAxis axisLine={false} tickLine={false} tick={{ fontSize: 12, fill: '#6B7280' }} />
                                        <Tooltip
                                            contentStyle={{ borderRadius: '1rem', border: 'none', boxShadow: '0 10px 15px -3px rgba(0, 0, 0, 0.1)' }}
                                            cursor={{ stroke: '#4F46E5', strokeWidth: 1, strokeDasharray: '3 3' }}
                                        />
                                        <Area type="monotone" dataKey="calories" name="Calorias (kcal)" stroke="#4F46E5" strokeWidth={3} fillOpacity={1} fill="url(#colorCals)" />
                                    </AreaChart>
                                </ResponsiveContainer>
                            ) : (
                                <div className="h-full flex items-center justify-center text-gray-400 font-medium">Não há dados suficientes</div>
                            )}
                        </div>
                    </div>

                    {/* Recent History */}
                    <div className="space-y-6">
                        <div className="flex items-center justify-between">
                            <h2 className="text-xl font-bold text-gray-900 flex items-center gap-2">
                                <TrendingUp className="text-brand-500" size={24} />
                                {t.dashboard.recentTitle}
                            </h2>
                            <button
                                onClick={() => setActiveTab('history')}
                                className="text-sm font-semibold text-gray-500 hover:text-brand-600 flex items-center gap-1 transition-colors"
                            >
                                Ver Todos <ArrowRight size={16} />
                            </button>
                        </div>

                        {loadingHistory ? (
                            <div className="flex justify-center p-12"><Loader2 className="animate-spin text-brand-500" size={32} /></div>
                        ) : history.length === 0 ? (
                            <div className="text-center p-12 bg-white rounded-3xl border border-dashed border-gray-200">
                                <div className="w-16 h-16 bg-gray-50 rounded-full flex items-center justify-center mx-auto mb-4">
                                    <Search className="text-gray-300" size={32} />
                                </div>
                                <p className="text-gray-500 font-medium">{t.dashboard.emptyRecent}</p>
                                <button
                                    onClick={() => window.open(whatsappUrl, '_blank')}
                                    className="mt-4 text-brand-600 font-bold hover:underline"
                                >
                                    Começar Agora
                                </button>
                            </div>
                        ) : (
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                {history.slice(0, 4).map(item => (
                                    <HistoryCard key={item.id} item={item} fallback={fallbackImage} />
                                ))}
                            </div>
                        )}
                    </div>
                </div>

                {/* 3. Side Widget (WhatsApp Connect) */}
                <div className="space-y-6">
                    <div className="bg-white rounded-3xl p-6 border border-gray-100 shadow-sm relative overflow-hidden group hover:shadow-md transition-all duration-500">
                        <div className="absolute top-0 right-0 w-32 h-32 bg-green-50 rounded-full blur-[60px] -translate-y-1/2 translate-x-1/2 group-hover:bg-green-100 transition-colors"></div>

                        <div className="relative z-10 flex flex-col items-center text-center">
                            <div className="bg-white p-2 rounded-2xl shadow-lg border border-gray-100 mb-4 transform group-hover:scale-105 transition-transform duration-300">
                                <img
                                    src={qrCodeUrl}
                                    alt="QR Code"
                                    className="w-32 h-32 mix-blend-multiply"
                                />
                            </div>
                            <h3 className="text-lg font-bold text-gray-900 mb-1">Conectar WhatsApp</h3>
                            <p className="text-sm text-gray-500 mb-4 px-4">Escaneie para enviar fotos e receber análises instantâneas.</p>

                            <button
                                onClick={() => window.open(whatsappUrl, '_blank')}
                                className="w-full bg-green-600 hover:bg-green-700 text-white font-bold py-3 rounded-xl flex items-center justify-center gap-2 transition-colors shadow-lg shadow-green-500/20"
                            >
                                <MessageCircle size={18} />
                                Abrir WhatsApp Web
                            </button>
                        </div>
                    </div>

                    {/* Mini Plan Status */}
                    <div className="bg-white rounded-3xl p-6 border border-gray-100 shadow-sm flex items-center justify-between">
                        <div>
                            <p className="text-xs font-bold text-gray-400 uppercase tracking-wider mb-1">Status do Plano</p>
                            <div className="flex items-center gap-2">
                                <div className={`w-2 h-2 rounded-full ${user.plan === 'pro' ? 'bg-brand-500' : 'bg-gray-400'}`}></div>
                                <span className="font-bold text-gray-900 text-lg capitalize">{planName}</span>
                            </div>
                            {user.plan_valid_until && (
                                <p className="text-xs text-gray-500 mt-1">Válido até {new Date(user.plan_valid_until).toLocaleDateString('pt-BR')}</p>
                            )}
                        </div>
                        <div className="w-12 h-12 bg-gray-50 rounded-2xl flex items-center justify-center text-gray-400">
                            <CreditCard size={24} />
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
};

export default DashboardOverview;
