import React, { useState, useMemo } from 'react';
import { 
  TrendingUp, 
  TrendingDown, 
  Wallet, 
  Calendar,
  Download,
  Filter,
  ArrowUpRight,
  ArrowDownRight,
  MoreHorizontal,
  Flame,
  Scale,
  AlertTriangle,
  HandCoins,
  Search,
  ChevronDown
} from 'lucide-react';
import { 
  Card, 
  CardContent, 
  CardHeader, 
  CardTitle, 
  CardDescription 
} from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { 
  Table, 
  TableBody, 
  TableCell, 
  TableHead, 
  TableHeader, 
  TableRow 
} from '@/components/ui/table';
import {
  ComposedChart,
  Line,
  Area,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer,
  ReferenceLine
} from 'recharts';

// --- Visual Components with Premium Light Theme ---

const FinanceHeader = () => {
  return (
    <div className="flex flex-col lg:flex-row items-center justify-between bg-white p-6 rounded-3xl border border-slate-100 shadow-lg shadow-slate-200/50 mb-10">
      <div className="flex items-center gap-6">
        <div className="w-14 h-14 bg-emerald-600 rounded-3xl flex items-center justify-center shadow-xl shadow-emerald-600/20">
          <Wallet className="w-7 h-7 text-white" strokeWidth={2.5} />
        </div>
        <div>
          <h1 className="text-3xl font-black text-slate-900 tracking-tight">Fluxo de Caixa</h1>
          <p className="text-slate-400 text-xs uppercase tracking-[0.2em] font-black mt-1">Visão Estratégica & Forecast</p>
        </div>
        <div className="h-12 w-px bg-slate-200 mx-4 hidden lg:block" />
        <div className="flex gap-8 text-sm">
          <div className="flex flex-col">
            <span className="text-[9px] text-slate-400 font-black uppercase tracking-widest">Dólar</span>
            <span className="font-mono font-black text-slate-900 flex items-center gap-1.5 text-sm">
              R$ 5.42 <span className="text-rose-600 text-[10px]">▼</span>
            </span>
          </div>
          <div className="flex flex-col">
            <span className="text-[9px] text-slate-400 font-black uppercase tracking-widest">Euro</span>
            <span className="font-mono font-black text-slate-900 flex items-center gap-1.5 text-sm">
              R$ 6.41 <span className="text-emerald-600 text-[10px]">▲</span>
            </span>
          </div>
          <div className="flex flex-col">
            <span className="text-[9px] text-slate-400 font-black uppercase tracking-widest">Selic</span>
            <span className="font-mono font-black text-slate-900 text-sm">0.055131%</span>
          </div>
          <div className="flex flex-col">
            <span className="text-[9px] text-slate-400 font-black uppercase tracking-widest">IPCA</span>
            <span className="font-mono font-black text-slate-900 text-sm">0.18%</span>
          </div>
        </div>
      </div>
    </div>
  );
};

const KPICard = ({ title, value, subtext, icon: IconComponent, colorClass, highlight }) => (
  <Card className="bg-white border-slate-200 shadow-lg shadow-slate-200/40 relative overflow-hidden group hover:border-emerald-500/50 transition-all duration-300 rounded-3xl">
    <CardContent className="p-8 flex items-center justify-between relative z-10">
      <div className="space-y-2">
        <p className="text-[10px] font-black text-slate-400 uppercase tracking-[0.2em]">{title}</p>
        <h3 className={`text-3xl font-black tracking-tighter ${highlight ? 'text-emerald-600' : 'text-slate-900'}`}>{value}</h3>
        <p className="text-xs text-slate-500 font-bold">{subtext}</p>
      </div>
      <div className={`p-4 rounded-2xl ${colorClass.replace('bg-', 'bg-')}/10 shadow-sm border border-${colorClass.replace('bg-', '')}/10 group-hover:scale-110 transition-transform duration-500`}>
        <IconComponent className={`w-8 h-8 ${colorClass.replace('bg-', 'text-')}`} strokeWidth={2.5} />
      </div>
    </CardContent>
    {/* Decorative Background Glow */}
    <div className={`absolute -bottom-10 -right-10 w-32 h-32 ${colorClass.replace('bg-', 'bg-')}/5 rounded-full blur-3xl pointer-events-none group-hover:blur-2xl transition-all duration-500`} />
  </Card>
);

const ChartSection = () => {
    const data = useMemo(() => Array.from({ length: 30 }, (_, i) => ({
        name: i + 1,
        saldo: 1000 + Math.random() * 500,
        entrada: Math.random() * 300,
        saida: -Math.random() * 200,
    })), []);

    return (
        <Card className="bg-white border-slate-100 shadow-xl shadow-slate-200/40 p-8 rounded-3xl">
            <div className="flex flex-col md:flex-row justify-between items-center mb-8 gap-6">
                <div className="flex items-center gap-6">
                    <div className="w-12 h-12 rounded-2xl bg-emerald-50 flex items-center justify-center">
                        <TrendingUp className="text-emerald-600 w-6 h-6" strokeWidth={2.5} />
                    </div>
                    <div>
                        <h3 className="text-lg font-black text-slate-900 tracking-tight">Projeção de Fluxo</h3>
                        <div className="flex gap-2 mt-2">
                             <span className="text-[9px] font-black text-slate-400 uppercase tracking-widest">Simular:</span>
                             <Badge variant="outline" className="text-[9px] font-black border-rose-200 text-rose-600 hover:bg-rose-50 cursor-pointer px-2 py-0.5">Perda</Badge>
                             <Badge variant="outline" className="text-[9px] font-black border-amber-200 text-amber-600 hover:bg-amber-50 cursor-pointer px-2 py-0.5">Dólar</Badge>
                             <Badge variant="outline" className="text-[9px] font-black border-rose-200 text-rose-600 hover:bg-rose-50 cursor-pointer px-2 py-0.5">Stress</Badge>
                        </div>
                    </div>
                </div>
                
                <div className="flex bg-slate-100 rounded-xl p-1.5 gap-1.5 shadow-inner">
                    <button className="px-5 py-2 rounded-lg text-xs font-black bg-emerald-600 text-white shadow-lg shadow-emerald-600/20 transition-all active:scale-95">Executado</button>
                    <button className="px-5 py-2 rounded-lg text-xs font-black text-slate-500 hover:text-slate-900 hover:bg-white transition-all">Planejado</button>
                </div>
            </div>

            <div className="h-[340px] w-full">
                <ResponsiveContainer width="100%" height="100%" minHeight={300}>
                    <ComposedChart data={data}>
                        <defs>
                            <linearGradient id="gSaldo" x1="0" y1="0" x2="0" y2="1">
                                <stop offset="5%" stopColor="#10b981" stopOpacity={0.15}/>
                                <stop offset="95%" stopColor="#10b981" stopOpacity={0}/>
                            </linearGradient>
                        </defs>
                        <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#f1f5f9" />
                        <XAxis dataKey="name" axisLine={false} tickLine={false} tick={{fill: '#94a3b8', fontSize: 10, fontWeight: 'bold'}} dy={10} />
                        <YAxis axisLine={false} tickLine={false} tick={{fill: '#94a3b8', fontSize: 10}} />
                        <Tooltip 
                            contentStyle={{ backgroundColor: '#ffffff', border: '1px solid #f1f5f9', color: '#0f172a', borderRadius: '16px', boxShadow: '0 10px 15px -3px rgba(0,0,0,0.1)' }}
                            itemStyle={{ fontSize: '12px', fontWeight: 'bold' }}
                        />
                        <Area type="monotone" dataKey="saldo" stroke="#10b981" fill="url(#gSaldo)" strokeWidth={3} dot={false} />
                        <Bar dataKey="entrada" fill="#34d399" barSize={6} radius={[3, 3, 0, 0]} />
                        <Bar dataKey="saida" fill="#f87171" barSize={6} radius={[3, 3, 0, 0]} />
                    </ComposedChart>
                </ResponsiveContainer>
            </div>
        </Card>
    );
}

const DetailTable = () => {
    const transactions = [
        { date: '03/01/2026', desc: 'Serviços de Consultoria', cat: 'DESPESA', val: '-R$ 2.372,13', status: 'PENDENTE' },
        { date: '03/01/2026', desc: 'Licença de Software', cat: 'DESPESA', val: '-R$ 215,19', status: 'PENDENTE' },
        { date: '03/01/2026', desc: 'Serviços de Consultoria', cat: 'RECEITA', val: 'R$ 806,32', status: 'COMPENSADO' },
        { date: '03/01/2026', desc: 'Compra de Material', cat: 'RECEITA', val: 'R$ 4.193,28', status: 'PENDENTE' },
        { date: '03/01/2026', desc: 'Reembolso Despesas', cat: 'RECEITA', val: 'R$ 929,88', status: 'PENDENTE' },
        { date: '03/01/2026', desc: 'Serviços de Consultoria', cat: 'RECEITA', val: 'R$ 2.330,37', status: 'PENDENTE' },
        { date: '03/01/2026', desc: 'Manutenção Preventiva', cat: 'DESPESA', val: '-R$ 1.073,58', status: 'PENDENTE' },
    ];

    return (
        <Card className="bg-white border-slate-100 shadow-xl shadow-slate-200/40 mt-8 rounded-3xl overflow-hidden">
            <CardHeader className="py-6 px-8 border-b border-slate-50 flex flex-row items-center justify-between bg-slate-50/30">
                <div className="flex items-center gap-4">
                    <div className="w-10 h-10 rounded-2xl bg-slate-100 flex items-center justify-center">
                        <div className="w-1.5 h-5 bg-emerald-600 rounded-full" />
                    </div>
                    <div>
                        <h3 className="font-black text-slate-900 text-lg tracking-tight">Detalhamento de Lançamentos</h3>
                        <span className="text-[10px] bg-slate-100 text-slate-500 px-3 py-1 rounded-lg font-black uppercase tracking-wider mt-1 inline-block">Mostrando 20 de 1013 lançamentos</span>
                    </div>
                </div>
                <div className="flex gap-3">
                    <Button variant="outline" size="sm" className="bg-white border-slate-200 text-slate-600 h-9 text-xs font-black hover:bg-slate-50 rounded-xl shadow-sm">
                        Categoria <ChevronDown className="w-3.5 h-3.5 ml-2" />
                    </Button>
                    <Button variant="outline" size="sm" className="bg-white border-slate-200 text-slate-600 h-9 text-xs font-black hover:bg-slate-50 rounded-xl shadow-sm">
                        Status <ChevronDown className="w-3.5 h-3.5 ml-2" />
                    </Button>
                </div>
            </CardHeader>
            <CardContent className="p-0">
                <div className="overflow-x-auto">
                    <Table>
                        <TableHeader className="bg-slate-50/50 border-b border-slate-100">
                            <TableRow className="hover:bg-transparent border-none">
                                <TableHead className="text-slate-400 font-black text-[9px] uppercase tracking-widest h-12 px-8">Data</TableHead>
                                <TableHead className="text-slate-400 font-black text-[9px] uppercase tracking-widest h-12 w-[40%]">Descrição</TableHead>
                                <TableHead className="text-slate-400 font-black text-[9px] uppercase tracking-widest h-12 text-center">Categoria</TableHead>
                                <TableHead className="text-slate-400 font-black text-[9px] uppercase tracking-widest h-12 text-right">Valor (R$)</TableHead>
                                <TableHead className="text-slate-400 font-black text-[9px] uppercase tracking-widest h-12 text-right pr-8">Status</TableHead>
                            </TableRow>
                        </TableHeader>
                        <TableBody>
                            {transactions.map((t, i) => (
                                <TableRow key={i} className="border-b border-slate-50 hover:bg-slate-50/50 transition-colors group">
                                    <TableCell className="font-mono text-xs text-slate-900 font-black py-4 px-8 border-r border-slate-50">{t.date}</TableCell>
                                    <TableCell className="text-sm text-slate-700 font-bold py-4 border-r border-slate-50 group-hover:text-emerald-600 transition-colors">{t.desc}</TableCell>
                                    <TableCell className="py-4 text-center border-r border-slate-50">
                                        <span className="bg-slate-100 border border-slate-200 text-slate-600 text-[9px] uppercase font-black tracking-wider px-2.5 py-1 rounded-lg">
                                            {t.cat}
                                        </span>
                                    </TableCell>
                                    <TableCell className={`font-mono text-xs font-black text-right py-4 border-r border-slate-50 ${t.val.includes('-') ? 'text-rose-600' : 'text-emerald-600'}`}>
                                        {t.val}
                                    </TableCell>
                                    <TableCell className="py-4 text-right pr-8">
                                        <Badge className={`
                                            text-[9px] font-black border-none px-3 py-1 rounded-full uppercase tracking-wide
                                            ${t.status === 'PENDENTE' ? 'bg-amber-100 text-amber-700' : 'bg-emerald-100 text-emerald-700'}
                                        `}>
                                            {t.status}
                                        </Badge>
                                    </TableCell>
                                </TableRow>
                            ))}
                        </TableBody>
                    </Table>
                </div>
            </CardContent>
        </Card>
    );
}

export const FluxoCaixaView = () => {
  return (
    <div className="animate-in fade-in duration-700 max-w-[1600px] mx-auto pb-12">
      <FinanceHeader />

      {/* KPI Row - Balanced Grid for Premium Feel */}
      <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-6 mb-10">
        <KPICard 
            title="Saldo Disponível" 
            value="R$ 1.842.150,00" 
            subtext="Liquidez Imediata" 
            icon={Wallet} 
            colorClass="bg-emerald-500" 
            highlight
        />
        <KPICard 
            title="Forecast de Entradas" 
            value="R$ 842.120,32" 
            subtext="Próximos 15 dias" 
            icon={TrendingUp} 
            colorClass="bg-blue-500" 
        />
        <KPICard 
            title="Comprometimento" 
            value="R$ 145.829,12" 
            subtext="Saídas agendadas" 
            icon={Scale} 
            colorClass="bg-amber-500" 
        />
      </div>

      <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-10">
        <KPICard 
            title="Burn Rate Médio" 
            value="R$ 45.200,00" 
            subtext="Consumo mensal" 
            icon={Flame} 
            colorClass="bg-rose-500" 
        />
        <KPICard 
            title="Runway Projetado" 
            value="14.2 Meses" 
            subtext="Sobrevivência de caixa" 
            icon={Calendar} 
            colorClass="bg-cyan-500" 
        />
        <KPICard 
            title="Risco de Liquidez" 
            value="MÍNIMO" 
            subtext="Saúde financeira estável" 
            icon={AlertTriangle} 
            colorClass="bg-emerald-500" 
        />
      </div>

      {/* Chart Section */}
      <ChartSection />

      {/* Detail Table */}
      <DetailTable />
    </div>
  );
};

