"use client";

import { useEffect, useState } from "react";
import { Users, ClipboardList, ShieldAlert, CheckCircle } from "lucide-react";
import { Header } from "@/components/layout/header";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { clientsApi, auditsApi, type Client, type Audit } from "@/lib/api";
import { getToken } from "@/lib/auth";

type Stats = {
  totalClients: number;
  totalAudits: number;
  auditsEnCours: number;
  auditsTermines: number;
};

export default function DashboardPage() {
  const [stats, setStats] = useState<Stats>({
    totalClients: 0,
    totalAudits: 0,
    auditsEnCours: 0,
    auditsTermines: 0,
  });
  const [recentAudits, setRecentAudits] = useState<Audit[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const token = getToken();
    if (!token) return;

    Promise.all([clientsApi.list(token), auditsApi.list(token)])
      .then(([clients, audits]) => {
        setStats({
          totalClients: clients.length,
          totalAudits: audits.length,
          auditsEnCours: audits.filter((a) => a.statut === "en_cours").length,
          auditsTermines: audits.filter((a) => a.statut === "termine").length,
        });
        setRecentAudits(audits.slice(0, 5));
      })
      .finally(() => setLoading(false));
  }, []);

  const statCards = [
    { label: "Clients", value: stats.totalClients, icon: Users, color: "text-blue-600" },
    { label: "Audits total", value: stats.totalAudits, icon: ClipboardList, color: "text-purple-600" },
    { label: "En cours", value: stats.auditsEnCours, icon: ShieldAlert, color: "text-orange-500" },
    { label: "Terminés", value: stats.auditsTermines, icon: CheckCircle, color: "text-green-600" },
  ];

  const statutLabels: Record<string, string> = {
    planifie: "Planifié",
    en_cours: "En cours",
    termine: "Terminé",
    annule: "Annulé",
  };

  const statutColors: Record<string, string> = {
    planifie: "text-blue-600 bg-blue-50",
    en_cours: "text-orange-600 bg-orange-50",
    termine: "text-green-600 bg-green-50",
    annule: "text-gray-500 bg-gray-50",
  };

  return (
    <div className="flex flex-col h-full">
      <Header title="Tableau de bord" />
      <div className="flex-1 p-6 space-y-6">
        {/* Stats cards */}
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
          {statCards.map(({ label, value, icon: Icon, color }) => (
            <Card key={label}>
              <CardHeader className="flex flex-row items-center justify-between pb-2">
                <CardTitle className="text-sm font-medium text-muted-foreground">{label}</CardTitle>
                <Icon className={`h-5 w-5 ${color}`} />
              </CardHeader>
              <CardContent>
                <p className="text-3xl font-bold">
                  {loading ? <span className="animate-pulse text-muted-foreground">—</span> : value}
                </p>
              </CardContent>
            </Card>
          ))}
        </div>

        {/* Recent audits */}
        <Card>
          <CardHeader>
            <CardTitle className="text-base">Audits récents</CardTitle>
          </CardHeader>
          <CardContent>
            {loading ? (
              <p className="text-sm text-muted-foreground">Chargement...</p>
            ) : recentAudits.length === 0 ? (
              <p className="text-sm text-muted-foreground">Aucun audit pour le moment.</p>
            ) : (
              <div className="space-y-3">
                {recentAudits.map((audit) => (
                  <div key={audit.id} className="flex items-center justify-between py-2 border-b last:border-0">
                    <div>
                      <p className="font-medium text-sm">{audit.nom}</p>
                      <p className="text-xs text-muted-foreground">
                        {new Date(audit.createdAt).toLocaleDateString("fr-FR")}
                      </p>
                    </div>
                    <span
                      className={`text-xs font-medium px-2 py-1 rounded-full ${statutColors[audit.statut]}`}
                    >
                      {statutLabels[audit.statut]}
                    </span>
                  </div>
                ))}
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
