import React, { useState } from 'react';
import { 
  ArrowUpRight, 
  ArrowDownRight,
  DollarSign,
  TrendingUp,
  CreditCard,
  Users,
  Settings,
  MoreHorizontal
} from 'lucide-react';
import { Card, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  AreaChart,
  Area,
  PieChart,
  Pie,
  Cell
} from 'recharts';
import { cn } from '@/lib/utils';

const cashFlowData = [
  { name: '13 de dez.', valor: -590000, projetado: false },
  { name: '15 de dez.', valor: -630000, projetado: false },
  { name: '17 de dez.', valor: -650000, projetado: false },
  { name: '19 de dez.', valor: -675000, projetado: false },
  { name: '21 de dez.', valor: -665000, projetado: false },
  { name: '23 de dez.', valor: -668000, projetado: false },
  { name: '25 de dez.', valor: -667000, projetado: false },
  { name: '27 de dez.', valor: -669000, projetado: false },
  { name: '29 de dez.', valor: -668000, projetado: false },
  { name: '31 de dez.', valor: -669000, projetado: false },
  { name: '02 de jan.', valor: -667000, projetado: false },
  { name: '04 de jan.', valor: -668000, projetado: false },
  { name: '06 de jan.', valor: -669000, projetado: false },
  { name: '08 de jan.', valor: -667000, projetado: false },
  { name: '10 de jan.', valor: -668000, projetado: false },
  { name: '12 de jan.', valor: -645000, projetado: false },
  // Projeção
  { name: '14 de jan.', valor: -645000, projetado: true },
  { name: '16 de jan.', valor: -645000, projetado: true },
  { name: '18 de jan.', valor: -645000, projetado: true },
  { name: '20 de jan.', valor: -645000, projetado: true },
  { name: '22 de jan.', valor: -645000, projetado: true },
  { name: '24 de jan.', valor: -645000, projetado: true },
  { name: '26 de jan.', valor: -645000, projetado: true },
];

const barData = [
  { name: 'Jan', entradas: 14000, saídas: 9000 },
  { name: 'Fev', entradas: 19000, saídas: 13000 },
  { name: 'Mar', entradas: 2500, saídas: 20000 },
  { name: 'Abr', entradas: 4000, saídas: 5000 },
  { name: 'Mai', entradas: 1500, saídas: 6000 },
  { name: 'Jun', entradas: 3000, saídas: 4500 },
];

const pieData = [
  { name: 'Pago', value: 65, color: '#10b981' },
  { name: 'Pendente', value: 25, color: '#f59e0b' },
  { name: 'Vencido', value: 10, color: '#ef4444' },
];

const XPICard = ({ title, value, subtitle, icon: Icon, color, bgIcon }) => (
  <Card className="bg-[#0b1120] border-none shadow-xl relative overflow-hidden group">
    <CardContent className="p-6 relative z-10 flex items-center gap-5">
      <div className={cn("w-14 h-14 rounded-2xl flex items-center justify-center transition-transform duration-500 group-hover:scale-110 shadow-lg", bgIcon)}>
        <Icon size={24} className={cn("text-white")} />
      </div>
      <div className="flex flex-col">
        <span className="text-[10px] font-black text-slate-500 uppercase tracking-widest">{title}</span>
        <div className="flex items-baseline gap-2 mt-1">
          <span className="text-2xl font-black text-white tracking-tighter">{value}</span>
        </div>
        <span className="text-[10px] font-bold text-slate-500 mt-1">{subtitle}</span>
      </div>
    </CardContent>
    {/* Background Pattern */}
    <div className="absolute top-0 right-0 p-4 opacity-5">
       <Icon size={80} strokeWidth={1} />
    </div>
  </Card>
);

const ProgressBarWidget = ({ label, percentage, current, total, colorClass }) => (
  <div className="space-y-3">
    <div className="flex justify-between items-end">
      <span className="text-xs font-black text-slate-200 uppercase tracking-widest">{label}</span>
      <span className={cn("text-xs font-black", colorClass)}>{percentage}%</span>
    </div>
    <div className="h-2 w-full bg-slate-800 rounded-full overflow-hidden">
      <div 
        className={cn("h-full rounded-full transition-all duration-1000", colorClass.replace('text-', 'bg-'))} 
        style={{ width: `${percentage}%` }}
      />
    </div>
    <div className="flex justify-between text-[10px] font-bold text-slate-500">
      <span>R$ {current} disponíveis</span>
      <span>{current} / {total}</span>
    </div>
  </div>
);

export const DashboardView = () => {
  const [period, setPeriod] = useState('30');

  return (
    <div className="space-y-6">
      {/* KPI Grid */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
        <XPICard 
          title="CAIXA LÍQUIDO" 
          value="-R$ 640,3 mil" 
          subtitle="Posição Atual"
          icon={DollarSign}
          bgIcon="bg-emerald-950/30 text-emerald-500"
        />
        <XPICard 
          title="FATURAMENTO" 
          value="R$ 1,2 mi" 
          subtitle="Acumulado (30 dias)"
          icon={TrendingUp}
          bgIcon="bg-emerald-950/30 text-emerald-500"
        />
        <XPICard 
          title="DESPESAS" 
          value="R$ 1,8 mi" 
          subtitle="Acumulado (30 dias)"
          icon={CreditCard}
          bgIcon="bg-rose-950/30 text-rose-500"
        />
        <XPICard 
          title="TICKET MÉDIO" 
          value="R$ 2,3 mil" 
          subtitle="Por Transação"
          icon={Users}
          bgIcon="bg-blue-950/30 text-blue-500"
        />
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Strategic Cash Flow Chart */}
        <Card className="lg:col-span-2 bg-[#0b1120] border-none shadow-2xl p-6">
          <div className="flex justify-between items-center mb-8">
            <div className="space-y-1">
              <h3 className="text-lg font-black text-white tracking-tight">Fluxo de Caixa Estratégico</h3>
              <p className="text-[10px] font-bold text-slate-500 uppercase tracking-widest">Projeção Inteligente</p>
            </div>
            <div className="flex gap-2">
               {['30', '60', '90'].map((p) => (
                 <button
                   key={p}
                   onClick={() => setPeriod(p)}
                   className={cn(
                     "px-4 py-1.5 rounded-lg text-[10px] font-black transition-all",
                     period === p ? "bg-emerald-500/20 text-emerald-500 border border-emerald-500/50" : "text-slate-500 hover:bg-slate-800"
                   )}
                 >
                   {p} Dias
                 </button>
               ))}
            </div>
          </div>
          <div className="h-[300px]">
             <ResponsiveContainer width="100%" height="100%">
               <AreaChart data={cashFlowData}>
                 <defs>
                   <linearGradient id="colorValor" x1="0" y1="0" x2="0" y2="1">
                     <stop offset="5%" stopColor="#10b981" stopOpacity={0.3}/>
                     <stop offset="95%" stopColor="#10b981" stopOpacity={0}/>
                   </linearGradient>
                 </defs>
                 <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#1e293b" opacity={0.5} />
                 <XAxis 
                   dataKey="name" 
                   axisLine={false} 
                   tickLine={false} 
                   tick={{fill: '#475569', fontSize: 10, fontWeight: 'bold'}} 
                   dy={10} 
                 />
                 <YAxis 
                   axisLine={false} 
                   tickLine={false} 
                   tick={{fill: '#475569', fontSize: 10}} 
                   tickFormatter={(val) => `-R$ ${Math.abs(val/1000)} mil`}
                 />
                 <Tooltip 
                   contentStyle={{ backgroundColor: '#0f172a', border: '1px solid #1e293b', borderRadius: '12px' }}
                   itemStyle={{ color: '#fff', fontSize: '12px' }}
                 />
                 <Area 
                   type="monotone" 
                   dataKey="valor" 
                   stroke="#10b981" 
                   strokeWidth={3}
                   fillOpacity={1} 
                   fill="url(#colorValor)" 
                   connectNulls 
                   strokeDasharray={(v) => v.projetado ? "5 5" : "0"}
                 />
               </AreaChart>
             </ResponsiveContainer>
          </div>
        </Card>

        {/* Expense Control */}
        <Card className="bg-[#0b1120] border-none shadow-2xl p-6">
          <div className="flex justify-between items-center mb-8">
            <div className="space-y-1">
              <h3 className="text-lg font-black text-white tracking-tight">Controle de Despesas</h3>
              <p className="text-[10px] font-bold text-slate-500 uppercase tracking-widest">Acompanhe seus limites mensais</p>
            </div>
            <Settings size={16} className="text-slate-500 cursor-pointer" />
          </div>
          <div className="space-y-8">
            <ProgressBarWidget label="Operacional" percentage={0} current="50.000,00" total="50.000,00" colorClass="text-emerald-500" />
            <ProgressBarWidget label="Marketing" percentage={0} current="12.000,00" total="12.000,00" colorClass="text-emerald-500" />
            <ProgressBarWidget label="Infraestrutura" percentage={223} current="11.155,38" total="5.000,00" colorClass="text-rose-500" />
            
            <div className="pt-6 border-t border-slate-800 flex justify-between items-center">
              <span className="text-xs font-bold text-slate-400">Total Utilizado</span>
              <span className="text-lg font-black text-white tracking-tighter">11.155,38</span>
            </div>
          </div>
        </Card>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Monthly Input/Output */}
        <Card className="bg-[#0b1120] border-none shadow-2xl p-6">
          <h3 className="text-sm font-black text-white mb-8 tracking-tighter uppercase">Entrada e Saída (Mensal)</h3>
          <div className="h-[300px]">
            <ResponsiveContainer width="100%" height="100%">
              <BarChart data={barData}>
                <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#1e293b" opacity={0.5} />
                <XAxis dataKey="name" axisLine={false} tickLine={false} tick={{fill: '#475569', fontSize: 11}} />
                <YAxis axisLine={false} tickLine={false} tick={{fill: '#475569', fontSize: 11}} />
                <Tooltip 
                   cursor={{fill: '#1e293b'}}
                   contentStyle={{ backgroundColor: '#0f172a', border: '1px solid #1e293b', borderRadius: '12px' }}
                />
                <Bar dataKey="entradas" fill="#10b981" radius={[4, 4, 0, 0]} barSize={20} />
                <Bar dataKey="saídas" fill="#f43f5e" radius={[4, 4, 0, 0]} barSize={20} />
              </BarChart>
            </ResponsiveContainer>
          </div>
        </Card>

        {/* Boletos Status */}
        <Card className="bg-[#0b1120] border-none shadow-2xl p-6">
          <h3 className="text-sm font-black text-white mb-8 tracking-tighter uppercase">Boletos por Status</h3>
          <div className="flex items-center gap-8 h-[300px]">
             <div className="flex-1 h-full">
                <ResponsiveContainer width="100%" height="100%">
                  <PieChart>
                    <Pie
                      data={pieData}
                      cx="50%"
                      cy="50%"
                      innerRadius={80}
                      outerRadius={100}
                      paddingAngle={5}
                      dataKey="value"
                    >
                      {pieData.map((entry, index) => (
                        <Cell key={`cell-${index}`} fill={entry.color} stroke="none" />
                      ))}
                    </Pie>
                  </PieChart>
                </ResponsiveContainer>
             </div>
             <div className="space-y-4">
                {pieData.map((item, index) => (
                  <div key={index} className="flex items-center gap-3">
                    <div className="w-2 h-2 rounded-full" style={{ backgroundColor: item.color }} />
                    <div className="flex flex-col">
                      <span className="text-[10px] font-bold text-slate-500 uppercase tracking-widest">{item.name}</span>
                      <span className="text-sm font-black text-white">{item.value}%</span>
                    </div>
                  </div>
                ))}
             </div>
          </div>
        </Card>
      </div>

      {/* Latest Transactions Table */}
      <Card className="bg-[#0b1120] border-none shadow-2xl overflow-hidden">
        <div className="p-6 border-b border-slate-800 flex justify-between items-center">
          <h3 className="text-sm font-black text-white tracking-widest uppercase">Últimas Movimentações</h3>
          <Button variant="outline" className="text-[10px] font-black uppercase bg-transparent border-slate-700 hover:bg-slate-800 text-white">Ver Todas</Button>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full text-left">
            <thead>
              <tr className="text-[10px] font-black text-slate-500 uppercase tracking-widest border-b border-slate-800/50">
                <th className="px-6 py-4">Entidade</th>
                <th className="px-6 py-4">Categoria</th>
                <th className="px-6 py-4">C. Custo</th>
                <th className="px-6 py-4">Valor</th>
                <th className="px-6 py-4">Status</th>
                <th className="px-6 py-4 text-right">Ações</th>
              </tr>
            </thead>
            <tbody className="text-xs">
              {[
                { entity: 'Stripe Brasil', category: 'INFRAESTRUTURA', cost: 'Marketing', value: '-R$ 2.413,92', status: 'Compensado' },
                { entity: 'Cora Bank', category: 'JUROS DE ANTECIPAÇÃO', cost: 'Marketing', value: 'R$ 1.685,22', status: 'Pendente' },
                { entity: 'Consigaz', category: 'SOFTWARE & LICENÇAS', cost: 'Operações', value: '-R$ 2.799,74', status: 'Compensado' },
                { entity: 'Posto Shell Logística', category: 'FOLHA DE PAGAMENTO', cost: 'Financeiro', value: '-R$ 6.339,59', status: 'Compensado' },
              ].map((row, i) => (
                <tr key={i} className="border-b border-slate-800/50 hover:bg-slate-800/30 transition-colors">
                  <td className="px-6 py-4 font-black text-white">{row.entity}</td>
                  <td className="px-6 py-4">
                    <span className="px-2 py-1 rounded bg-rose-500/10 text-rose-500 font-black text-[9px] uppercase tracking-tighter">
                      {row.category}
                    </span>
                  </td>
                  <td className="px-6 py-4 font-bold text-slate-400">{row.cost}</td>
                  <td className="px-6 py-4 font-black text-white tracking-tighter">{row.value}</td>
                  <td className="px-6 py-4 font-bold text-slate-200">{row.status}</td>
                  <td className="px-6 py-4 text-right">
                    <MoreHorizontal className="w-5 h-5 text-slate-600 ml-auto cursor-pointer hover:text-white" />
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </Card>
    </div>
  );
};

