import React from 'react';
import { 
  ArrowUp, 
  ArrowDown, 
  List, 
  PieChart, 
  Filter, 
  Calendar as CalendarIcon, 
  Search,
  Plus,
  Trash2,
  Edit,
  FileText,
  AlertCircle,
  CheckCircle2,
  MoreHorizontal
} from 'lucide-react';
import { 
  Card, 
  CardContent, 
  CardHeader, 
  CardTitle 
} 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 {
  PieChart as RePieChart,
  Pie,
  Cell,
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  Legend
} from 'recharts';
import { useContasPagar } from '../hooks/useContasPagar';
import { cn } from '@/lib/utils';

/**
 * KPI Card with Premium Light Look
 */
const KPICard = ({ title, value, subtext, trend, colorClass, icon: Icon }) => (
    <Card className="bg-white border-slate-200 shadow-sm relative overflow-hidden group hover:border-emerald-500/50 transition-all duration-300">
        <CardContent className="p-6">
            <div className="flex justify-between items-start">
                <div>
                    <p className="text-[10px] uppercase font-black text-slate-400 tracking-widest mb-1">{title}</p>
                    <h3 className={cn("text-2xl font-black tracking-tighter text-slate-900", colorClass)}>{value}</h3>
                    <div className="flex items-center mt-2 gap-1.5">
                        <span className={cn(
                            "text-[10px] px-2 py-0.5 rounded-full font-bold",
                            trend === 'up' ? 'bg-rose-50 text-rose-600' : 'bg-emerald-50 text-emerald-600'
                        )}>
                            {trend === 'up' ? '↑' : '↓'} 2.4%
                        </span>
                        <span className="text-[10px] text-slate-400 font-bold uppercase tracking-wider">{subtext}</span>
                    </div>
                </div>
                <div className="bg-slate-50 p-3 rounded-2xl border border-slate-100 group-hover:scale-110 group-hover:bg-white group-hover:shadow-md transition-all duration-300">
                    <Icon className={cn("w-5 h-5", colorClass)} strokeWidth={2.5} />
                </div>
            </div>
        </CardContent>
    </Card>
);

const RegistrosView = ({ state, actions }) => {
    const { transactions = [], selectedIds = [] } = state;

    const formatDate = (dateString) => {
        try {
            if (!dateString) return "N/D";
            const date = new Date(dateString);
            return isNaN(date.getTime()) ? "Data Inválida" : date.toLocaleDateString('pt-BR');
        } catch (e) {
            return "Erro Data";
        }
    };

    return (
        <Card className="bg-white border-slate-200 shadow-xl mt-6 overflow-hidden rounded-3xl">
             <CardHeader className="py-6 px-8 border-b border-slate-50 flex flex-col md:flex-row md:items-center justify-between gap-6 bg-slate-50/30">
                <div className="flex items-center gap-4">
                    <div className="w-10 h-10 rounded-2xl bg-rose-500/10 flex items-center justify-center border border-rose-500/10 shadow-sm">
                        <List className="w-5 h-5 text-rose-600" />
                    </div>
                    <div>
                        <h3 className="font-black text-slate-900 text-lg flex items-center gap-2 tracking-tight">
                            Contas a Pagar
                        </h3>
                        <p className="text-[10px] font-black text-slate-400 uppercase tracking-widest flex items-center gap-1.5 mt-0.5">
                             Monitoramento de saídas <span className="w-1 h-1 bg-slate-300 rounded-full" /> {(state?.totalCount || 0)} REGISTROS
                        </p>
                    </div>
                </div>
                
                <div className="flex flex-wrap items-center gap-3">
                    <div className="relative group">
                        <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400 group-focus-within:text-rose-500 transition-colors" />
                        <Input 
                            value={state?.searchTerm || ""}
                            onChange={(e) => actions?.setSearchTerm(e.target.value)}
                            placeholder="Buscar fornecedor..." 
                            className="h-10 w-64 pl-10 bg-white border-slate-200 text-slate-900 text-xs font-medium focus:ring-rose-500/10 focus:border-rose-500/50 transition-all rounded-xl shadow-sm"
                        />
                    </div>
                    <Button size="sm" className="bg-rose-600 hover:bg-rose-700 text-white font-black text-[10px] uppercase tracking-widest shadow-lg shadow-rose-600/20 px-6 h-10 rounded-xl active:scale-95 transition-all">
                        <Plus className="w-4 h-4 mr-2" strokeWidth={3} /> Nova Conta
                    </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="border-none hover:bg-transparent">
                                <TableHead className="w-12 px-8">
                                    <input 
                                        type="checkbox" 
                                        className="rounded-md border-slate-300 bg-white text-rose-600 focus:ring-rose-500/20" 
                                        checked={transactions.length > 0 && selectedIds.length === transactions.length}
                                        onChange={actions?.toggleSelectAll}
                                    />
                                </TableHead>
                                <TableHead className="text-slate-400 font-black text-[9px] uppercase tracking-widest h-12">Vencimento</TableHead>
                                <TableHead className="text-slate-400 font-black text-[9px] uppercase tracking-widest h-12">Favorecido / Descrição</TableHead>
                                <TableHead className="text-slate-400 font-black text-[9px] uppercase tracking-widest h-12">Categoria</TableHead>
                                <TableHead className="text-slate-400 font-black text-[9px] uppercase tracking-widest h-12 text-right">Valor</TableHead>
                                <TableHead className="text-slate-400 font-black text-[9px] uppercase tracking-widest h-12 text-center">Status</TableHead>
                                <TableHead className="text-slate-400 font-black text-[9px] uppercase tracking-widest h-12 text-right pr-8">Ações</TableHead>
                            </TableRow>
                        </TableHeader>
                        <TableBody>
                            {transactions.length === 0 ? (
                                <TableRow>
                                    <TableCell colSpan={7} className="h-60 text-center text-slate-400 text-sm font-bold bg-slate-50/20">
                                        <div className="flex flex-col items-center gap-4">
                                            <div className="w-12 h-12 rounded-full bg-slate-100 flex items-center justify-center">
                                                <List className="w-6 h-6 text-slate-300" />
                                            </div>
                                            Nenhuma conta encontrada para o filtro atual.
                                        </div>
                                    </TableCell>
                                </TableRow>
                            ) : transactions.map((item) => (
                                <TableRow key={item.id} className={cn(
                                    "border-b border-slate-50 hover:bg-slate-50/50 transition-all duration-300 group",
                                    selectedIds.includes(item.id) ? 'bg-rose-50/30' : ''
                                )}>
                                    <TableCell className="px-8 py-5">
                                        <input 
                                            type="checkbox" 
                                            className="rounded-md border-slate-300 bg-white text-rose-600 focus:ring-rose-500/20"
                                            checked={selectedIds.includes(item.id)}
                                            onChange={() => actions?.toggleSelect(item.id)}
                                        />
                                    </TableCell>
                                    <TableCell className="py-5 font-bold text-xs">
                                        <div className="flex flex-col">
                                            <span className="text-slate-900 font-black">{formatDate(item.dataVencimento)}</span>
                                            {item.status === 'ATRASADO' && <span className="text-[8px] text-rose-600 font-black tracking-tighter animate-pulse mt-1">VENCIDO AGORA</span>}
                                        </div>
                                    </TableCell>
                                    <TableCell className="py-5">
                                        <div className="flex items-center gap-3">
                                            <div className="flex flex-col">
                                                <span className="text-sm font-black text-slate-800 group-hover:text-rose-600 transition-colors">{item.favorecido}</span>
                                                <span className="text-[10px] text-slate-400 font-medium flex items-center gap-1 mt-0.5">
                                                    {item.descricao}
                                                    {item.hasAttachment && <FileText className="w-3 h-3 text-blue-500" title="Ver Anexo" />}
                                                </span>
                                            </div>
                                        </div>
                                    </TableCell>
                                    <TableCell className="py-5">
                                        <span className="bg-slate-100 border border-slate-200 text-slate-600 text-[9px] uppercase font-black px-2.5 py-1 rounded-lg tracking-tight">
                                            {item.categoria}
                                        </span>
                                    </TableCell>
                                    <TableCell className="font-black text-xs text-slate-900 text-right py-5">
                                        {new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(item.valor || 0)}
                                    </TableCell>
                                    <TableCell className="py-5 text-center">
                                        <Badge className={cn(
                                            "text-[9px] font-black tracking-widest uppercase px-3 py-1 rounded-full shadow-none border",
                                            item.status === 'PAGO' ? 'bg-emerald-50 text-emerald-600 border-emerald-100' : 
                                            item.status === 'ATRASADO' ? 'bg-rose-100 text-rose-700 border-rose-200' : 
                                            'bg-amber-50 text-amber-600 border-amber-100'
                                        )}>
                                            {item.status}
                                        </Badge>
                                    </TableCell>
                                    <TableCell className="py-5 text-right pr-8">
                                        <div className="flex justify-end gap-2 opacity-0 group-hover:opacity-100 transition-all transform translate-x-2 group-hover:translate-x-0">
                                            {item.status !== 'PAGO' && (
                                                <Button variant="ghost" size="icon" onClick={() => actions?.markAsPaid(item.id)} className="h-8 w-8 rounded-xl bg-emerald-50 text-emerald-600 hover:bg-emerald-600 hover:text-white transition-all shadow-sm">
                                                    <CheckCircle2 className="w-4 h-4" />
                                                </Button>
                                            )}
                                            <Button variant="ghost" size="icon" className="h-8 w-8 rounded-xl bg-slate-100 text-slate-500 hover:bg-rose-500 hover:text-white transition-all shadow-sm">
                                                <Edit className="w-4 h-4" />
                                            </Button>
                                            <Button variant="ghost" size="icon" onClick={() => actions?.deleteTransaction(item.id)} className="h-8 w-8 rounded-xl bg-slate-100 text-slate-500 hover:bg-rose-600 hover:text-white transition-all shadow-sm">
                                                <Trash2 className="w-4 h-4" />
                                            </Button>
                                        </div>
                                    </TableCell>
                                </TableRow>
                            ))}
                        </TableBody>
                    </Table>
                </div>
            </CardContent>
        </Card>
    );
};

const CruzamentoView = ({ state }) => {
    const { transactions = [], kpis = {} } = state;

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

    const timelineData = React.useMemo(() => {
        if (!Array.isArray(transactions)) return [];
        const map = {};
        transactions.forEach(item => {
            if (item?.dataVencimento && typeof item.dataVencimento === 'string') {
                const date = item.dataVencimento.substring(5); // 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 }));
    }, [transactions]);

    const COLORS = ['#ef4444', '#f97316', '#f59e0b', '#8b5cf6', '#64748b'];

    const formatCurrency = (val) => new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(val || 0);

    return (
        <div className="space-y-8 animate-in fade-in slide-in-from-bottom-8 duration-700">
            {/* Filter Bar */}
            <div className="bg-white p-6 rounded-3xl border border-slate-100 flex flex-wrap gap-8 items-center shadow-lg shadow-slate-200/50">
                <div className="flex items-center gap-4">
                    <div className="w-10 h-10 rounded-2xl bg-slate-50 flex items-center justify-center text-slate-400">
                        <Filter className="w-5 h-5" />
                    </div>
                    <div>
                        <span className="text-[10px] font-black text-slate-400 uppercase tracking-widest block mb-1">
                            Filtrar Período
                        </span>
                        <div className="flex items-center gap-3 bg-slate-50 px-4 py-2 rounded-xl border border-slate-100 group focus-within:border-emerald-500/30 transition-all">
                            <Input type="date" className="h-6 w-32 bg-transparent border-none text-xs text-slate-900 font-bold focus-visible:ring-0 p-0" />
                            <span className="text-slate-300 font-black text-[9px] uppercase tracking-tighter">ATÉ</span>
                            <Input type="date" className="h-6 w-32 bg-transparent border-none text-xs text-slate-900 font-bold focus-visible:ring-0 p-0" />
                        </div>
                    </div>
                </div>
            </div>

            {/* KPIs */}
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
                <KPICard 
                    title="Total Pago"
                    value={formatCurrency(kpis?.totalPago)}
                    subtext="Realizado no mês"
                    trend="down"
                    colorClass="text-emerald-600"
                    icon={CheckCircle2}
                />
                <KPICard 
                    title="Atrasado"
                    value={formatCurrency(kpis?.totalAtrasado)}
                    subtext="Urgente / Crítico"
                    trend="up"
                    colorClass="text-rose-600"
                    icon={AlertCircle}
                />
                <KPICard 
                    title="A Pagar"
                    value={formatCurrency(kpis?.totalPendente)}
                    subtext="Compromissos ativos"
                    trend="down"
                    colorClass="text-amber-600"
                    icon={CalendarIcon}
                />
                <KPICard 
                    title="Total Geral"
                    value={formatCurrency(kpis?.totalGeral)}
                    subtext="Montante projetado"
                    trend="up"
                    colorClass="text-emerald-500"
                    icon={PieChart}
                />
            </div>

            {/* Charts Grid */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
                <Card className="bg-white border-slate-100 overflow-hidden shadow-lg shadow-slate-200/40 rounded-3xl">
                    <CardHeader className="pb-4 border-b border-slate-50 bg-slate-50/30 px-8">
                        <CardTitle className="text-[10px] font-black text-slate-400 uppercase flex items-center gap-3 tracking-[0.2em]">
                            <div className="p-2 rounded-lg bg-rose-50">
                                <PieChart className="w-4 h-4 text-rose-600" />
                            </div>
                            Distribuição por Categoria
                        </CardTitle>
                    </CardHeader>
                    <CardContent className="h-[360px] pt-8 px-8 relative">
                        <ResponsiveContainer width="100%" height="100%" minHeight={300}>
                            <RePieChart>
                                <Pie
                                    data={categoryData}
                                    cx="50%"
                                    cy="50%"
                                    innerRadius={80}
                                    outerRadius={105}
                                    paddingAngle={10}
                                    dataKey="value"
                                    stroke="none"
                                >
                                    {categoryData.map((entry, index) => (
                                        <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                                    ))}
                                </Pie>
                                <Tooltip 
                                    contentStyle={{ backgroundColor: '#ffffff', border: '1px solid #f1f5f9', borderRadius: '16px', boxShadow: '0 10px 15px -3px rgba(0,0,0,0.1)', color: '#0f172a' }}
                                    itemStyle={{ fontSize: '12px', fontWeight: 'bold' }}
                                    formatter={(value) => formatCurrency(value)}
                                />
                                <Legend verticalAlign="bottom" height={40} iconType="circle" wrapperStyle={{ fontSize: '10px', textTransform: 'uppercase', fontWeight: 'black', letterSpacing: '0.1em', paddingTop: '20px' }} />
                            </RePieChart>
                        </ResponsiveContainer>
                    </CardContent>
                </Card>

                <Card className="bg-white border-slate-100 overflow-hidden shadow-lg shadow-slate-200/40 rounded-3xl">
                    <CardHeader className="pb-4 border-b border-slate-50 bg-slate-50/30 px-8">
                        <CardTitle className="text-[10px] font-black text-slate-400 uppercase flex items-center gap-3 tracking-[0.2em]">
                            <div className="p-2 rounded-lg bg-emerald-50">
                                <ArrowUp className="w-4 h-4 text-emerald-600" />
                            </div>
                            Histórico de Saídas
                        </CardTitle>
                    </CardHeader>
                    <CardContent className="h-[360px] pt-8 px-8 relative">
                        <ResponsiveContainer width="100%" height="100%" minHeight={300}>
                            <LineChart data={timelineData}>
                                <defs>
                                    <linearGradient id="colorVal" x1="0" y1="0" x2="0" y2="1">
                                        <stop offset="5%" stopColor="#ef4444" stopOpacity={0.1}/>
                                        <stop offset="95%" stopColor="#ef4444" 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', borderRadius: '16px', boxShadow: '0 10px 15px -3px rgba(0,0,0,0.1)', color: '#0f172a' }}
                                    formatter={(value) => formatCurrency(value)}
                                />
                                <Line type="monotone" dataKey="value" stroke="#ef4444" strokeWidth={5} dot={false} activeDot={{r: 6, fill: '#ef4444', stroke: '#fff', strokeWidth: 3}} />
                            </LineChart>
                        </ResponsiveContainer>
                    </CardContent>
                </Card>
            </div>
        </div>
    );
};

export const ContasPagarView = () => {
    const { state, actions } = useContasPagar();
    const activeTab = state?.activeTab || 'registros';

    return (
        <div className="animate-in fade-in duration-700 space-y-8 max-w-[1600px] mx-auto pb-12">
            {/* Header / Sub-Navigation */}
            <div className="flex flex-col lg:flex-row lg:items-center justify-between gap-8 border-b border-slate-100 pb-8">
                <div className="flex items-center gap-6">
                   <div className="w-16 h-16 bg-white rounded-3xl flex items-center justify-center border border-slate-100 shadow-xl shadow-slate-200/30">
                        <List className="w-8 h-8 text-rose-600" strokeWidth={2.5} />
                   </div>
                   <div>
                       <div className="flex items-center gap-3">
                            <h1 className="text-4xl font-black text-slate-900 tracking-tighter">
                                Contas a Pagar
                            </h1>
                            <Badge className="bg-rose-500 text-white border-none text-[8px] font-black px-2 tracking-widest mt-1">PREMIUM v2</Badge>
                       </div>
                       <p className="text-sm text-slate-400 font-bold mt-1 max-w-md">Gestão estratégica de fluxos de saída, fornecedores e obrigações financeiras.</p>
                   </div>
                </div>

                <div className="flex bg-slate-100/50 p-1.5 rounded-2xl border border-slate-200/50 shadow-inner">
                    <Button 
                        variant="ghost" 
                        onClick={() => actions?.setActiveTab('registros')}
                        className={cn(
                            "rounded-xl px-8 h-12 font-black text-[10px] uppercase tracking-widest transition-all duration-500",
                            activeTab === 'registros' 
                                ? 'bg-white text-slate-900 shadow-xl shadow-slate-200/50 ring-1 ring-slate-200' 
                                : 'text-slate-400 hover:text-slate-600 hover:bg-white/50'
                        )}
                    >
                        <List className="w-4 h-4 mr-2" /> Registros
                    </Button>
                    <Button 
                        variant="ghost" 
                        onClick={() => actions?.setActiveTab('cruzamento')}
                        className={cn(
                            "rounded-xl px-8 h-12 font-black text-[10px] uppercase tracking-widest transition-all duration-500",
                            activeTab === 'cruzamento' 
                                ? 'bg-white text-slate-900 shadow-xl shadow-slate-200/50 ring-1 ring-slate-200' 
                                : 'text-slate-400 hover:text-slate-600 hover:bg-white/50'
                        )}
                    >
                        <PieChart className="w-4 h-4 mr-2" /> Inteligência/Cruzamento
                    </Button>
                </div>
            </div>

            <div className="min-h-[600px]">
                {activeTab === 'registros' ? (
                    <RegistrosView state={state} actions={actions} />
                ) : (
                    <CruzamentoView state={state} />
                )}
            </div>
        </div>
    );
};

