
import React, { useState } from 'react';
import { Card } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { PieChart as PieChartIcon, Ban, AlertCircle, TrendingDown, TrendingUp, Minus, BarChart3, PieChart as PieIcon } from 'lucide-react';
import { PieChart, Pie, Cell, ResponsiveContainer, Tooltip, BarChart, Bar, XAxis, YAxis, CartesianGrid } from 'recharts';
import { cn } from '@/lib/utils';

/**
 * FinesCard (Componente de Multas)
 * 
 * Exibe o resumo de multas do mês atual comparado com o mês anterior.
 * Permite alternar entre visualização por Categoria (Pie) e Histórico Mensal (Bar).
 */
export const FinesCard = ({
  currentDate = 'Mês',
  currentValue = 0,
  currentCount = 0,
  previousValue = 0,
  previousCount = 0,
  data = [], // [{ name: 'Type', value: 100, color: '#f00' }]
  monthlyData = [], // [{ name: 'Jan', value: 500, count: 2 }]
  isLoading = false,
  onPeriodChange,
  className
}) => {
  const [activeView, setActiveView] = useState('category'); // 'category' | 'history'
  const [period, setPeriod] = useState('30d'); // '30d' | '60d' | '120d'

  const handlePeriodChange = (p) => {
      setPeriod(p);
      if (onPeriodChange) onPeriodChange(p);
  };

  // Formatters
  const formatCurrency = (val) => new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(val);
  const formatCompact = (val) => Intl.NumberFormat('pt-BR', { notation: "compact", maximumFractionDigits: 1 }).format(val);

  // Calculation for reduction/increase
  const hasPrevious = previousValue > 0;
  const diff = currentValue - previousValue;
  const percentage = hasPrevious ? (diff / previousValue) * 100 : 0;
  const isReduction = percentage < 0;
  const isIncrease = percentage > 0;
  
  const trendColor = isReduction ? 'text-emerald-500' : isIncrease ? 'text-rose-500' : 'text-slate-500';
  const badgeColor = isReduction ? 'bg-emerald-500/10 text-emerald-500 border-emerald-500/20' : isIncrease ? 'bg-rose-500/10 text-rose-500 border-rose-500/20' : 'bg-slate-500/10 text-slate-500 border-slate-500/20';
  const TrendIcon = isReduction ? TrendingDown : isIncrease ? TrendingUp : Minus;

  const isEmpty = !data || data.length === 0 || currentValue === 0;

  const CustomTooltip = ({ active, payload, label }) => {
    if (active && payload && payload.length) {
      const pData = payload[0];
      return (
        <div className="bg-white dark:bg-[#18181b] border border-slate-200 dark:border-white/10 p-3 rounded-lg shadow-xl min-w-[120px]">
           <p className="text-[10px] uppercase font-bold text-slate-500 mb-1 tracking-wider">{label || pData.name}</p>
           <div className="flex items-center gap-2">
              <div className="w-1.5 h-1.5 rounded-full" style={{ backgroundColor: pData.payload.color || '#3b82f6' }} />
              <span className="text-sm font-bold text-slate-900 dark:text-white font-mono">
                {formatCurrency(pData.value)}
              </span>
           </div>
        </div>
      );
    }
    return null;
  };

  return (
    <Card className={cn("flex flex-col h-full bg-white dark:bg-[#18181b] border-slate-200 dark:border-white/10 shadow-sm dark:shadow-xl overflow-hidden relative", className)}>
      
      {/* Header */}
      <div className="p-5 pb-2 shrink-0">
        <div className="flex justify-between items-start mb-4">
          <div className="flex items-center gap-3">
             <div className="w-10 h-10 rounded-full bg-amber-500/10 flex items-center justify-center">
                <PieChartIcon className="text-amber-600 dark:text-amber-500" size={20} />
             </div>
             <div>
                <h3 className="font-bold text-lg text-slate-900 dark:text-white leading-none">Multas</h3>
                <span className="text-[10px] text-slate-500 font-medium uppercase tracking-wider">Visão Geral</span>
             </div>
          </div>
          
          <div className="text-right">
             <div className={cn("text-2xl font-black tracking-tight leading-none", currentValue > 0 ? "text-slate-900 dark:text-white" : "text-emerald-600 dark:text-emerald-500")}>
                {formatCurrency(currentValue)}
             </div>
             <div className="text-xs text-slate-500 dark:text-slate-400 font-medium mt-1">{currentCount} registros</div>
          </div>
        </div>

        {/* Comparison Box */}
        <div className="bg-slate-50 dark:bg-white/5 rounded-xl p-3 flex items-center justify-between border border-slate-200 dark:border-white/5 mb-4 relative overflow-hidden">
           <div className="flex flex-col relative z-10">
              <span className="text-[10px] uppercase font-bold text-slate-500 tracking-wider">Mês Anterior</span>
              <div className="flex items-baseline gap-1.5 mt-0.5">
                  <span className="text-sm font-bold text-slate-700 dark:text-slate-200">{hasPrevious ? `R$ ${formatCompact(previousValue)}` : '-'}</span>
                  <span className="text-[10px] text-slate-400 dark:text-slate-500 italic">({previousCount} registros)</span>
              </div>
           </div>
           
           {hasPrevious && (
             <Badge variant="outline" className={cn("gap-1.5 pl-2 pr-3 py-1 relative z-10", badgeColor)}>
                <TrendIcon size={12} />
                {Math.abs(percentage).toFixed(1)}%
             </Badge>
           )}

           {/* Background gradient for decoration */}
           <div className="absolute right-0 top-0 bottom-0 w-32 bg-gradient-to-l from-white/50 dark:from-white/5 to-transparent pointer-events-none" />
        </div>

        {/* Filters & Toggles Row */}
        {!isEmpty && !isLoading && (
            <div className="flex items-center gap-2">
                {/* Time Period Selector */}
                <div className="flex-1 bg-slate-100 dark:bg-black/20 p-1 rounded-lg border border-slate-200 dark:border-white/5 flex">
                    {['30d', '60d', '120d'].map((p) => (
                        <button 
                            key={p}
                            onClick={() => handlePeriodChange(p)}
                            className={cn(
                                "flex-1 py-1.5 rounded-md text-[10px] uppercase font-bold tracking-wider transition-all",
                                period === p 
                                    ? "bg-white dark:bg-emerald-500 text-emerald-600 dark:text-white shadow-sm ring-1 ring-black/5 dark:ring-0" 
                                    : "text-slate-500 hover:text-slate-700 dark:hover:text-slate-300 hover:bg-black/5 dark:hover:bg-white/5"
                            )}
                        >
                            {p.replace('d', ' dias')}
                        </button>
                    ))}
                </div>

                {/* View Type Toggle (Icon Only) */}
                <div className="flex bg-slate-100 dark:bg-black/20 p-1 rounded-lg border border-slate-200 dark:border-white/5">
                    <button 
                        onClick={() => setActiveView('category')}
                        className={cn(
                            "p-1.5 rounded-md transition-all",
                            activeView === 'category' 
                                ? "bg-white dark:bg-white/10 text-amber-600 dark:text-amber-500 shadow-sm ring-1 ring-black/5 dark:ring-0" 
                                : "text-slate-400 dark:text-slate-500 hover:text-slate-600 dark:hover:text-slate-300"
                        )}
                        title="Agrupado"
                    >
                        <PieIcon size={14} />
                    </button>
                    <button 
                        onClick={() => setActiveView('history')}
                        className={cn(
                            "p-1.5 rounded-md transition-all",
                            activeView === 'history' 
                                ? "bg-white dark:bg-white/10 text-blue-600 dark:text-blue-500 shadow-sm ring-1 ring-black/5 dark:ring-0" 
                                : "text-slate-400 dark:text-slate-500 hover:text-slate-600 dark:hover:text-slate-300"
                        )}
                        title="Histórico"
                    >
                        <BarChart3 size={14} />
                    </button>
                </div>
            </div>
        )}
      </div>

      <div className="flex-1 min-h-[px] relative px-4 pb-4 pt-2 flex flex-col">
         {isLoading ? (
            <div className="flex-1 flex flex-col items-center justify-center gap-4 animate-pulse">
               <div className="w-24 h-24 rounded-full bg-slate-200 dark:bg-white/5" />
               <div className="h-4 w-32 bg-slate-200 dark:bg-white/5 rounded" />
            </div>
         ) : isEmpty ? (
            // Empty State
            <div className="flex-1 flex flex-col items-center justify-center text-center gap-4 py-8">
               <div className="w-16 h-16 rounded-full bg-slate-100 dark:bg-slate-800 flex items-center justify-center mb-2">
                  <PieChartIcon className="text-slate-300 dark:text-slate-600 opacity-50" size={32} />
               </div>
               <div>
                 <h4 className="font-bold text-slate-900 dark:text-white">Sem dados</h4>
                 <p className="text-[10px] text-slate-500 leading-relaxed max-w-[150px] mx-auto mt-1">
                   Nenhum registro encontrado para o período.
                 </p>
               </div>
            </div>
         ) : (
            // Charts Area
            <div className="flex-1 w-full h-full min-h-0 flex flex-col">
               {activeView === 'category' ? (
                  <>
                    <div className="flex-1 min-h-0">
                        <ResponsiveContainer width="100%" height="100%">
                            <PieChart>
                                <Pie
                                    data={data}
                                    cx="50%"
                                    cy="50%"
                                    innerRadius="60%"
                                    outerRadius="80%"
                                    paddingAngle={5}
                                    dataKey="value"
                                    stroke="none"
                                >
                                    {data.map((entry, index) => (
                                    <Cell key={`cell-${index}`} fill={entry.color} />
                                    ))}
                                </Pie>
                                <Tooltip content={<CustomTooltip />} />
                            </PieChart>
                        </ResponsiveContainer>
                    </div>
                    {/* Legend */}
                    <div className="mt-2 flex flex-wrap gap-x-4 gap-y-2 justify-center pb-2 shrink-0">
                        {data.map((item, i) => (
                            <div key={i} className="flex items-center gap-1.5">
                                <div className="w-2 h-2 rounded-full" style={{ backgroundColor: item.color }} />
                                <span className="text-[10px] text-slate-500 dark:text-slate-400 font-medium">{item.name}</span>
                            </div>
                        ))}
                    </div>
                  </>
               ) : (
                   <div className="flex-1 min-h-0 pt-2">
                        <ResponsiveContainer width="100%" height="100%">
                            <BarChart data={monthlyData} margin={{ top: 10, right: 10, left: -20, bottom: 0 }}>
                                <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="rgba(148, 163, 184, 0.1)" />
                                <XAxis 
                                    dataKey="name" 
                                    axisLine={false} 
                                    tickLine={false} 
                                    tick={{ fill: '#64748b', fontSize: 10 }} 
                                    dy={10}
                                />
                                <YAxis 
                                    axisLine={false} 
                                    tickLine={false} 
                                    tick={{ fill: '#64748b', fontSize: 10 }}
                                    tickFormatter={(val) => `R$${val/1000}k`}
                                />
                                <Tooltip content={<CustomTooltip />} cursor={{ fill: 'rgba(148, 163, 184, 0.1)' }} />
                                <Bar dataKey="value" radius={[4, 4, 0, 0]} maxBarSize={40}>
                                    {monthlyData.map((entry, index) => (
                                        <Cell 
                                            key={`cell-${index}`} 
                                            fill={entry.active ? '#3b82f6' : '#94a3b8'} // Blue active, Slate-400 others
                                            className="dark:fill-slate-700"
                                            style={{ fill: entry.active ? '#3b82f6' : undefined }} // Override inline for active
                                        />
                                    ))}
                                </Bar>
                            </BarChart>
                        </ResponsiveContainer>
                        <div className="text-center mt-2 pb-2">
                            <span className="text-[10px] text-slate-400 dark:text-slate-500 italic">Evolução últimos 6 meses</span>
                        </div>
                   </div>
               )}
            </div>
         )}
      </div>
    </Card>
  );
};

