"use client";

import { useEffect, useState } from "react";
import { Plus, Search, ClipboardList } from "lucide-react";
import { Header } from "@/components/layout/header";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { auditsApi, type Audit } from "@/lib/api";
import { getToken } from "@/lib/auth";
import Link from "next/link";

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

const statutVariant: Record<string, "default" | "secondary" | "destructive" | "outline"> = {
  planifie: "secondary",
  en_cours: "default",
  termine: "outline",
  annule: "destructive",
};

export default function AuditsPage() {
  const [audits, setAudits] = useState<Audit[]>([]);
  const [search, setSearch] = useState("");
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const token = getToken();
    if (!token) return;
    auditsApi.list(token).then(setAudits).finally(() => setLoading(false));
  }, []);

  const filtered = audits.filter((a) =>
    a.nom.toLowerCase().includes(search.toLowerCase())
  );

  return (
    <div className="flex flex-col h-full">
      <Header title="Audits" />
      <div className="flex-1 p-6 space-y-4">
        <div className="flex items-center gap-3">
          <div className="relative flex-1 max-w-sm">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
            <Input
              placeholder="Rechercher un audit..."
              className="pl-9"
              value={search}
              onChange={(e) => setSearch(e.target.value)}
            />
          </div>
          <Button asChild>
            <Link href="/audits/nouveau">
              <Plus className="h-4 w-4 mr-2" />
              Nouvel audit
            </Link>
          </Button>
        </div>

        {loading ? (
          <p className="text-sm text-muted-foreground">Chargement...</p>
        ) : filtered.length === 0 ? (
          <div className="text-center py-16 text-muted-foreground">
            <ClipboardList className="h-12 w-12 mx-auto mb-3 opacity-30" />
            <p className="font-medium">Aucun audit trouvé</p>
          </div>
        ) : (
          <div className="space-y-3">
            {filtered.map((audit) => (
              <Link key={audit.id} href={`/audits/${audit.id}`}>
                <Card className="hover:shadow-md transition-shadow cursor-pointer">
                  <CardContent className="p-4 flex items-center justify-between">
                    <div>
                      <p className="font-semibold">{audit.nom}</p>
                      <p className="text-sm text-muted-foreground">
                        {audit.dateDebut
                          ? new Date(audit.dateDebut).toLocaleDateString("fr-FR")
                          : "Date non définie"}
                      </p>
                    </div>
                    <div className="flex items-center gap-3">
                      {audit.scoreGlobal !== null && (
                        <span className="text-sm font-medium text-muted-foreground">
                          Score : {audit.scoreGlobal.toFixed(1)}
                        </span>
                      )}
                      <Badge variant={statutVariant[audit.statut]}>
                        {statutLabels[audit.statut]}
                      </Badge>
                    </div>
                  </CardContent>
                </Card>
              </Link>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
