import { useAuth } from "@/_core/hooks/useAuth";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { PortalMetricTile, PortalSectionIntro } from "@/components/portal/PortalSurface";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
  Sidebar,
  SidebarContent,
  SidebarFooter,
  SidebarGroup,
  SidebarGroupContent,
  SidebarGroupLabel,
  SidebarHeader,
  SidebarInset,
  SidebarMenu,
  SidebarMenuButton,
  SidebarMenuItem,
  SidebarProvider,
  SidebarSeparator,
  SidebarTrigger,
  useSidebar,
} from "@/components/ui/sidebar";
import { getLoginUrl } from "@/const";
import { useTheme } from "@/contexts/ThemeContext";
import { useIsMobile } from "@/hooks/useMobile";
import { trpc } from "@/lib/trpc";
import TerrainMissions from "@/pages/TerrainMissions";
import { 
  AlertTriangle,
  Building2, 
  CalendarDays,
  Package2,
  Edit,
  Eye,
  FileText, 
  FolderOpen, 
  Home, 
  LayoutDashboard, 
  LogOut, 
  PanelLeft, 
  Plus,
  Settings,
  Users,
  ClipboardList,
  HelpCircle,
  Shield
} from "lucide-react";
import { CSSProperties, useEffect, useRef, useState } from "react";
import { Link, useLocation } from "wouter";
import { DashboardLayoutSkeleton } from "@/components/DashboardLayoutSkeleton";

type SidebarNavItem = {
  icon: typeof LayoutDashboard;
  label: string;
  path: string;
  accentClass?: string;
};

type SidebarNavSection = {
  id: string;
  label: string;
  accentClass?: string;
  items: SidebarNavItem[];
};

const userSidebarSections: SidebarNavSection[] = [
  {
    id: "suivi",
    label: "Suivi",
    accentClass: "text-emerald-700",
    items: [
      { icon: LayoutDashboard, label: "Tableau de bord", path: "/dashboard", accentClass: "text-emerald-600" },
      { icon: Building2, label: "Mon association", path: "/dashboard/profile", accentClass: "text-sky-600" },
      { icon: FolderOpen, label: "Mes documents", path: "/dashboard/documents", accentClass: "text-cyan-600" },
      { icon: ClipboardList, label: "Mes demandes", path: "/dashboard/requests", accentClass: "text-emerald-500" },
    ],
  },
  {
    id: "demarches",
    label: "Démarches",
    accentClass: "text-orange-700",
    items: [
      { icon: FileText, label: "Nouvelle demande", path: "/dashboard/requests/new", accentClass: "text-amber-600" },
      { icon: CalendarDays, label: "Réservation de salle", path: "/dashboard/reservation-salle", accentClass: "text-blue-600" },
      { icon: Package2, label: "Matériel événementiel", path: "/dashboard/materiel-evenementiel", accentClass: "text-orange-600" },
    ],
  },
  {
    id: "referentiels",
    label: "Référentiels",
    accentClass: "text-violet-700",
    items: [
      { icon: Users, label: "Annuaire des associations", path: "/dashboard/associations", accentClass: "text-violet-600" },
      { icon: HelpCircle, label: "Aide", path: "/faq", accentClass: "text-slate-500" },
    ],
  },
];

// Admin menu items
const adminMenuItems = [
  { icon: Shield, label: "Administration", path: "/admin" },
];

const tourIdsByPath: Record<string, string> = {
  "/dashboard/profile": "nav-profile",
  "/dashboard/documents": "nav-documents",
  "/dashboard/requests/new": "nav-new-request",
  "/dashboard/reservation-salle": "nav-reservation",
  "/dashboard/materiel-evenementiel": "nav-material",
  "/dashboard/associations": "nav-directory",
  "/dashboard/requests": "nav-requests",
  "/admin": "nav-admin",
};

const SIDEBAR_WIDTH_KEY = "sidebar-width";
const DEFAULT_WIDTH = 280;
const MIN_WIDTH = 200;
const MAX_WIDTH = 480;

export default function Dashboard() {
  const [sidebarWidth, setSidebarWidth] = useState(() => {
    const saved = localStorage.getItem(SIDEBAR_WIDTH_KEY);
    return saved ? parseInt(saved, 10) : DEFAULT_WIDTH;
  });
  const { loading, user } = useAuth();

  useEffect(() => {
    localStorage.setItem(SIDEBAR_WIDTH_KEY, sidebarWidth.toString());
  }, [sidebarWidth]);

  if (loading) {
    return <DashboardLayoutSkeleton />;
  }

  if (!user) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="flex flex-col items-center gap-8 p-8 max-w-md w-full">
          <div className="flex flex-col items-center gap-6">
            <h1 className="text-2xl font-semibold tracking-tight text-center">
              Connexion requise
            </h1>
            <p className="text-sm text-muted-foreground text-center max-w-sm">
              Veuillez vous connecter pour accéder à votre espace association.
            </p>
          </div>
          <Button
            onClick={() => {
              window.location.href = getLoginUrl();
            }}
            size="lg"
            className="w-full shadow-lg hover:shadow-xl transition-all"
          >
            Se connecter
          </Button>
        </div>
      </div>
    );
  }

  if (user.role === "service_terrain") {
    return <TerrainMissions />;
  }

  return (
    <SidebarProvider
      style={
        {
          "--sidebar-width": `${sidebarWidth}px`,
        } as CSSProperties
      }
    >
      <DashboardContent setSidebarWidth={setSidebarWidth} />
    </SidebarProvider>
  );
}

function DashboardContent({ setSidebarWidth }: { setSidebarWidth: (width: number) => void }) {
  const { user, logout } = useAuth();
  const { appearance } = useTheme();
  const [location, setLocation] = useLocation();
  const { state, toggleSidebar } = useSidebar();
  const isCollapsed = state === "collapsed";
  const [isResizing, setIsResizing] = useState(false);
  const sidebarRef = useRef<HTMLDivElement>(null);
  const isMobile = useIsMobile();

  const { data: association } = trpc.association.getMyProfile.useQuery();
  const { data: requests } = trpc.request.getMyRequests.useQuery();
  const { data: documents } = trpc.document.getMyDocuments.useQuery();

  const allMenuItems = userSidebarSections.flatMap((section) => section.items);
  const activeMenuItem = allMenuItems.find(item => location.startsWith(item.path));
  const portalTitle = appearance.portalTitle?.trim() || "Portail Associations 973";
  const previewDocumentsReminder =
    typeof window !== "undefined" &&
    new URLSearchParams(window.location.search).get("preview") === "documents-banner";

  useEffect(() => {
    if (isCollapsed) {
      setIsResizing(false);
    }
  }, [isCollapsed]);

  useEffect(() => {
    const handleMouseMove = (e: MouseEvent) => {
      if (!isResizing) return;
      const sidebarLeft = sidebarRef.current?.getBoundingClientRect().left ?? 0;
      const newWidth = e.clientX - sidebarLeft;
      if (newWidth >= MIN_WIDTH && newWidth <= MAX_WIDTH) {
        setSidebarWidth(newWidth);
      }
    };

    const handleMouseUp = () => {
      setIsResizing(false);
    };

    if (isResizing) {
      document.addEventListener("mousemove", handleMouseMove);
      document.addEventListener("mouseup", handleMouseUp);
      document.body.style.cursor = "col-resize";
      document.body.style.userSelect = "none";
    }

    return () => {
      document.removeEventListener("mousemove", handleMouseMove);
      document.removeEventListener("mouseup", handleMouseUp);
      document.body.style.cursor = "";
      document.body.style.userSelect = "";
    };
  }, [isResizing, setSidebarWidth]);

  // Stats
  const pendingRequests = requests?.filter(r => r.status === 'soumise' || r.status === 'en_cours_traitement').length || 0;
  const approvedRequests = requests?.filter(r => r.status === 'validee').length || 0;
  const totalDocuments = documents?.length || 0;
  const shouldShowDocumentsReminder = Boolean(
    previewDocumentsReminder ||
      (
        association?.profileComplete &&
        totalDocuments === 0 &&
        location !== "/dashboard/documents"
      ),
  );

  return (
    <>
      <div className="relative" ref={sidebarRef}>
        <Sidebar collapsible="icon" className="border-r-0" disableTransition={isResizing}>
          <SidebarHeader className="h-16 justify-center">
            <div className="flex items-center gap-3 px-2 transition-all w-full">
              <button
                onClick={toggleSidebar}
                className="h-8 w-8 flex items-center justify-center hover:bg-accent rounded-lg transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-ring shrink-0"
                aria-label="Toggle navigation"
              >
                <PanelLeft className="h-4 w-4 text-muted-foreground" />
              </button>
              {!isCollapsed && (
                <Link href="/" className="flex items-center gap-2 min-w-0">
                  {appearance.logoUrl ? (
                    <img
                      src={appearance.logoUrl}
                      alt={portalTitle}
                      className="h-8 w-8 shrink-0 rounded-md object-contain"
                    />
                  ) : null}
                  <span className="font-semibold tracking-tight truncate text-primary">
                    {portalTitle}
                  </span>
                </Link>
              )}
            </div>
          </SidebarHeader>

          <SidebarContent className="gap-0">
            <div className="px-2 py-2">
              {userSidebarSections.map((section, sectionIndex) => (
                <div key={section.id}>
                  {sectionIndex > 0 ? <SidebarSeparator className="my-2 opacity-70" /> : null}
                  <SidebarGroup className="py-0.5">
                    {!isCollapsed ? (
                      <SidebarGroupLabel
                        className={`px-2 pb-1 text-[10px] font-semibold uppercase tracking-[0.12em] text-muted-foreground/75 ${section.accentClass ?? ""}`}
                      >
                        {section.label}
                      </SidebarGroupLabel>
                    ) : null}
                    <SidebarGroupContent>
                      <SidebarMenu className="px-0 py-0.5">
                        {section.items.map((item) => {
                          const isActive = location === item.path || (item.path !== "/dashboard" && location.startsWith(item.path));
                          return (
                            <SidebarMenuItem key={item.path}>
                              <SidebarMenuButton
                                isActive={isActive}
                                onClick={() => setLocation(item.path)}
                                tooltip={item.label}
                                className="h-9 rounded-xl px-2 font-medium transition-all data-[active=true]:shadow-sm"
                                data-tour-id={tourIdsByPath[item.path]}
                              >
                                <item.icon className={`h-4 w-4 shrink-0 transition-colors ${isActive ? "text-primary" : item.accentClass ?? "text-muted-foreground"}`} />
                                <span className="min-w-0 flex-1 truncate">{item.label}</span>
                              </SidebarMenuButton>
                            </SidebarMenuItem>
                          );
                        })}
                      </SidebarMenu>
                    </SidebarGroupContent>
                  </SidebarGroup>
                </div>
              ))}
            </div>
          </SidebarContent>

          <SidebarFooter className="p-3">
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <button className="flex items-center gap-3 rounded-lg px-1 py-1 hover:bg-accent/50 transition-colors w-full text-left group-data-[collapsible=icon]:justify-center focus:outline-none focus-visible:ring-2 focus-visible:ring-ring">
                  <Avatar className="h-9 w-9 border shrink-0">
                    <AvatarFallback className="text-xs font-medium bg-primary text-primary-foreground">
                      {user?.name?.charAt(0).toUpperCase() || 'U'}
                    </AvatarFallback>
                  </Avatar>
                  <div className="flex-1 min-w-0 group-data-[collapsible=icon]:hidden">
                    <p className="text-sm font-medium truncate leading-none">
                      {user?.name || "Utilisateur"}
                    </p>
                    <p className="text-xs text-muted-foreground truncate mt-1.5">
                      {user?.email || "-"}
                    </p>
                  </div>
                </button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end" className="w-48">
                <DropdownMenuItem onClick={logout} className="cursor-pointer text-destructive focus:text-destructive">
                  <LogOut className="mr-2 h-4 w-4" />
                  <span>Déconnexion</span>
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          </SidebarFooter>
        </Sidebar>
        <div
          className={`absolute top-0 right-0 w-1 h-full cursor-col-resize hover:bg-primary/20 transition-colors ${isCollapsed ? "hidden" : ""}`}
          onMouseDown={() => {
            if (isCollapsed) return;
            setIsResizing(true);
          }}
          style={{ zIndex: 50 }}
        />
      </div>

      <SidebarInset>
        {isMobile && (
          <div className="flex border-b h-14 items-center justify-between bg-background/95 px-2 backdrop-blur supports-[backdrop-filter]:backdrop-blur sticky top-0 z-40">
            <div className="flex items-center gap-2">
              <SidebarTrigger className="h-9 w-9 rounded-lg bg-background" />
              <span className="tracking-tight text-foreground">
                {activeMenuItem?.label ?? "Tableau de bord"}
              </span>
            </div>
          </div>
        )}
        <main className="portal-immersive-main flex-1 p-6">
          <div className="mb-8" data-tour-id="dashboard-welcome">
            <h1 className="text-2xl font-bold mb-2">
              Bienvenue{association?.nomAssociation ? `, ${association.nomAssociation}` : ''} !
            </h1>
            <p className="text-muted-foreground">
              Gérez vos documents et suivez vos demandes depuis votre tableau de bord.
            </p>
          </div>

          {shouldShowDocumentsReminder && (
            <section className="mb-8 rounded-lg border-2 border-amber-300 bg-amber-50 shadow-sm">
              <div className="flex flex-col gap-4 p-5 md:flex-row md:items-center md:justify-between">
                <div className="flex gap-4">
                  <div className="flex h-11 w-11 shrink-0 items-center justify-center rounded-full bg-amber-100 text-amber-700">
                    <AlertTriangle className="h-5 w-5" />
                  </div>
                  <div className="space-y-1">
                    <h2 className="text-lg font-semibold text-amber-950">
                      Documents obligatoires à déposer
                    </h2>
                    <p className="text-sm leading-6 text-amber-900">
                      Pour finaliser votre espace association et accélérer le traitement de vos démarches,
                      merci de déposer vos documents (RIB, statuts, dirigeants, assurance…) dans la rubrique
                      {" "}
                      <span className="font-semibold">Mes documents</span>.
                    </p>
                  </div>
                </div>
                <Link href="/dashboard/documents">
                  <Button className="w-full md:w-auto">
                    <FolderOpen className="mr-2 h-4 w-4" />
                    Aller dans Mes documents
                  </Button>
                </Link>
              </div>
            </section>
          )}

          <section className="mb-10 overflow-hidden rounded-2xl border border-primary/10 bg-gradient-to-r from-primary/10 via-background to-primary/5 shadow-[0_24px_50px_-36px_rgba(15,23,42,0.22)]">
            <div className="border-b px-5 py-5 sm:px-6">
              <div className="flex flex-col gap-3 lg:flex-row lg:items-end lg:justify-between">
                <div className="max-w-2xl space-y-2">
                  <p className="text-sm font-medium text-primary">Parcours principaux</p>
                  <h2 className="text-xl font-semibold tracking-tight sm:text-2xl">
                    Lancez rapidement une réservation de salle ou une demande de matériel
                  </h2>
                  <p className="text-sm text-muted-foreground">
                    Les deux formulaires les plus utilisés du portail sont accessibles ici en priorité, avec un parcours pensé pour aller vite.
                  </p>
                </div>
                <div className="rounded-xl border bg-background/85 px-4 py-2.5 text-sm text-muted-foreground shadow-sm">
                  Commencez par l’action qui correspond à votre besoin du moment.
                </div>
              </div>
            </div>

            <div className="grid gap-5 p-5 sm:p-6 lg:grid-cols-2">
              <Card className="border-primary/25 bg-background/92 shadow-sm">
                <CardHeader className="gap-4 border-b">
                  <div className="flex items-center justify-between gap-4">
                    <div className="flex h-11 w-11 items-center justify-center rounded-xl bg-primary text-primary-foreground shadow-sm">
                      <CalendarDays className="h-6 w-6" />
                    </div>
                    <span className="rounded-full bg-primary/10 px-3 py-1 text-xs font-medium text-primary">
                      Action prioritaire
                    </span>
                  </div>
                  <div className="space-y-2">
                    <CardTitle className="text-xl">Réservation de salle</CardTitle>
                    <CardDescription className="leading-6">
                      Réservez un local, indiquez votre créneau et transmettez rapidement les informations utiles à l'administration.
                    </CardDescription>
                  </div>
                </CardHeader>
                <CardContent className="flex flex-col gap-4 pt-4">
                  <div className="grid gap-3 text-sm text-muted-foreground sm:grid-cols-2">
                    <div className="rounded-lg border bg-background/80 px-4 py-3">
                      <div className="font-medium text-foreground">Créneau et dates</div>
                      <div className="mt-1 text-sm text-muted-foreground">Début, fin et horaires obligatoires</div>
                    </div>
                    <div className="rounded-lg border bg-background/80 px-4 py-3">
                      <div className="font-medium text-foreground">Nombre de participants</div>
                      <div className="mt-1 text-sm text-muted-foreground">Capacité visible pour l'administration</div>
                    </div>
                  </div>
                  <Link href="/dashboard/reservation-salle">
                    <Button className="w-full" size="lg">
                      <Plus className="mr-2 h-4 w-4" />
                      Commencer la réservation
                    </Button>
                  </Link>
                </CardContent>
              </Card>

              <Card className="border-primary/25 bg-background/92 shadow-sm">
                <CardHeader className="gap-4 border-b">
                  <div className="flex items-center justify-between gap-4">
                    <div className="flex h-11 w-11 items-center justify-center rounded-xl bg-primary text-primary-foreground shadow-sm">
                      <Package2 className="h-6 w-6" />
                    </div>
                    <span className="rounded-full bg-primary/10 px-3 py-1 text-xs font-medium text-primary">
                      Action prioritaire
                    </span>
                  </div>
                  <div className="space-y-2">
                    <CardTitle className="text-xl">Demande du matériel événementiel</CardTitle>
                    <CardDescription className="leading-6">
                      Remplissez la fiche officielle avec les informations de l'association déjà préremplies pour gagner du temps.
                    </CardDescription>
                  </div>
                </CardHeader>
                <CardContent className="flex flex-col gap-4 pt-4">
                  <div className="grid gap-3 text-sm text-muted-foreground sm:grid-cols-2">
                    <div className="rounded-lg border bg-background/80 px-4 py-3">
                      <div className="font-medium text-foreground">Association préremplie</div>
                      <div className="mt-1 text-sm text-muted-foreground">Moins d’informations à ressaisir</div>
                    </div>
                    <div className="rounded-lg border bg-background/80 px-4 py-3">
                      <div className="font-medium text-foreground">Cadre DSU séparé</div>
                      <div className="mt-1 text-sm text-muted-foreground">Traitement réservé à l’administration</div>
                    </div>
                  </div>
                  <Link href="/dashboard/materiel-evenementiel">
                    <Button className="w-full" size="lg">
                      <Plus className="mr-2 h-4 w-4" />
                      Commencer la demande
                    </Button>
                  </Link>
                </CardContent>
              </Card>
            </div>
          </section>

          {/* Quick stats */}
          <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4 mb-8">
            <PortalMetricTile
              label="Documents"
              value={totalDocuments}
              detail="documents stockés"
            />
            <PortalMetricTile
              label="En cours"
              value={pendingRequests}
              detail="demandes en attente"
              tone="warning"
            />
            <PortalMetricTile
              label="Validées"
              value={<span className="text-emerald-600">{approvedRequests}</span>}
              detail="demandes approuvées"
              tone="success"
            />
            <PortalMetricTile
              label="Profil"
              value={association?.profileComplete ? '100%' : '0%'}
              detail={association?.profileComplete ? 'Profil complet' : 'À compléter'}
              tone="info"
            />
          </div>

          <div className="mb-6 mt-10">
            <h2 className="text-lg font-semibold">Autres raccourcis</h2>
            <p className="text-sm text-muted-foreground">
              Retrouvez ici les autres actions utiles pour gérer votre espace association.
            </p>
          </div>

          {/* Quick actions */}
          <div className="grid gap-5 md:grid-cols-2 lg:grid-cols-3">
            {!association && (
              <Card className="border-primary/20 bg-primary/5">
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <Building2 className="h-5 w-5 text-primary" />
                    Complétez votre profil
                  </CardTitle>
                  <CardDescription>
                    Renseignez les informations de votre association pour pouvoir soumettre des demandes.
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  <Link href="/dashboard/profile">
                    <Button className="w-full">
                      <Plus className="mr-2 h-4 w-4" />
                      Créer mon profil
                    </Button>
                  </Link>
                </CardContent>
              </Card>
            )}

            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <FolderOpen className="h-5 w-5 text-primary" />
                  Gérer mes documents
                </CardTitle>
                <CardDescription>
                  Téléversez et organisez vos documents administratifs.
                </CardDescription>
              </CardHeader>
              <CardContent>
                <Link href="/dashboard/documents">
                  <Button variant="outline" className="w-full">
                    Voir mes documents
                  </Button>
                </Link>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <FileText className="h-5 w-5 text-primary" />
                  Nouvelle demande
                </CardTitle>
                <CardDescription>
                  Créez une nouvelle demande de subvention ou d'agrément.
                </CardDescription>
              </CardHeader>
              <CardContent>
                <Link href="/dashboard/requests/new">
                  <Button variant="outline" className="w-full">
                    <Plus className="mr-2 h-4 w-4" />
                    Créer une demande
                  </Button>
                </Link>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <ClipboardList className="h-5 w-5 text-primary" />
                  Suivre mes demandes
                </CardTitle>
                <CardDescription>
                  Consultez l'état d'avancement de vos demandes en cours.
                </CardDescription>
              </CardHeader>
              <CardContent>
                <Link href="/dashboard/requests">
                  <Button variant="outline" className="w-full">
                    Voir mes demandes
                  </Button>
                </Link>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Users className="h-5 w-5 text-primary" />
                  Annuaire des associations
                </CardTitle>
                <CardDescription>
                  Consultez le bordereau des associations, même avant l’activation de leur espace.
                </CardDescription>
              </CardHeader>
              <CardContent>
                <Link href="/dashboard/associations">
                  <Button variant="outline" className="w-full">
                    Voir l'annuaire
                  </Button>
                </Link>
              </CardContent>
            </Card>
          </div>

          {/* Recent requests */}
          {requests && requests.length > 0 && (
            <div className="mt-8 space-y-4">
              <PortalSectionIntro
                eyebrow="Suivi"
                title="Demandes récentes"
                description="Retrouvez vos derniers dossiers sans repasser par toute la liste."
              />
              <div className="space-y-3">
                {requests.slice(0, 5).map(request => (
                  <Card key={request.id} className="overflow-hidden border-slate-200 bg-white/95 p-3.5 shadow-sm transition-all duration-200 hover:-translate-y-0.5 hover:shadow-md">
                    <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                      <div className="flex-1 min-w-0">
                        <p className="font-medium truncate">{request.titre}</p>
                        <p className="text-sm text-muted-foreground">
                          {request.type.replace(/_/g, ' ')}
                        </p>
                      </div>
                      <div className="flex flex-wrap items-center gap-2">
                        <StatusBadge status={request.status} />
                        <Link href={`/dashboard/requests/${request.id}`}>
                          <Button variant="outline" size="sm">
                            <Eye className="mr-1 h-3 w-3" />
                            Voir
                          </Button>
                        </Link>
                        {['brouillon', 'information_complementaire'].includes(request.status) && (
                          <Link href={`/dashboard/requests/${request.id}/edit`}>
                            <Button variant="default" size="sm">
                              <Edit className="mr-1 h-3 w-3" />
                              Éditer
                            </Button>
                          </Link>
                        )}
                      </div>
                    </div>
                  </Card>
                ))}
              </div>
            </div>
          )}
        </main>
      </SidebarInset>
    </>
  );
}

function StatusBadge({ status }: { status: string }) {
  const statusConfig: Record<string, { label: string; className: string }> = {
    brouillon: { label: 'Brouillon', className: 'bg-gray-100 text-gray-700' },
    soumise: { label: 'Soumise', className: 'bg-blue-100 text-blue-700' },
    en_cours_traitement: { label: 'En cours', className: 'bg-yellow-100 text-yellow-700' },
    information_complementaire: { label: 'Info requise', className: 'bg-orange-100 text-orange-700' },
    validee: { label: 'Validée', className: 'bg-green-100 text-green-700' },
    refusee: { label: 'Refusée', className: 'bg-red-100 text-red-700' },
  };

  const config = statusConfig[status] || { label: status, className: 'bg-gray-100 text-gray-700' };

  return (
    <span className={`px-2 py-1 rounded-full text-xs font-medium ${config.className}`}>
      {config.label}
    </span>
  );
}
