import { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import {
  Users,
  Building2,
  Wallet,
  TrendingUp,
  ArrowRight,
  Calendar,
  CheckCircle,
  Clock,
  AlertTriangle,
} from 'lucide-react';
import { PageHeader } from '@/components/common/PageHeader';
import { StatsCard } from '@/components/common/StatsCard';
import { StatusBadge } from '@/components/common/StatusBadge';
import { Button } from '@/components/ui/button';
import { formatCurrency, formatNumber } from '@/utils/locale';
import { rhService } from '@/services/rhService';
import { budgetService } from '@/services/budgetService';
import { treasuryService } from '@/services/treasuryService';
import { useMinistries } from '@/hooks/useMinistries';
import { useOrgUnits } from '@/hooks/useOrgUnits';
import { toast } from 'sonner';
import { format } from 'date-fns';
import { ptBR } from 'date-fns/locale';

export function Dashboard() {
  const [stats, setStats] = useState({
    totalAgents: 0,
    activeAgents: 0,
    totalMinistries: 0,
    totalUnits: 0,
    monthlyPayroll: 0,
    budgetExecution: 0,
  });
  const [recentPayrollRuns, setRecentPayrollRuns] = useState<any[]>([]);
  const [recentPaymentBatches, setRecentPaymentBatches] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  const { ministries } = useMinistries({ size: 100 });
  const { orgUnits } = useOrgUnits({ size: 100 });

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

  const loadDashboardData = async () => {
    try {
      setLoading(true);

      // Carregar estatísticas de agentes
      const agentStats = await rhService.getStats({});
      setStats((prev) => ({
        ...prev,
        totalAgents: agentStats.total || 0,
        activeAgents: agentStats.active || 0,
      }));

      // Carregar ministérios e unidades
      setStats((prev) => ({
        ...prev,
        totalMinistries: ministries.length,
        totalUnits: orgUnits.length,
      }));

      // Carregar períodos de folha recentes
      const periods = await rhService.getPayrollPeriods();
      const recentPeriods = periods.slice(0, 3);

      // Carregar execuções de folha recentes
      const payrollRuns = await Promise.all(
        recentPeriods.map(async (period: any) => {
          try {
            // Buscar execuções de folha para este período
            // Por enquanto, usar dados básicos
            return {
              id: period.id,
              periodName: format(new Date(period.fiscalYear, period.month - 1), "MMMM 'de' yyyy", { locale: ptBR }),
              totalEmployees: 0,
              totalNet: 0,
              status: period.status,
            };
          } catch {
            return null;
          }
        })
      );
      setRecentPayrollRuns(payrollRuns.filter(Boolean));

      // Carregar lotes de pagamento recentes
      const batchesResponse = await treasuryService.getPaymentBatches({
        page: 0,
        size: 3,
        sortBy: 'createdAt',
        sortDirection: 'DESC',
      });
      setRecentPaymentBatches(batchesResponse.content.map((batch: any) => ({
        id: batch.id,
        reference: `LOTE-${batch.periodId}`,
        description: `Período ${batch.periodId}`,
        totalAmount: 0,
        totalOrders: 0,
        status: batch.status === 'CREATED' ? 'pending' :
          batch.status === 'SENT_TO_BANK' ? 'processing' :
            batch.status === 'CONFIRMED' ? 'completed' : 'rejected',
      })));

      // Calcular execução orçamentária (simplificado)
      const currentFiscalYear = await budgetService.getCurrentFiscalYear().catch(() => null);
      if (currentFiscalYear) {
        const budgetLines = await budgetService.getBudgetLines({
          page: 0,
          size: 1,
          fiscalYearId: currentFiscalYear.id,
        });
        if (budgetLines.content.length > 0) {
          const line = budgetLines.content[0];
          const totalAllocated = line.totalAllocated || 0;
          const totalCommitted = line.totalCommitted || 0;
          const executionPercent = totalAllocated > 0
            ? Math.round((totalCommitted / totalAllocated) * 100)
            : 0;
          setStats((prev) => ({
            ...prev,
            budgetExecution: executionPercent,
          }));
        }
      }

    } catch (error) {
      toast.error('Erro ao carregar dados do dashboard');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="space-y-8">
      <PageHeader
        title="Painel Principal"
        description="Visão geral do Sistema Integrado de Gestão do Estado e Pessoal"
      />

      {/* Main Stats */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        <StatsCard
          title="Total de Agentes"
          value={loading ? '...' : formatNumber(stats.totalAgents)}
          description={loading ? 'Carregando...' : `${formatNumber(stats.activeAgents)} activos`}
          icon={Users}
          variant="rh"
        />
        <StatsCard
          title="Ministérios"
          value={loading ? '...' : stats.totalMinistries.toString()}
          description={loading ? 'Carregando...' : `${stats.totalUnits} unidades orgânicas`}
          icon={Building2}
          variant="org"
        />
        <StatsCard
          title="Folha Mensal"
          value={loading ? '...' : formatCurrency(stats.monthlyPayroll, { compact: true })}
          description="Último período processado"
          icon={Wallet}
          variant="treasury"
        />
        <StatsCard
          title="Execução Orçamental"
          value={loading ? '...' : `${stats.budgetExecution}%`}
          description="Do orçamento anual"
          icon={TrendingUp}
          variant="budget"
          trend={stats.budgetExecution > 0 ? { value: 3.2, isPositive: true } : undefined}
        />
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Recent Payroll Runs */}
        <div className="gov-card">
          <div className="p-4 border-b border-border flex items-center justify-between">
            <div>
              <h2 className="font-semibold text-foreground">Folhas de Pagamento</h2>
              <p className="text-sm text-muted-foreground">Últimos processamentos</p>
            </div>
            <Button variant="ghost" size="sm" asChild>
              <Link to="/rh/payroll-runs">
                Ver todos
                <ArrowRight className="ml-2 h-4 w-4" />
              </Link>
            </Button>
          </div>
          <div className="divide-y divide-border">
            {loading ? (
              <div className="p-4 text-center text-muted-foreground">Carregando...</div>
            ) : recentPayrollRuns.length === 0 ? (
              <div className="p-4 text-center text-muted-foreground">Nenhuma folha processada</div>
            ) : (
              recentPayrollRuns.map((run) => (
                <div
                  key={run.id}
                  className="p-4 flex items-center justify-between hover:bg-muted/50 transition-colors"
                >
                  <div className="flex items-center gap-3">
                    <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-rh-light">
                      <Calendar className="h-5 w-5 text-rh" />
                    </div>
                    <div>
                      <p className="font-medium text-foreground">{run.periodName}</p>
                      <p className="text-sm text-muted-foreground">
                        {formatNumber(run.totalEmployees)} agentes
                      </p>
                    </div>
                  </div>
                  <div className="flex items-center gap-4">
                    <div className="text-right">
                      <p className="font-medium">{formatCurrency(run.totalNet, { compact: true })}</p>
                      <p className="text-sm text-muted-foreground">Líquido</p>
                    </div>
                    <StatusBadge status={run.status} />
                  </div>
                </div>
              ))
            )}
          </div>
        </div>

        {/* Payment Batches */}
        <div className="gov-card">
          <div className="p-4 border-b border-border flex items-center justify-between">
            <div>
              <h2 className="font-semibold text-foreground">Lotes de Pagamento</h2>
              <p className="text-sm text-muted-foreground">Estado das transferências</p>
            </div>
            <Button variant="ghost" size="sm" asChild>
              <Link to="/treasury/batches">
                Ver todos
                <ArrowRight className="ml-2 h-4 w-4" />
              </Link>
            </Button>
          </div>
          <div className="divide-y divide-border">
            {loading ? (
              <div className="p-4 text-center text-muted-foreground">Carregando...</div>
            ) : recentPaymentBatches.length === 0 ? (
              <div className="p-4 text-center text-muted-foreground">Nenhum lote de pagamento</div>
            ) : (
              recentPaymentBatches.map((batch) => {
                const StatusIcon =
                  batch.status === 'completed'
                    ? CheckCircle
                    : batch.status === 'processing'
                      ? Clock
                      : batch.status === 'rejected'
                        ? AlertTriangle
                        : Clock;

                return (
                  <div
                    key={batch.id}
                    className="p-4 flex items-center justify-between hover:bg-muted/50 transition-colors"
                  >
                    <div className="flex items-center gap-3">
                      <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-treasury-light">
                        <StatusIcon className="h-5 w-5 text-treasury" />
                      </div>
                      <div>
                        <p className="font-medium text-foreground">{batch.reference}</p>
                        <p className="text-sm text-muted-foreground truncate max-w-[200px]">
                          {batch.description}
                        </p>
                      </div>
                    </div>
                    <div className="flex items-center gap-4">
                      <div className="text-right">
                        <p className="font-medium">{formatCurrency(batch.totalAmount, { compact: true })}</p>
                        <p className="text-sm text-muted-foreground">
                          {formatNumber(batch.totalOrders)} ordens
                        </p>
                      </div>
                      <StatusBadge status={batch.status} />
                    </div>
                  </div>
                );
              }))}
          </div>
        </div>
      </div>

      {/* Quick Actions */}
      <div className="gov-card p-6">
        <h2 className="font-semibold text-foreground mb-4">Acções Rápidas</h2>
        <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-4">
          {[
            { label: 'Novo Agente', href: '/rh/agents/new', color: 'module-rh' },
            { label: 'Nova Folha', href: '/rh/payroll-runs/new', color: 'module-rh' },
            { label: 'Novo Ministério', href: '/org/ministries/new', color: 'module-org' },
            { label: 'Nova Linha', href: '/budget/lines/new', color: 'module-budget' },
            { label: 'Novo Lote', href: '/treasury/batches/new', color: 'module-treasury' },
            { label: 'Novo Utilizador', href: '/admin/users/new', color: 'module-admin' },
          ].map((action) => (
            <Link
              key={action.href}
              to={action.href}
              className={`flex flex-col items-center justify-center p-4 rounded-lg ${action.color} hover:opacity-80 transition-opacity text-center`}
            >
              <span className="text-sm font-medium">{action.label}</span>
            </Link>
          ))}
        </div>
      </div>
    </div>
  );
}
