import React, { useState, useMemo } from 'react';
import { useGrDashboard } from '../hooks/useGrDashboard';
import { 
  Users, 
  MapPin, 
  BarChart3, 
  PieChart as PieChartIcon, 
  RefreshCw, 
  TrendingUp, 
  AlertCircle,
  LayoutDashboard,
  UserCheck,
  ShieldCheck,
  Activity,
  FileCheck,
  ClipboardList
} from 'lucide-react';
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card';
import { 
  PieChart, Pie, Cell, ResponsiveContainer, Tooltip, BarChart, Bar, XAxis, YAxis, CartesianGrid, Legend
} from 'recharts';
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { GrPeriodSelector } from '../components/GrPeriodSelector';

// Cores premium consistentes com o design system
const COLORS = ['#10b981', '#3b82f6', '#f59e0b', '#ef4444', '#8b5cf6', '#06b6d4', '#ec4899', '#14b8a6'];

const Skeleton = ({ className }) => (
  <div className={`animate-pulse bg-slate-200 dark:bg-slate-800 rounded-xl ${className}`} />
);

const KPIWrapper = ({ title, value, icon: Icon, color, loading }) => (
  <Card className="border-none shadow-sm hover:shadow-md transition-all bg-white dark:bg-[#1c1c1c] overflow-hidden group">
    <CardContent className="p-6">
      <div className="flex items-center justify-between">
        <div className="space-y-1">
          <p className="text-[10px] font-bold text-slate-400 uppercase tracking-[0.15em]">{title}</p>
          {loading ? (
            <Skeleton className="h-8 w-24" />
          ) : (
            <h3 className="text-[clamp(1.25rem,2.5vw,1.75rem)] font-bold text-slate-800 dark:text-white group-hover:text-[var(--gr-primary)] transition-colors">
              {value ?? 0}
            </h3>
          )}
        </div>
        <div className={`p-3 rounded-2xl ${color} shadow-inner group-hover:scale-110 transition-transform flex items-center justify-center shrink-0`}>
          {React.cloneElement(Icon, { size: 24 })}
        </div>
      </div>
    </CardContent>
  </Card>
);

const CustomTooltip = ({ active, payload, label }) => {
  if (!active || !payload || !payload.length) return null;

  return (
    <div className="bg-white/90 dark:bg-[#1c1c1c]/90 border border-slate-200 dark:border-[#2a2a2a] p-3 rounded-xl shadow-xl backdrop-blur-md z-[9999]">
      {label && <p className="text-[10px] font-bold uppercase text-slate-400 mb-2 tracking-widest">{label}</p>}
      <div className="space-y-1.5">
        {payload.map((item, index) => (
          <div key={index} className="flex items-center gap-2">
            <div className="w-2.5 h-2.5 rounded-full" style={{ backgroundColor: item.color || item.fill }} />
            <span className="text-xs font-semibold text-slate-600 dark:text-slate-300">{item.name}:</span>
            <span className="text-xs font-bold text-slate-900 dark:text-white">{item.value.toLocaleString()}</span>
          </div>
        ))}
      </div>
    </div>
  );
};

const GrDashboardView = () => {
  const { data, loading, refresh, filters, setFilters } = useGrDashboard();
  const [activeTab, setActiveTab] = useState("registros");

  // Dados formatados para Registros
  const statusData = useMemo(() => data.globalStatusEst.map(item => ({
    name: item.global_status || 'N/A',
    value: item.total || 0
  })), [data.globalStatusEst]);

  const baseData = useMemo(() => data.baseEst.map(item => ({
    name: item.base || 'N/A',
    total: item.total || 0
  })).slice(0, 8), [data.baseEst]);

  const coordData = useMemo(() => data.coordenadorEst.map(item => ({
    name: item.coordenador || 'N/A',
    total: item.total || 0
  })).slice(0, 10), [data.coordenadorEst]);

  // Dados formatados para Contratos
  const statusContratosData = useMemo(() => data.statusContratos.map(item => ({
    name: item.status_assinatura || item.global_status || 'N/A',
    value: item.total || 0
  })), [data.statusContratos]);

  const producaoBaseContratosData = useMemo(() => data.producaoBaseContratos.map(item => ({
    name: item.base || 'N/A',
    total: item.total_contratos || item.total || 0,
    total_dia: item.total_dia || 0
  })).slice(0, 8), [data.producaoBaseContratos]);

  const despachanteContratosData = useMemo(() => data.despachanteContratos.map(item => ({
    name: item.despachante || 'N/A',
    total: item.total_contratos || 0
  })).slice(0, 8), [data.despachanteContratos]);

  const totalRegistros = useMemo(() => statusData.reduce((acc, curr) => acc + curr.value, 0), [statusData]);
  const totalContratosArr = useMemo(() => statusContratosData.reduce((acc, curr) => acc + curr.value, 0), [statusContratosData]);
  const totalContratos = totalContratosArr > 0 ? totalContratosArr : data.statusContratos.reduce((acc, curr) => acc + (curr.total || 0), 0);

  if (loading && !data.resumo) {
    return (
      <div className="p-6 md:p-8 space-y-8 animate-in fade-in duration-500">
        <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
          <div className="space-y-2">
            <Skeleton className="h-10 w-64" />
            <Skeleton className="h-4 w-96" />
          </div>
          <Skeleton className="h-10 w-40" />
        </div>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
          {[1, 2, 3, 4].map((i) => <Skeleton key={i} className="h-32 w-full" />)}
        </div>
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
          <Skeleton className="h-[400px] w-full" />
          <Skeleton className="h-[400px] w-full" />
        </div>
      </div>
    );
  }

  return (
    <div className="p-4 md:p-8 w-full h-full min-h-[calc(100vh-100px)] relative bg-[#f8fafc] dark:bg-[#0f0f0f] animate-in fade-in slide-in-from-bottom-4 duration-700 pb-12 overflow-y-auto custom-scrollbar">
      {/* Header com Tipografia Fluida */}
      <div className="flex flex-col md:flex-row md:items-center justify-between gap-6 mb-8">
        <div className="space-y-1">
          <div className="flex items-center gap-3">
            <div className="p-2.5 bg-[var(--gr-primary)]/10 rounded-xl">
               <LayoutDashboard className="text-[var(--gr-primary)]" size={28} />
            </div>
            <h1 className="text-[clamp(1.5rem,3.5vw,2.25rem)] font-bold text-slate-800 dark:text-white tracking-tight">
              Cockpit <span className="text-[var(--gr-primary)]">Estatístico</span>
            </h1>
          </div>
          <p className="text-[clamp(0.875rem,1.2vw,1rem)] text-slate-500 dark:text-slate-400 font-medium">
            Monitoramento analítico de cadastros e conformidade contratual.
          </p>
        </div>
        <div className="flex flex-col md:flex-row items-center gap-4">
          <GrPeriodSelector filters={filters} setFilters={setFilters} loading={loading} />
          <button 
            onClick={refresh}
            className="flex items-center justify-center gap-2 px-6 py-3 rounded-2xl bg-white dark:bg-[#1c1c1c] border border-slate-200 dark:border-[#2a2a2a] text-slate-600 dark:text-slate-300 font-bold text-sm hover:shadow-xl hover:-translate-y-0.5 active:scale-95 transition-all w-full md:w-fit"
          >
            <RefreshCw size={18} className={loading ? "animate-spin" : ""} /> 
            Sincronizar Dados
          </button>
        </div>
      </div>

      <Tabs defaultValue="registros" className="space-y-8" onValueChange={setActiveTab}>
        <div className="flex justify-center md:justify-start">
          <TabsList className="bg-slate-100 dark:bg-[#1c1c1c] p-1.5 rounded-2xl border border-slate-200 dark:border-[#2a2a2a]">
            <TabsTrigger value="registros" className="rounded-xl px-8 py-2.5 text-xs font-bold uppercase tracking-widest data-[state=active]:bg-white dark:data-[state=active]:bg-[#2a2a2a] data-[state=active]:text-[var(--gr-primary)] data-[state=active]:shadow-sm transition-all">
              Gestão de Cadastros
            </TabsTrigger>
            <TabsTrigger value="contratos" className="rounded-xl px-8 py-2.5 text-xs font-bold uppercase tracking-widest data-[state=active]:bg-white dark:data-[state=active]:bg-[#2a2a2a] data-[state=active]:text-[var(--gr-primary)] data-[state=active]:shadow-sm transition-all">
              Gestão de Contratos
            </TabsTrigger>
          </TabsList>
        </div>

        <TabsContent value="registros" className="space-y-8 animate-in fade-in slide-in-from-left-4 duration-500">
          {/* KPIs Registros */}
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
            <KPIWrapper 
              title="Total de Cadastros" 
              value={totalRegistros} 
              icon={<Activity />} 
              color="bg-blue-500/10 text-blue-600"
              loading={loading}
            />
            <KPIWrapper 
              title="Aprovados" 
              value={statusData.find(s => s.name.includes('APROVADO'))?.value || 0} 
              icon={<ShieldCheck />} 
              color="bg-emerald-500/10 text-emerald-600"
              loading={loading}
            />
             <KPIWrapper 
              title="Pedências / Revisão" 
              value={statusData.find(s => s.name.includes('PEND'))?.value || 0} 
              icon={<AlertCircle />} 
              color="bg-orange-500/10 text-orange-600"
              loading={loading}
            />
            <KPIWrapper 
              title="Usuários Plataforma" 
              value={data.resumo?.total_usuarios || 0} 
              icon={<Users />} 
              color="bg-purple-500/10 text-purple-600"
              loading={loading}
            />
          </div>

          {/* Graficos Registros */}
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
            <Card className="border-none shadow-sm bg-white dark:bg-[#1c1c1c] overflow-hidden">
              <CardHeader className="flex flex-row items-center gap-3 border-b dark:border-[#2a2a2a] mb-6 p-6">
                <div className="p-2 bg-emerald-500/10 rounded-xl text-emerald-600">
                  <PieChartIcon size={20} />
                </div>
                <CardTitle className="text-sm font-bold uppercase tracking-widest text-slate-700 dark:text-slate-300">Status dos Cadastros</CardTitle>
              </CardHeader>
              <CardContent className="h-[380px] p-0 pb-8">
                <ResponsiveContainer width="100%" height="100%">
                  <PieChart>
                    <Pie
                      data={statusData}
                      cx="50%"
                      cy="45%"
                      innerRadius="60%"
                      outerRadius="85%"
                      paddingAngle={4}
                      dataKey="value"
                      stroke="none"
                    >
                      {statusData.map((entry, index) => (
                        <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                      ))}
                    </Pie>
                    <Tooltip content={<CustomTooltip />} />
                    <Legend 
                      verticalAlign="bottom" 
                      align="center" 
                      layout="horizontal" 
                      iconType="circle"
                      wrapperStyle={{ paddingTop: '20px', fontSize: '10px', fontWeight: 'bold' }}
                    />
                  </PieChart>
                </ResponsiveContainer>
              </CardContent>
            </Card>

            <Card className="border-none shadow-sm bg-white dark:bg-[#1c1c1c] overflow-hidden">
              <CardHeader className="flex flex-row items-center gap-3 border-b dark:border-[#2a2a2a] mb-6 p-6">
                <div className="p-2 bg-blue-500/10 rounded-xl text-blue-600">
                  <MapPin size={20} />
                </div>
                <CardTitle className="text-sm font-bold uppercase tracking-widest text-slate-700 dark:text-slate-300">Volume por Base Operacional</CardTitle>
              </CardHeader>
              <CardContent className="h-[380px] p-4">
                <ResponsiveContainer width="100%" height="100%">
                  <BarChart data={baseData}>
                    <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#f1f5f9" />
                    <XAxis 
                       dataKey="name" 
                       fontSize={10} 
                       fontWeight="600"
                       axisLine={false} 
                       tickLine={false} 
                       tick={{ fill: 'currentColor' }}
                       className="text-slate-400"
                    />
                    <YAxis 
                       fontSize={10} 
                       fontWeight="600"
                       axisLine={false} 
                       tickLine={false} 
                       tick={{ fill: 'currentColor' }}
                       className="text-slate-400"
                    />
                    <Tooltip content={<CustomTooltip />} cursor={{ fill: 'transparent' }} />
                    <Bar dataKey="total" name="Cadastros" fill="#3b82f6" radius={[6, 6, 0, 0]} barSize={32} />
                  </BarChart>
                </ResponsiveContainer>
              </CardContent>
            </Card>
          </div>

          <Card className="border-none shadow-sm bg-white dark:bg-[#1c1c1c] overflow-hidden">
             <CardHeader className="flex flex-row items-center gap-3 border-b dark:border-[#2a2a2a] mb-6 p-6">
               <div className="p-2 bg-purple-500/10 rounded-xl text-purple-600">
                 <UserCheck size={20} />
               </div>
               <CardTitle className="text-sm font-bold uppercase tracking-widest text-slate-700 dark:text-slate-300">Produção por Coordenador</CardTitle>
             </CardHeader>
             <CardContent className="h-[450px] p-4 pb-8">
               <ResponsiveContainer width="100%" height="100%">
                 <BarChart data={coordData} layout="vertical" margin={{ left: 20, right: 20 }}>
                   <CartesianGrid strokeDasharray="3 3" horizontal={false} stroke="#f1f5f9" />
                   <XAxis type="number" fontSize={10} fontWeight="600" axisLine={false} tickLine={false} className="text-slate-400" />
                   <YAxis 
                      dataKey="name" 
                      type="category" 
                      fontSize={10} 
                      fontWeight="700"
                      axisLine={false} 
                      tickLine={false} 
                      width={120}
                      className="text-slate-600 dark:text-slate-300"
                   />
                   <Tooltip content={<CustomTooltip />} cursor={{ fill: 'rgba(139, 92, 246, 0.05)' }} />
                   <Bar dataKey="total" name="Cadastros Ativos" fill="#8b5cf6" radius={[0, 6, 6, 0]} barSize={24} />
                 </BarChart>
               </ResponsiveContainer>
             </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="contratos" className="space-y-8 animate-in fade-in slide-in-from-right-4 duration-500">
           {/* KPIs Contratos */}
           <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
            <KPIWrapper 
              title="Total de Contratos" 
              value={totalContratos} 
              icon={<FileCheck />} 
              color="bg-emerald-500/10 text-emerald-600"
              loading={loading}
            />
            <KPIWrapper 
              title="Assinados" 
              value={statusContratosData.find(s => s.name.includes('ASSINADO'))?.value || 0} 
              icon={<ShieldCheck />} 
              color="bg-blue-500/10 text-blue-600"
              loading={loading}
            />
             <KPIWrapper 
              title="Pedentes Assinatura" 
              value={statusContratosData.find(s => s.name.includes('PEND'))?.value || 0} 
              icon={<ClipboardList />} 
              color="bg-orange-500/10 text-orange-600"
              loading={loading}
            />
            <KPIWrapper 
              title="Produção Diária" 
              value={data.producaoBaseContratos.reduce((acc, curr) => acc + (curr.total_dia || 0), 0)} 
              icon={<TrendingUp />} 
              color="bg-purple-500/10 text-purple-600"
              loading={loading}
            />
          </div>

          <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
            <Card className="border-none shadow-sm bg-white dark:bg-[#1c1c1c] overflow-hidden">
              <CardHeader className="flex flex-row items-center gap-3 border-b dark:border-[#2a2a2a] mb-6 p-6">
                <div className="p-2 bg-blue-500/10 rounded-xl text-blue-600">
                  <PieChartIcon size={20} />
                </div>
                <CardTitle className="text-sm font-bold uppercase tracking-widest text-slate-700 dark:text-slate-300">Status de Assinatura</CardTitle>
              </CardHeader>
              <CardContent className="h-[380px] p-0 pb-8">
                <ResponsiveContainer width="100%" height="100%">
                  <PieChart>
                    <Pie
                      data={statusContratosData}
                      cx="50%"
                      cy="45%"
                      innerRadius="60%"
                      outerRadius="85%"
                      paddingAngle={4}
                      dataKey="value"
                      stroke="none"
                    >
                      {statusContratosData.map((entry, index) => (
                        <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                      ))}
                    </Pie>
                    <Tooltip content={<CustomTooltip />} />
                    <Legend 
                      verticalAlign="bottom" 
                      align="center" 
                      layout="horizontal" 
                      iconType="circle"
                      wrapperStyle={{ paddingTop: '20px', fontSize: '10px', fontWeight: 'bold' }}
                    />
                  </PieChart>
                </ResponsiveContainer>
              </CardContent>
            </Card>

            <Card className="border-none shadow-sm bg-white dark:bg-[#1c1c1c] overflow-hidden">
              <CardHeader className="flex flex-row items-center gap-3 border-b dark:border-[#2a2a2a] mb-6 p-6">
                <div className="p-2 bg-emerald-500/10 rounded-xl text-emerald-600">
                  <MapPin size={20} />
                </div>
                <CardTitle className="text-sm font-bold uppercase tracking-widest text-slate-700 dark:text-slate-300">Contratos por Base</CardTitle>
              </CardHeader>
              <CardContent className="h-[380px] p-4">
                <ResponsiveContainer width="100%" height="100%">
                  <BarChart data={producaoBaseContratosData}>
                    <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#f1f5f9" />
                    <XAxis 
                      dataKey="name" 
                      fontSize={10} 
                      fontWeight="600" 
                      axisLine={false} 
                      tickLine={false} 
                      tick={{ fill: 'currentColor' }}
                      className="text-slate-400"
                    />
                    <YAxis 
                      fontSize={10} 
                      fontWeight="600" 
                      axisLine={false} 
                      tickLine={false} 
                      tick={{ fill: 'currentColor' }}
                      className="text-slate-400"
                    />
                    <Tooltip content={<CustomTooltip />} cursor={{ fill: 'rgba(16, 185, 129, 0.05)' }} />
                    <Bar dataKey="total" name="Total Contratos" fill="#10b981" radius={[6, 6, 0, 0]} barSize={32} />
                  </BarChart>
                </ResponsiveContainer>
              </CardContent>
            </Card>
          </div>

          <Card className="border-none shadow-sm bg-white dark:bg-[#1c1c1c] overflow-hidden">
             <CardHeader className="flex flex-row items-center gap-3 border-b dark:border-[#2a2a2a] mb-6 p-6">
               <div className="p-2 bg-blue-500/10 rounded-xl text-blue-600">
                 <Users size={20} />
               </div>
               <CardTitle className="text-sm font-bold uppercase tracking-widest text-slate-700 dark:text-slate-300">Contratos por Despachante</CardTitle>
             </CardHeader>
             <CardContent className="h-[400px] p-4 pb-8">
               <ResponsiveContainer width="100%" height="100%">
                 <BarChart data={despachanteContratosData} layout="vertical" margin={{ left: 20, right: 20 }}>
                   <CartesianGrid strokeDasharray="3 3" horizontal={false} stroke="#f1f5f9" />
                   <XAxis type="number" fontSize={10} fontWeight="600" axisLine={false} tickLine={false} className="text-slate-400" />
                   <YAxis 
                      dataKey="name" 
                      type="category" 
                      fontSize={10} 
                      fontWeight="700"
                      axisLine={false} 
                      tickLine={false} 
                      width={120}
                      className="text-slate-600 dark:text-slate-300"
                   />
                   <Tooltip content={<CustomTooltip />} cursor={{ fill: 'rgba(59, 130, 246, 0.05)' }} />
                   <Bar dataKey="total" name="Contratos" fill="#3b82f6" radius={[0, 6, 6, 0]} barSize={24} />
                 </BarChart>
               </ResponsiveContainer>
             </CardContent>
          </Card>
          <Card className="border-none shadow-sm bg-white dark:bg-[#1c1c1c] overflow-hidden">
             <CardHeader className="flex flex-row items-center gap-3 border-b dark:border-[#2a2a2a] mb-6 p-6">
               <div className="p-2 bg-purple-500/10 rounded-xl text-purple-600">
                 <ClipboardList size={20} />
               </div>
               <CardTitle className="text-sm font-bold uppercase tracking-widest text-slate-700 dark:text-slate-300">Status por Coordenador</CardTitle>
             </CardHeader>
             <CardContent className="h-[450px] p-4 pb-8">
               <ResponsiveContainer width="100%" height="100%">
                 <BarChart data={data.coordenadorStatusAssinatura.slice(0, 10)} layout="vertical" margin={{ left: 20, right: 20 }}>
                   <CartesianGrid strokeDasharray="3 3" horizontal={false} stroke="#f1f5f9" />
                   <XAxis type="number" fontSize={10} fontWeight="600" axisLine={false} tickLine={false} className="text-slate-400" />
                   <YAxis 
                      dataKey="coordenador" 
                      type="category" 
                      fontSize={10} 
                      fontWeight="700"
                      axisLine={false} 
                      tickLine={false} 
                      width={120}
                      className="text-slate-600 dark:text-slate-300"
                   />
                   <Tooltip content={<CustomTooltip />} cursor={{ fill: 'rgba(139, 92, 246, 0.05)' }} />
                   <Legend verticalAlign="top" align="right" iconType="circle" wrapperStyle={{ paddingBottom: '20px', fontSize: '10px', fontWeight: 'bold' }} />
                   <Bar dataKey="ASSINADO" name="Assinado" stackId="a" fill="#10b981" barSize={24} />
                   <Bar dataKey="NÃO ASSINADO" name="Não Assinado" stackId="a" fill="#f59e0b" barSize={24} />
                   <Bar dataKey="SEM ASSINATURA" name="Sem Assinatura" stackId="a" fill="#ef4444" barSize={24} />
                   <Bar dataKey="EM ANDAMENTO" name="Em Andamento" stackId="a" fill="#3b82f6" barSize={24} radius={[0, 6, 6, 0]} />
                 </BarChart>
               </ResponsiveContainer>
             </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
};

export default GrDashboardView;
