import React, { useMemo } from 'react';
import { 
  ArrowUp, 
  ArrowDown, 
  DollarSign,
  PieChart,
  Activity,
  Calendar,
  Filter,
  TrendingUp,
  Target,
  CheckCircle2,
  Clock
} from 'lucide-react';
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import {
  PieChart as RePieChart,
  Pie,
  Cell,
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  Legend,
  AreaChart,
  Area
} from 'recharts';

/**
 * Premium KPI Card with Glow and Glassmorphism
 */
const KPICard = ({ title, value, subtext, icon, colorClass, highlight, trend }) => {
    const Icon = icon;
    return (
        <Card className="bg-[#1e293b]/40 backdrop-blur-md border-slate-800 shadow-xl relative overflow-hidden group hover:border-slate-700/50 transition-all duration-500">
            {/* Animated Glow Effect */}
            <div className={`absolute -right-8 -bottom-8 w-32 h-32 rounded-full opacity-0 group-hover:opacity-10 transition-opacity duration-700 blur-2xl ${highlight ? 'bg-emerald-500' : 'bg-blue-500'}`} />
            
            <CardContent className="p-5 flex items-start justify-between relative z-10">
                <div>
                    <p className="text-[10px] font-black text-slate-500 uppercase tracking-[0.2em] mb-1.5">{title}</p>
                    <h3 className={`text-3xl font-black tracking-tight ${highlight ? 'text-emerald-400' : 'text-white'}`}>{value}</h3>
                    <div className="flex items-center gap-2 mt-2">
                        {trend && (
                            <span className={`text-[10px] font-bold px-1.5 py-0.5 rounded ${trend === 'up' ? 'bg-emerald-500/10 text-emerald-400' : 'bg-red-500/10 text-red-400'}`}>
                                {trend === 'up' ? '+' : '-'}7.2%
                            </span>
                        )}
                        <p className="text-[11px] text-slate-500 font-medium">{subtext}</p>
                    </div>
                </div>
                <div className={`w-12 h-12 rounded-2xl flex items-center justify-center ${colorClass} bg-opacity-10 border border-current border-opacity-20 group-hover:scale-110 transition-transform duration-500 shadow-lg`}>
                    <Icon className={`w-6 h-6 ${colorClass.replace('bg-', 'text-')}`} />
                </div>
            </CardContent>
        </Card>
    );
};

export const CruzamentoView = ({ data = [], kpis = {} }) => {
    // Helper para formatação
    const formatCurrency = (val) => {
        return new Intl.NumberFormat('pt-BR', { 
            style: 'currency', 
            currency: 'BRL' 
        }).format(val || 0);
    };

    // Chart Data Processing com safe checks
    const categoryData = useMemo(() => {
        if (!Array.isArray(data)) return [];
        const map = {};
        data.forEach(item => {
            if (item?.categoria) {
                map[item.categoria] = (map[item.categoria] || 0) + (item?.valor || 0);
            }
        });
        return Object.entries(map).map(([name, value]) => ({ name, value }));
    }, [data]);

    const timelineData = useMemo(() => {
        if (!Array.isArray(data)) return [];
        const map = {};
        data.forEach(item => {
            const date = item?.dataEntrada?.substring(5) || 'N/A'; // MM-DD
            map[date] = (map[date] || 0) + (item?.valor || 0);
        });
        return Object.entries(map)
            .sort((a,b) => a[0].localeCompare(b[0]))
            .map(([name, value]) => ({ name, value }));
    }, [data]);

    const COLORS = ['#10b981', '#3b82f6', '#f59e0b', '#8b5cf6', '#ec4899', '#f43f5e'];

    return (
        <div className="space-y-6 animate-in fade-in slide-in-from-bottom-6 duration-700 mt-6 relative pb-10">
             {/* Abstract Background Elements */}
             <div className="absolute top-0 left-1/2 -translate-x-1/2 w-full max-w-4xl h-full pointer-events-none overflow-hidden opacity-20">
                <div className="absolute top-20 right-0 w-96 h-96 bg-blue-500/10 rounded-full blur-3xl" />
                <div className="absolute bottom-40 left-0 w-[500px] h-[500px] bg-emerald-500/5 rounded-full blur-3xl" />
             </div>

             {/* Filter & Summary Bar */}
             <div className="bg-[#0f172a]/60 backdrop-blur-xl p-4 rounded-2xl border border-slate-800/50 flex flex-wrap gap-6 items-center shadow-2xl relative z-10">
                <div className="flex items-center gap-2">
                    <div className="p-2 bg-slate-900 rounded-lg border border-slate-800">
                        <Filter className="w-4 h-4 text-emerald-400" />
                    </div>
                    <div className="flex items-center gap-2 bg-slate-900/50 p-1.5 rounded-xl border border-slate-800/50">
                        <Input type="date" className="h-8 w-32 bg-transparent border-none text-[11px] font-bold text-white focus-visible:ring-0 px-2" />
                        <span className="text-slate-600 font-black text-[10px] uppercase">até</span>
                        <Input type="date" className="h-8 w-32 bg-transparent border-none text-[11px] font-bold text-white focus-visible:ring-0 px-2" />
                    </div>
                </div>
                
                <div className="flex items-center gap-3">
                    <Badge variant="outline" className="h-9 px-4 rounded-xl bg-slate-900/50 border-slate-800 text-slate-400 hover:text-white transition-colors cursor-pointer">
                        Últimos 30 dias
                    </Badge>
                </div>

                <div className="ml-auto flex items-center gap-4">
                    <div className="text-right hidden md:block">
                        <p className="text-[9px] font-black text-slate-500 uppercase tracking-widest">Performance</p>
                        <p className="text-xs font-bold text-emerald-500">+12.4% vs mês anterior</p>
                    </div>
                    <div className="w-10 h-10 rounded-full border-2 border-emerald-500/20 border-t-emerald-500 animate-spin-slow flex items-center justify-center">
                        <Target className="w-4 h-4 text-emerald-500" />
                    </div>
                </div>
            </div>

            {/* KPIs */}
            <div className="grid grid-cols-1 md:grid-cols-3 gap-6 relative z-10">
                <KPICard 
                    title="Liquidado"
                    value={formatCurrency(kpis?.totalRecebido)}
                    subtext="Realizado no período"
                    icon={CheckCircle2}
                    colorClass="text-emerald-500"
                    highlight
                    trend="up"
                />
                 <KPICard 
                    title="Em Aberto"
                    value={formatCurrency(kpis?.totalPendente)}
                    subtext="Compromissos futuros"
                    icon={Clock}
                    colorClass="text-amber-500"
                    trend="down"
                />
                 <KPICard 
                    title="Volume Geral"
                    value={formatCurrency(kpis?.totalGeral)}
                    subtext="Entrada total projetada"
                    icon={TrendingUp}
                    colorClass="text-blue-500"
                    trend="up"
                />
            </div>

            {/* Charts Grid */}
             <div className="grid grid-cols-1 lg:grid-cols-2 gap-8 relative z-10">
                {/* Category Chart */}
                <Card className="bg-[#1e293b]/30 backdrop-blur-md border-slate-800/50 shadow-2xl overflow-hidden group">
                    <CardHeader className="p-6 border-b border-white/5 bg-white/5">
                        <CardTitle className="text-xs font-black text-slate-400 uppercase tracking-[0.2em] flex items-center gap-3">
                            <div className="w-7 h-7 rounded-lg bg-emerald-500/10 flex items-center justify-center border border-emerald-500/20">
                                <PieChart className="w-4 h-4 text-emerald-500" />
                            </div>
                            Composição de Receita
                        </CardTitle>
                    </CardHeader>
                    <CardContent className="h-[380px] p-6 pt-10">
                        <ResponsiveContainer width="100%" height="100%">
                            <RePieChart>
                                <Pie
                                    data={categoryData}
                                    cx="50%"
                                    cy="50%"
                                    innerRadius={85}
                                    outerRadius={115}
                                    paddingAngle={10}
                                    dataKey="value"
                                    stroke="none"
                                >
                                    {categoryData.map((entry, index) => (
                                        <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                                    ))}
                                </Pie>
                                <Tooltip 
                                    contentStyle={{ 
                                        backgroundColor: 'rgba(15, 23, 42, 0.95)', 
                                        backdropFilter: 'blur(10px)',
                                        borderColor: 'rgba(51, 65, 85, 0.5)', 
                                        borderRadius: '16px', 
                                        color: '#fff',
                                        boxShadow: '0 25px 50px -12px rgba(0, 0, 0, 0.5)'
                                    }}
                                    itemStyle={{ color: '#fff', fontSize: '12px', fontWeight: 'bold' }}
                                    formatter={(value) => formatCurrency(value)}
                                />
                                <Legend 
                                    verticalAlign="bottom" 
                                    height={40} 
                                    iconType="circle" 
                                    formatter={(value) => <span className="text-[10px] uppercase font-bold text-slate-400">{value}</span>}
                                />
                            </RePieChart>
                        </ResponsiveContainer>
                    </CardContent>
                </Card>

                {/* Timeline Chart */}
                <Card className="bg-[#1e293b]/30 backdrop-blur-md border-slate-800/50 shadow-2xl overflow-hidden group">
                    <CardHeader className="p-6 border-b border-white/5 bg-white/5">
                        <CardTitle className="text-xs font-black text-slate-400 uppercase tracking-[0.2em] flex items-center gap-3">
                            <div className="w-7 h-7 rounded-lg bg-blue-500/10 flex items-center justify-center border border-blue-500/20">
                                <Activity className="w-4 h-4 text-blue-500" />
                            </div>
                            Fluxo de Recebimento
                        </CardTitle>
                    </CardHeader>
                    <CardContent className="h-[380px] p-0 pr-6 pt-10">
                        <ResponsiveContainer width="100%" height="100%">
                            <AreaChart data={timelineData}>
                                <defs>
                                    <linearGradient id="colorWave" x1="0" y1="0" x2="0" y2="1">
                                        <stop offset="5%" stopColor="#10b981" stopOpacity={0.4}/>
                                        <stop offset="95%" stopColor="#10b981" stopOpacity={0}/>
                                    </linearGradient>
                                </defs>
                                <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#334155" opacity={0.2} />
                                <XAxis 
                                    dataKey="name" 
                                    axisLine={false} 
                                    tickLine={false} 
                                    tick={{fill: '#64748b', fontSize: 10, fontWeight: 'bold'}} 
                                    dy={10} 
                                />
                                <YAxis 
                                    axisLine={false} 
                                    tickLine={false} 
                                    tick={{fill: '#64748b', fontSize: 10}} 
                                    tickFormatter={(val) => `R$ ${val/1000}k`} 
                                />
                                <Tooltip 
                                    contentStyle={{ 
                                        backgroundColor: 'rgba(15, 23, 42, 0.95)', 
                                        backdropFilter: 'blur(10px)',
                                        borderColor: 'rgba(51, 65, 85, 0.5)', 
                                        borderRadius: '16px'
                                    }}
                                    formatter={(value) => formatCurrency(value)}
                                />
                                <Area 
                                    type="monotone" 
                                    dataKey="value" 
                                    stroke="#10b981" 
                                    strokeWidth={4} 
                                    fillOpacity={1} 
                                    fill="url(#colorWave)" 
                                    dot={{ fill: '#10b981', r: 4, strokeWidth: 2, stroke: '#1e293b' }}
                                    activeDot={{ r: 6, stroke: '#fff', strokeWidth: 2, fill: '#10b981' }}
                                />
                            </AreaChart>
                        </ResponsiveContainer>
                    </CardContent>
                </Card>
            </div>
        </div>
    );
};
