import React, { useEffect } from 'react';
import { useFleetDashboard } from '../hooks/useFleetDashboard';
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card';
import { 
  Truck, Activity, AlertTriangle, CheckCircle, Database, BarChart3, PieChart as PieChartIcon, MapPin
} from 'lucide-react';
import { 
  BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer, 
  PieChart, Pie, Cell 
} from 'recharts';

const COLORS = ['#10b981', '#3b82f6', '#f59e0b', '#ef4444', '#8b5cf6', '#ec4899', '#6366f1'];
const EMERALD_Theme = ['#059669', '#34d399', '#6ee7b7', '#a7f3d0', '#d1fae5'];

export const FleetDashboardView = () => {
  const { metrics, loading, fetchAllMetrics } = useFleetDashboard();

  useEffect(() => {
    fetchAllMetrics();
  }, [fetchAllMetrics]);

  // Helper para formatar dados para charts se necessário
  // Assumindo que a API retorna [{ name: '...', value: ... }] ou similar. 
  // Se retornar objeto { 'Base A': 10 }, precisaremos converter.
  // Pela nomenclatura dos endpoints, vamos assumir que vem array ou objeto chave-valor.
  // Vamos fazer uma função segura.
  const formatData = (data, keyName = 'name', valueName = 'value') => {
    if (!data) return [];
    if (Array.isArray(data)) return data; 
    // Se for objeto: { 'Ativo': 10, 'Inativo': 5 } -> [{ name: 'Ativo', value: 10 }, ...]
    return Object.entries(data).map(([key, value]) => ({ [keyName]: key, [valueName]: value }));
  };

  const statusData = formatData(metrics.placasPorStatus);
  const baseData = formatData(metrics.placasPorBase);
  const disponibilidadeData = formatData(metrics.disponibilidade);
  const manutencaoData = formatData(metrics.manutencaoPorStatus);
  const sinistroData = formatData(metrics.sinistrosPorStatus);
  const categoriaData = formatData(metrics.placasPorCategoria);

  // Custom Tooltip
  const CustomTooltip = ({ active, payload, label }) => {
    if (active && payload && payload.length) {
      return (
        <div className="bg-white p-3 border border-slate-100 shadow-lg rounded-lg">
          <p className="text-xs font-bold text-slate-700 mb-1">{label}</p>
          <p className="text-sm font-bold text-emerald-600">
            {payload[0].value} <span className="text-[10px] text-slate-400 font-normal">veículos</span>
          </p>
        </div>
      );
    }
    return null;
  };

  return (
    <div className="space-y-6 pb-20 fade-in">
      <div className="flex flex-col space-y-1">
         <h2 className="text-3xl font-black tracking-tight text-slate-900">Dashboard Frota</h2>
         <p className="text-slate-500 font-medium">Visão geral da operação e indicadores chave.</p>
      </div>

      {/* Summary Cards */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
         <Card className="bg-white border-slate-200 shadow-sm hover:shadow transition-shadow">
            <CardContent className="p-6 flex items-center gap-4">
               <div className="p-3 bg-emerald-100 text-emerald-600 rounded-lg">
                 <Truck size={24} />
               </div>
               <div>
                 <p className="text-2xl font-bold text-slate-900">
                    {loading ? '...' : (metrics.totalPlacas?.total || metrics.totalPlacas || 0)}
                 </p>
                 <p className="text-xs font-bold text-slate-500 uppercase">Frota Total</p>
               </div>
            </CardContent>
         </Card>
      </div>

      {loading ? (
        <div className="h-64 flex items-center justify-center text-slate-400 animate-pulse">
           Carregando gráficos...
        </div>
      ) : (
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            
            {/* Status Chart */}
            <Card className="shadow-sm border-slate-200">
                <CardHeader>
                    <CardTitle className="text-sm font-bold text-slate-700 flex items-center gap-2">
                        <Activity size={16} className="text-emerald-500"/> Status da Frota
                    </CardTitle>
                </CardHeader>
                <CardContent className="h-[300px]">
                    <ResponsiveContainer width="100%" height="100%">
                        <PieChart>
                            <Pie
                                data={statusData}
                                cx="50%"
                                cy="50%"
                                innerRadius={60}
                                outerRadius={80}
                                paddingAngle={5}
                                dataKey="value"
                            >
                                {statusData.map((entry, index) => (
                                    <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                                ))}
                            </Pie>
                            <Tooltip content={<CustomTooltip />} />
                            <Legend verticalAlign="bottom" height={36} iconType="circle" />
                        </PieChart>
                    </ResponsiveContainer>
                </CardContent>
            </Card>

            {/* Base Chart */}
            <Card className="shadow-sm border-slate-200">
                <CardHeader>
                    <CardTitle className="text-sm font-bold text-slate-700 flex items-center gap-2">
                        <MapPin size={16} className="text-indigo-500"/> Veículos por Base
                    </CardTitle>
                </CardHeader>
                <CardContent className="h-[300px]">
                     <ResponsiveContainer width="100%" height="100%">
                        <BarChart data={baseData} layout="vertical" margin={{ left: 20 }}>
                            <CartesianGrid strokeDasharray="3 3" horizontal={false} />
                            <XAxis type="number" hide />
                            <YAxis dataKey="name" type="category" width={100} tick={{fontSize: 10}} />
                            <Tooltip cursor={{fill: '#f1f5f9'}} content={<CustomTooltip />} />
                            <Bar dataKey="value" fill="#6366f1" radius={[0, 4, 4, 0]} barSize={20} />
                        </BarChart>
                    </ResponsiveContainer>
                </CardContent>
            </Card>

             {/* Disponibilidade Chart */}
             <Card className="shadow-sm border-slate-200">
                <CardHeader>
                    <CardTitle className="text-sm font-bold text-slate-700 flex items-center gap-2">
                        <CheckCircle size={16} className="text-teal-500"/> Disponibilidade
                    </CardTitle>
                </CardHeader>
                <CardContent className="h-[300px]">
                     <ResponsiveContainer width="100%" height="100%">
                        <PieChart>
                             <Pie
                                data={disponibilidadeData}
                                cx="50%"
                                cy="50%"
                                outerRadius={80}
                                dataKey="value"
                                label={({name, percent}) => `${name} ${(percent * 100).toFixed(0)}%`}
                                labelLine={false}
                            >
                                {disponibilidadeData.map((entry, index) => (
                                    <Cell key={`cell-${index}`} fill={entry.name === 'Disponível' ? '#10b981' : '#ef4444'} />
                                ))}
                            </Pie>
                            <Tooltip content={<CustomTooltip />} />
                        </PieChart>
                    </ResponsiveContainer>
                </CardContent>
            </Card>

            {/* Manutenção Chart */}
            <Card className="shadow-sm border-slate-200">
                <CardHeader>
                    <CardTitle className="text-sm font-bold text-slate-700 flex items-center gap-2">
                        <AlertTriangle size={16} className="text-orange-500"/> Manutenção por Status
                    </CardTitle>
                </CardHeader>
                <CardContent className="h-[300px]">
                     <ResponsiveContainer width="100%" height="100%">
                        <BarChart data={manutencaoData} margin={{ top: 20 }}>
                            <CartesianGrid strokeDasharray="3 3" vertical={false} />
                            <XAxis dataKey="name" tick={{fontSize: 10}} />
                            <YAxis />
                            <Tooltip content={<CustomTooltip />} />
                            <Bar dataKey="value" fill="#f97316" radius={[4, 4, 0, 0]} barSize={30} />
                        </BarChart>
                    </ResponsiveContainer>
                </CardContent>
            </Card>

             {/* Categoria Chart */}
             <Card className="shadow-sm border-slate-200 col-span-1 lg:col-span-2">
                <CardHeader>
                    <CardTitle className="text-sm font-bold text-slate-700 flex items-center gap-2">
                        <BarChart3 size={16} className="text-slate-500"/> Frota por Categoria
                    </CardTitle>
                </CardHeader>
                <CardContent className="h-[250px]">
                     <ResponsiveContainer width="100%" height="100%">
                        <BarChart data={categoriaData}>
                            <CartesianGrid strokeDasharray="3 3" vertical={false} />
                            <XAxis dataKey="name" tick={{fontSize: 10}} />
                            <YAxis />
                            <Tooltip content={<CustomTooltip />} />
                            <Bar dataKey="value" fill="#0f172a" radius={[4, 4, 0, 0]} barSize={40} />
                        </BarChart>
                    </ResponsiveContainer>
                </CardContent>
            </Card>
        </div>
      )}
    </div>
  );
};
