import React, { useState, useMemo, useEffect } from 'react';
import { 
  TrendingUp, 
  TrendingDown, 
  Wallet, 
  Calendar,
  Download,
  Filter,
  ArrowUpRight,
  ArrowDownRight,
  MoreHorizontal,
  Flame,
  Scale,
  AlertTriangle,
  HandCoins,
  Search,
  ChevronDown,
  Loader2,
  CheckCircle2,
  AlertCircle,
  Receipt,
  Target,
  BarChart3,
  PieChart
} from 'lucide-react';
import { useFluxoCaixa } from '../hooks/useFluxoCaixa';
import ExcelTable from '../components/ExcelTable';
import { formatDate, formatCurrency } from '../utils/dateUtils';
import { cn } from '@/lib/utils';
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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { 
  Table, 
  TableBody, 
  TableCell, 
  TableHead, 
  TableHeader, 
  TableRow 
} from '@/components/ui/table';
import {
  BarChart,
  Bar,
  PieChart as RechartsPieChart,
  Pie,
  Cell,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer
} from 'recharts';
import { FinanceiroChartTooltip } from '../components/FinanceiroChartTooltip';
import CaixinhaDetailsModal from '../components/CaixinhaDetailsModal';
import { LayoutGrid } from 'lucide-react';

// Standardized Filter Header matching CruzamentoView pattern
const MESES = ['', 'Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'];
const ANOS = Array.from({ length: 11 }, (_, i) => new Date().getFullYear() - 5 + i);

const FinanceHeader = ({ filtroTipo, setFiltroTipo, filtroMes, setFiltroMes, filtroAno, setFiltroAno }) => {
  return (
    <div className="bg-white/80 dark:bg-slate-900/60 backdrop-blur-xl p-[clamp(0.75rem,1.2vw,1.25rem)] rounded-xl border border-slate-200 dark:border-slate-800/50 flex flex-col sm:flex-row flex-wrap gap-[clamp(0.75rem,1vw,1rem)] items-stretch sm:items-center shadow-xl relative z-10 mb-6">
      <div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-2 sm:gap-2 flex-1 min-w-0 flex-wrap">
        <div className="p-[clamp(0.5rem,0.6vw,0.625rem)] bg-slate-100 dark:bg-slate-900 rounded-lg border border-slate-200 dark:border-slate-800 shrink-0">
          <Filter className="w-[clamp(0.875rem,1vw,1rem)] h-[clamp(0.875rem,1vw,1rem)] text-cyan-600 dark:text-cyan-400" />
        </div>
        <Select value={filtroTipo} onValueChange={setFiltroTipo}>
          <SelectTrigger className="h-[clamp(2rem,2.2vw,2.25rem)] w-full sm:w-[110px] bg-slate-100 dark:bg-slate-900/50 border-slate-200 dark:border-slate-800 text-[clamp(0.75rem,0.8vw,0.8125rem)] font-semibold text-slate-900 dark:text-white">
            <SelectValue placeholder="Período" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="mes">Mês</SelectItem>
            <SelectItem value="ano">Ano</SelectItem>
            <SelectItem value="todos">Todos</SelectItem>
          </SelectContent>
        </Select>
        {filtroTipo === 'mes' && (
          <>
            <Select value={filtroMes} onValueChange={setFiltroMes}>
              <SelectTrigger className="h-[clamp(2rem,2.2vw,2.25rem)] w-full sm:w-[130px] bg-slate-100 dark:bg-slate-900/50 border-slate-200 dark:border-slate-800 text-[clamp(0.75rem,0.8vw,0.8125rem)] font-semibold text-slate-900 dark:text-white">
                <SelectValue placeholder="Mês" />
              </SelectTrigger>
              <SelectContent>
                {MESES.map((m, i) => (i === 0 ? null : <SelectItem key={i} value={String(i)}>{m}</SelectItem>))}
              </SelectContent>
            </Select>
            <Select value={filtroAno} onValueChange={setFiltroAno}>
              <SelectTrigger className="h-[clamp(2rem,2.2vw,2.25rem)] w-full sm:w-[100px] bg-slate-100 dark:bg-slate-900/50 border-slate-200 dark:border-slate-800 text-[clamp(0.75rem,0.8vw,0.8125rem)] font-semibold text-slate-900 dark:text-white">
                <SelectValue placeholder="Ano" />
              </SelectTrigger>
              <SelectContent>
                {ANOS.map((a) => <SelectItem key={a} value={String(a)}>{a}</SelectItem>)}
              </SelectContent>
            </Select>
          </>
        )}
        {filtroTipo === 'ano' && (
          <Select value={filtroAno} onValueChange={setFiltroAno}>
            <SelectTrigger className="h-[clamp(2rem,2.2vw,2.25rem)] w-full sm:w-[100px] bg-slate-100 dark:bg-slate-900/50 border-slate-200 dark:border-slate-800 text-[clamp(0.75rem,0.8vw,0.8125rem)] font-semibold text-slate-900 dark:text-white">
              <SelectValue placeholder="Ano" />
            </SelectTrigger>
            <SelectContent>
              {ANOS.map((a) => <SelectItem key={a} value={String(a)}>{a}</SelectItem>)}
            </SelectContent>
          </Select>
        )}
        <Badge variant="outline" className="h-[clamp(2rem,2.2vw,2.25rem)] px-[clamp(0.75rem,1vw,1rem)] rounded-lg bg-slate-100 dark:bg-slate-900/50 border-slate-200 dark:border-slate-800 text-slate-600 dark:text-slate-400 text-[clamp(0.75rem,0.8vw,0.8125rem)] whitespace-nowrap self-center font-medium">
          {filtroTipo === 'mes' && filtroMes ? `${MESES[Number(filtroMes)]} / ${filtroAno}` : filtroTipo === 'ano' ? filtroAno : 'Todos'}
        </Badge>
      </div>
    </div>
  );
};

// Theme-aware KPI Card - financeiro_V2 pattern
const KPICard = ({ title, value, subtext, icon: Icon, colorClass, isPositive }) => {
  return (
    <Card className="bg-white dark:bg-[#0f172a] border border-slate-200 dark:border-slate-800/50 shadow-xl hover:border-emerald-500/30 dark:hover:border-emerald-500/30 transition-all duration-300 rounded-xl overflow-hidden group">
      <CardContent className="p-5 relative">
        <div className="flex items-start justify-between">
          <div className="flex-1">
            <p className="text-[10px] font-bold text-slate-500 dark:text-slate-500 uppercase tracking-widest mb-2">{title}</p>
            <h3 className={cn(
              "text-2xl font-bold tracking-tight mb-1",
              colorClass
            )}>{value}</h3>
            <p className="text-xs text-slate-500 dark:text-slate-400 font-medium">{subtext}</p>
          </div>
          <div className={cn(
            "w-10 h-10 rounded-xl flex items-center justify-center transition-all duration-500 group-hover:shadow-[0_0_20px_rgba(16,185,129,0.2)]",
            isPositive ? "bg-emerald-500/10" : "bg-rose-500/10"
          )}>
            <Icon className={cn(
              "w-5 h-5",
              colorClass
            )} strokeWidth={2} />
          </div>
        </div>
      </CardContent>
    </Card>
  );
};

// Chart Section - Theme-aware Bar Chart
const ChartSection = ({ getChartData, tipoPeriodo }) => {
  const data = useMemo(() => getChartData(tipoPeriodo === 'ano' ? 'mensal' : 'diario'), [getChartData, tipoPeriodo]);

  return (
    <Card className="bg-white/80 dark:bg-[#0f172a] border border-slate-200 dark:border-slate-800/50 shadow-xl rounded-xl overflow-hidden">
      <CardHeader className="pb-4 border-b border-slate-200 dark:border-slate-700/50">
        <div className="flex items-center gap-3">
          <div className="p-2 bg-slate-100 dark:bg-slate-900 rounded-lg border border-slate-200 dark:border-slate-700">
            <BarChart3 className="w-4 h-4 text-cyan-600 dark:text-cyan-400" />
          </div>
          <div>
            <h3 className="text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-widest">
              Receitas vs Despesas ({tipoPeriodo === 'mes' ? 'Diário' : 'Mensal'})
            </h3>
          </div>
        </div>
      </CardHeader>
      <CardContent className="p-6">
        <div className="h-[300px] w-full">
          {data.length === 0 ? (
            <div className="flex items-center justify-center h-full text-slate-500 dark:text-slate-500 text-sm">
              Sem dados para o período
            </div>
          ) : (
            <ResponsiveContainer width="100%" height="100%">
              <BarChart data={data} margin={{ top: 10, right: 10, bottom: 20, left: 10 }}>
                <CartesianGrid strokeDasharray="3 3" stroke="#334155" opacity={0.3} />
                <XAxis 
                  dataKey="name" 
                  tick={{ fill: '#94a3b8', fontSize: 11 }}
                  axisLine={{ stroke: '#475569' }}
                  tickLine={false}
                />
                <YAxis 
                  tick={{ fill: '#94a3b8', fontSize: 11 }}
                  axisLine={{ stroke: '#475569' }}
                  tickLine={false}
                  tickFormatter={(val) => `R$ ${(val/1000).toFixed(0)}k`}
                />
                <Tooltip 
                  content={<FinanceiroChartTooltip formatCurrency={formatCurrency} />}
                  cursor={{ fill: 'rgba(148, 163, 184, 0.1)' }}
                />
                <Legend 
                  wrapperStyle={{ paddingTop: '20px' }}
                  iconType="rect"
                  formatter={(value) => <span className="text-xs text-slate-400 uppercase font-semibold">{value}</span>}
                />
                <Bar dataKey="receitas" fill="#22d3ee" name="RECEITAS" radius={[4, 4, 0, 0]} />
                <Bar dataKey="despesas" fill="#f87171" name="DESPESAS" radius={[4, 4, 0, 0]} />
              </BarChart>
            </ResponsiveContainer>
          )}
        </div>
      </CardContent>
    </Card>
  );
};

// Category Pie Chart Section - Using correct API data structure
const COLORS = ['#22d3ee', '#f87171', '#10b981', '#a78bfa', '#fb923c', '#f472b6', '#facc15', '#60a5fa'];

const CategorySection = ({ data = [] }) => {
  const chartData = useMemo(() => {
    if (!Array.isArray(data)) return [];
    
    return data.map((item, index) => ({
      name: item.categoria || 'Sem Categoria',
      value: Math.abs(Number(item.total) || (Number(item.total_entradas || 0) + Number(item.total_saidas || 0))),
      color: COLORS[index % COLORS.length]
    })).filter(item => item.value > 0);
  }, [data]);

  return (
    <Card className="bg-white/80 dark:bg-[#0f172a] border border-slate-200 dark:border-slate-800/50 shadow-xl rounded-xl overflow-hidden">
      <CardHeader className="pb-4 border-b border-slate-200 dark:border-slate-700/50">
        <div className="flex items-center gap-3">
          <div className="p-2 bg-slate-100 dark:bg-slate-900 rounded-lg border border-slate-200 dark:border-slate-700">
            <PieChart className="w-4 h-4 text-emerald-600 dark:text-emerald-400" />
          </div>
          <h3 className="text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-widest">Por Categoria</h3>
        </div>
      </CardHeader>
      <CardContent className="p-6">
        <div className="h-[300px] w-full">
          {chartData.length === 0 ? (
            <div className="flex items-center justify-center h-full text-slate-500 dark:text-slate-500 text-sm">
              Sem dados de categorias
            </div>
          ) : (
            <ResponsiveContainer width="100%" height="100%">
              <RechartsPieChart>
                <Pie
                  data={chartData}
                  cx="50%"
                  cy="50%"
                  innerRadius={60}
                  outerRadius={100}
                  paddingAngle={2}
                  dataKey="value"
                >
                  {chartData.map((entry, index) => (
                    <Cell key={`cell-${index}`} fill={entry.color} />
                  ))}
                </Pie>
                <Tooltip 
                  content={({ active, payload }) => {
                    if (active && payload && payload.length) {
                      return (
                        <div className="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-700 rounded-lg p-3 shadow-xl">
                          <p className="text-xs text-slate-500 dark:text-slate-400 mb-1">{payload[0].name}</p>
                          <p className="text-sm font-bold text-slate-900 dark:text-white">{formatCurrency(payload[0].value)}</p>
                        </div>
                      );
                    }
                    return null;
                  }}
                />
                <Legend 
                  verticalAlign="bottom"
                  height={36}
                  formatter={(value) => <span className="text-xs text-slate-500 dark:text-slate-400">{value}</span>}
                />
              </RechartsPieChart>
            </ResponsiveContainer>
          )}
        </div>
      </CardContent>
    </Card>
  );
};

// Caixinha Table Section - Using correct API data structure
const CaixinhaSection = ({ data = [], onSelectCaixinha }) => {
  const caixinhaData = useMemo(() => {
    if (!Array.isArray(data)) return [];
    
    return data.map(item => ({
      id: item.id,
      caixinha: item.caixinha || 'Padrão',
      receitas: Math.abs(Number(item.receitas || item.total_entradas) || 0),
      despesas: Math.abs(Number(item.despesas || item.total_saidas) || 0),
      saldo: Number(item.saldo || item.diferenca) || 0
    }));
  }, [data]);

  return (
    <Card className="bg-white/80 dark:bg-[#0f172a] border border-slate-200 dark:border-slate-800/50 shadow-xl rounded-xl overflow-hidden">
      <CardHeader className="pb-4 border-b border-slate-200 dark:border-slate-700/50">
        <div className="flex items-center gap-3">
          <div className="p-2 bg-slate-100 dark:bg-slate-900 rounded-lg border border-slate-200 dark:border-slate-700">
            <Target className="w-4 h-4 text-blue-600 dark:text-blue-400" />
          </div>
          <h3 className="text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-widest">Por Caixinha</h3>
        </div>
      </CardHeader>
      <CardContent className="p-0">
        <div className="overflow-x-auto">
          <Table>
            <TableHeader>
              <TableRow className="border-slate-200 dark:border-slate-700/50 hover:bg-transparent">
                <TableHead className="text-slate-500 dark:text-slate-400 font-bold text-xs uppercase">Caixinha</TableHead>
                <TableHead className="text-slate-500 dark:text-slate-400 font-bold text-xs uppercase text-right">Receitas</TableHead>
                <TableHead className="text-slate-500 dark:text-slate-400 font-bold text-xs uppercase text-right">Despesas</TableHead>
                <TableHead className="text-slate-500 dark:text-slate-400 font-bold text-xs uppercase text-right">Saldo</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {caixinhaData.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={4} className="text-center text-slate-500 dark:text-slate-500 text-sm py-8">
                    Sem dados de caixinhas
                  </TableCell>
                </TableRow>
              ) : (
                caixinhaData.map((item, index) => (
                  <TableRow 
                    key={index} 
                    className="border-slate-200 dark:border-slate-700/50 hover:bg-slate-50 dark:hover:bg-slate-800/20 cursor-pointer group"
                    onClick={() => onSelectCaixinha(item)}
                  >
                    <TableCell className="text-slate-900 dark:text-white text-sm font-medium">
                      <div className="flex items-center gap-2">
                        {item.caixinha}
                        <LayoutGrid className="w-3 h-3 text-slate-400 opacity-0 group-hover:opacity-100 transition-opacity" />
                      </div>
                    </TableCell>
                    <TableCell className="text-cyan-600 dark:text-cyan-400 text-sm font-mono text-right">{formatCurrency(item.receitas)}</TableCell>
                    <TableCell className="text-rose-600 dark:text-rose-400 text-sm font-mono text-right">{formatCurrency(item.despesas)}</TableCell>
                    <TableCell className={cn(
                      "text-sm font-mono font-bold text-right",
                      item.saldo >= 0 ? "text-emerald-600 dark:text-emerald-400" : "text-rose-600 dark:text-rose-400"
                    )}>{formatCurrency(item.saldo)}</TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </div>
      </CardContent>
    </Card>
  );
};

// Transactions Table Section - Using actual API data
const TransactionsSection = ({ data = [], loading = false }) => {
  const transactionData = useMemo(() => {
    if (!Array.isArray(data)) return [];
    
    return data.map(item => ({
      id: item.idextrato || item.id,
      categoria: item.categoria_nome || item.categoria || 'Sem Categoria',
      tipoOperacao: item.tipoOperacao,
      valor: item.valor,
      descricao: item.descricao || item.historico || '---',
      data: item.dataEntrada || item.data || item.data_entrada
    }));
  }, [data]);

  const columns = [
    { 
      field: 'data', 
      header: 'DATA',
      render: (row) => row.data ? formatDate(row.data).split(' ')[0] : '---'
    },
    { 
      field: 'descricao', 
      header: 'DESCRIÇÃO',
      render: (row) => (
        <span className="text-slate-900 dark:text-white font-medium truncate block max-w-md">
          {row.descricao || row.historico || '---'}
        </span>
      )
    },
    /* { 
      field: 'categoria', 
      header: 'CATEGORIA',
      render: (row) => (
        <Badge variant="outline" className="bg-slate-100 dark:bg-slate-700/50 border-slate-300 dark:border-slate-600 text-slate-700 dark:text-slate-300 text-xs">
          {row.categoria || 'Sem Categoria'}
        </Badge>
      )
    }, */
    { 
      field: 'tipo', 
      header: 'TIPO',
      render: (row) => (
        <Badge className={cn(
          "text-xs font-bold",
          row.tipoOperacao === 'C' 
            ? "bg-emerald-500/20 text-emerald-600 dark:text-emerald-400 border-emerald-500/30" 
            : "bg-rose-500/20 text-rose-600 dark:text-rose-400 border-rose-500/30"
        )}>
          {row.tipoOperacao === 'C' ? 'Receita' : 'Despesa'}
        </Badge>
      )
    },
    { 
      field: 'valor', 
      header: 'VALOR',
      render: (row) => (
        <span className={cn(
          "font-mono font-bold text-sm",
          row.tipoOperacao === 'C' ? "text-emerald-600 dark:text-emerald-400" : "text-rose-600 dark:text-rose-400"
        )}>
          {row.tipoOperacao === 'C' ? '+ ' : '- '}{formatCurrency(Math.abs(Number(row.valor) || 0))}
        </span>
      )
    }
  ];

  return (
    <Card className="bg-white/80 dark:bg-[#0f172a] border border-slate-200 dark:border-slate-800/50 shadow-xl rounded-xl overflow-hidden">
      <CardHeader className="pb-4 border-b border-slate-200 dark:border-slate-700/50">
        <div className="flex items-center gap-3">
          <div className="p-2 bg-slate-100 dark:bg-slate-900 rounded-lg border border-slate-200 dark:border-slate-700">
            <Flame className="w-4 h-4 text-amber-600 dark:text-amber-400" />
          </div>
          <h3 className="text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-widest">Movimentações do Período</h3>
        </div>
      </CardHeader>
      <CardContent className="p-0">
        <ExcelTable 
          data={transactionData}
          columns={columns}
          loading={loading}
          rowKey="id"
          pageSize={10}
        />
      </CardContent>
    </Card>
  );
};

export const FluxoCaixaView = () => {
  const {
    loading,
    error,
    extrato,
    receitas,
    receitasCard,
    despesas,
    ultimoSaldo,
    resultadoCruzamento,
    saldoDisponivel,
    bateComSaldo,
    getChartData,
    somaCategoria,
    porCaixinha,
    saldoConsolidado,
    filtroMes,
    setFiltroMes,
    filtroAno,
    setFiltroAno,
    filtroTipo,
    setFiltroTipo,
    reload
  } = useFluxoCaixa();

  const [tipoPeriodo, setTipoPeriodo] = useState('mensal');
  const [selectedCaixinha, setSelectedCaixinha] = useState(null);

  const handleSelectCaixinha = (caixinha) => {
    setSelectedCaixinha(caixinha);
  };

  if (error) {
    return (
      <div className="animate-in fade-in duration-700 max-w-[1600px] mx-auto pb-12 flex flex-col items-center justify-center min-h-[40vh] gap-4">
        <AlertCircle className="w-12 h-12 text-rose-500 dark:text-rose-400" />
        <h3 className="text-lg font-bold text-slate-900 dark:text-white">Erro ao carregar fluxo de caixa</h3>
        <p className="text-sm text-slate-500 dark:text-slate-400">{error}</p>
        <Button onClick={reload} variant="outline" className="rounded-xl">
          Tentar novamente
        </Button>
      </div>
    );
  }

  return (
    <div className="animate-in fade-in duration-700 max-w-[1600px] mx-auto pb-12 px-4 sm:px-6 lg:px-8">
      <FinanceHeader 
        filtroTipo={filtroTipo}
        setFiltroTipo={setFiltroTipo}
        filtroMes={filtroMes}
        setFiltroMes={setFiltroMes}
        filtroAno={filtroAno}
        setFiltroAno={setFiltroAno}
      />

      {/* KPI Row - 3 Main Cards */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
        {loading ? (
          <div className="col-span-full flex items-center justify-center py-12">
            <Loader2 className="w-8 h-8 text-cyan-600 dark:text-cyan-400 animate-spin" />
          </div>
        ) : (
          <>
            <KPICard 
              title="Receitas (Executado)" 
              value={formatCurrency(saldoConsolidado?.entradas_vs_saidas?.total_entradas || 0)} 
              subtext="Entradas do período + último saldo do mês anterior" 
              icon={ArrowUpRight} 
              colorClass="text-cyan-600 dark:text-cyan-400" 
              isPositive={true}
            />
            <KPICard 
              title="Despesas (Executado)" 
              value={formatCurrency(saldoConsolidado?.entradas_vs_saidas?.total_saidas || 0)} 
              subtext="Total de despesas do período (extrato D)" 
              icon={ArrowDownRight} 
              colorClass="text-rose-600 dark:text-rose-400" 
              isPositive={false}
            />
            <KPICard 
              title="Saldo Disponível" 
              value={formatCurrency(saldoConsolidado?.entradas_vs_saidas?.diferenca || 0)} 
              subtext="Saldo disponivel em conta" 
              icon={Wallet} 
              colorClass="text-emerald-600 dark:text-emerald-400" 
              isPositive={true}
            />
          </>
        )}
      </div>

      {/* Chart Section */}
      <div className="mb-6">
        <ChartSection getChartData={getChartData} tipoPeriodo={filtroTipo} />
      </div>

      {/* Category and Caixinha Sections - Side by Side */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4 mb-6">
        <CategorySection data={somaCategoria?.por_categoria || []} />
        <CaixinhaSection data={porCaixinha} onSelectCaixinha={handleSelectCaixinha} />
      </div>

      {/* Transactions Table */}
      <TransactionsSection data={extrato} loading={loading} />

      {/* Caixinha Details Modal */}
      <CaixinhaDetailsModal 
        isOpen={!!selectedCaixinha}
        onClose={() => setSelectedCaixinha(null)}
        caixinhaId={selectedCaixinha?.id}
        caixinhaName={selectedCaixinha?.caixinha}
        mes={filtroMes}
        ano={filtroAno}
      />
    </div>
  );
};

