import React from 'react';
import { Button } from '@/components/ui/button';
import { Upload, Bot, ArrowUp, ArrowDown, Scale } from 'lucide-react';
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card';
import { 
  BarChart, 
  Bar, 
  XAxis, 
  YAxis, 
  CartesianGrid, 
  Tooltip, 
  Legend, 
  ResponsiveContainer 
} from 'recharts';
import useConciliacao from '../../../hooks/useConciliacao';

export const ConciliacaoHeader = () => {
  const { runOptimizedReconciliation, importOFX } = useConciliacao();
  const handleFileUpload = async (e) => {
    const file = e.target.files[0];
    if (file) {
      await importOFX(file);
    }
  };
  return (
    <div className="flex flex-col md:flex-row justify-between items-center p-4 bg-white backdrop-blur-xl rounded-2xl border border-emerald-200 shadow-lg shadow-emerald-100/50 gap-4">
      <div className="flex gap-4 items-center px-2">
        <div className="w-2.5 h-2.5 rounded-full bg-emerald-500 animate-pulse shadow-[0_0_12px_rgba(16,185,129,0.5)]" />
        <div className="flex flex-col">
            <span className="text-[10px] font-black text-slate-600 uppercase tracking-[0.2em] leading-none">Status do Gateway</span>
            <span className="text-xs font-bold text-slate-900 uppercase tracking-wider">Conectado & Sincronizado</span>
        </div>
      </div>
      <div className="flex gap-3 items-center">
        <input type="file" id="ofx-upload" accept=".ofx" className="hidden" onChange={handleFileUpload} />
        <Button variant="outline" className="gap-2 rounded-xl text-[10px] font-black uppercase tracking-widest px-6 h-10 border-emerald-300 bg-white hover:bg-emerald-50 text-slate-700 hover:text-emerald-700 transition-all shadow-sm" onClick={() => document.getElementById('ofx-upload').click()}>
          <Upload className="w-3.5 h-3.5" /> Importar OFX
        </Button>
        <Button className="gap-3 bg-emerald-600 hover:bg-emerald-700 text-white rounded-xl text-[10px] font-black uppercase tracking-widest px-8 h-10 shadow-lg shadow-emerald-500/20 transition-all active:scale-95" onClick={runOptimizedReconciliation}>
          <Bot className="w-4 h-4" /> IA Conciliadora
        </Button>
      </div>
    </div>
  );
};

export const ConciliacaoMetrics = () => {
  const { getScopedData } = useConciliacao();
  const scopedTransactions = getScopedData();
  
  const entradas = scopedTransactions.filter(t => t.amount > 0).reduce((acc, t) => acc + t.amount, 0);
  const saidas = scopedTransactions.filter(t => t.amount < 0).reduce((acc, t) => acc + t.amount, 0);
  const saldo = entradas + saidas;
  const formatCurrency = (v) => new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(v);
  
  const MetricItem = ({ label, value, icon: Icon, colorClass, bgClass }) => (
    <div className="flex flex-1 items-center gap-5 p-5 rounded-2xl transition-all hover:bg-emerald-50/50 group border border-transparent">
      <div className={`p-4 rounded-2xl ${bgClass} ${colorClass} shadow-lg transition-transform group-hover:scale-110 duration-500 border border-current border-opacity-10`}>
        <Icon className="w-5 h-5" />
      </div>
      <div className="text-left">
        <label className="text-[10px] font-black uppercase tracking-[0.2em] text-slate-600 block mb-1.5">{label}</label>
        <h3 className={`text-2xl font-mono font-black leading-none tracking-tighter ${colorClass}`}>{formatCurrency(value)}</h3>
      </div>
    </div>
  );

  return (
    <div className="bg-white backdrop-blur-xl rounded-2xl border border-emerald-200 p-2 shadow-lg shadow-emerald-100/50 relative overflow-hidden group">
      {/* Decorative Glow */}
      <div className="absolute top-0 right-0 w-32 h-32 bg-emerald-500/5 rounded-full blur-3xl pointer-events-none" />
      
      <div className="flex flex-wrap md:flex-nowrap items-center justify-between gap-4 relative z-10">
        <MetricItem label="Entradas" value={entradas} icon={ArrowUp} colorClass="text-emerald-600" bgClass="bg-emerald-50" />
        <div className="hidden md:block w-px h-12 bg-emerald-200 mx-2" />
        <MetricItem label="Saídas" value={saidas} icon={ArrowDown} colorClass="text-rose-600" bgClass="bg-rose-50" />
        <div className="hidden md:block w-px h-12 bg-emerald-200 mx-2" />
        <MetricItem label="Patrimônio" value={saldo} icon={Scale} colorClass="text-emerald-700" bgClass="bg-emerald-50" />
      </div>
    </div>
  );
};

export const ConciliacaoCharts = () => {
  const { getScopedData } = useConciliacao();
  const scopedTransactions = getScopedData();

  // Simple aggregation by month for the chart
  const months = ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez'];
  const chartData = months.map((month, idx) => {
    const monthTransactions = scopedTransactions.filter(t => t.date.getMonth() === idx);
    return {
      name: month,
      entrada: monthTransactions.filter(t => t.amount > 0).reduce((acc, t) => acc + t.amount, 0),
      saida: Math.abs(monthTransactions.filter(t => t.amount < 0).reduce((acc, t) => acc + t.amount, 0))
    };
  });

  return (
    <Card className="shadow-lg shadow-emerald-100/50 border border-emerald-200 bg-white overflow-hidden">
      <CardHeader className="border-b border-emerald-200 bg-emerald-50/30">
        <CardTitle className="text-xs font-black text-slate-700 uppercase tracking-widest flex items-center gap-2">
            <div className="w-1.5 h-4 bg-emerald-500 rounded-full" />
            Fluxo Histórico: Previsto vs Realizado
        </CardTitle>
      </CardHeader>
      <CardContent className="h-[320px] w-full pt-8 p-4" style={{ minHeight: '320px' }}>
        <ResponsiveContainer width="100%" height="100%">
          <BarChart data={chartData}>
            <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#d1d5db" opacity={0.5} />
            <XAxis dataKey="name" axisLine={false} tickLine={false} tick={{ fill: '#64748b', fontSize: 10, fontWeight: 'bold' }} />
            <YAxis axisLine={false} tickLine={false} tick={{ fill: '#64748b', fontSize: 10 }} tickFormatter={(v) => `R$ ${v}`} />
            <Tooltip 
                cursor={{ fill: 'rgba(16,185,129,0.05)' }} 
                contentStyle={{ borderRadius: '12px', border: '1px solid rgba(209, 213, 219, 0.5)', backgroundColor: '#ffffff', color: '#1e293b', boxShadow: '0 4px 6px -1px rgba(0, 0, 0, 0.1)' }} 
                itemStyle={{ fontSize: '12px' }}
            />
            <Legend verticalAlign="bottom" height={36} iconType="circle" wrapperStyle={{ fontSize: '10px', fontWeight: 'bold', textTransform: 'uppercase', paddingTop: '20px' }} />
            <Bar dataKey="entrada" name="Entrada" fill="#10b981" radius={[4, 4, 0, 0]} barSize={32} />
            <Bar dataKey="saida" name="Saída" fill="#ef4444" radius={[4, 4, 0, 0]} barSize={32} />
          </BarChart>
        </ResponsiveContainer>
      </CardContent>
    </Card>
  );
};
