import { useAuth } from "@/_core/hooks/useAuth";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { buildMaterialReturnFinalPdfViewerHref } from "@/lib/materialReturnFinalPdf";
import { trpc } from "@/lib/trpc";
import { AlertTriangle, ArrowUpRight, CalendarClock, CheckCircle2, ClipboardList, Download, Loader2, LogOut, MapPin } from "lucide-react";

const boardStateClasses: Record<string, string> = {
  planifie: "bg-blue-100 text-blue-700 border-blue-200",
  terrain: "bg-amber-100 text-amber-800 border-amber-200",
  retard: "bg-red-100 text-red-700 border-red-200",
  litige: "bg-orange-100 text-orange-800 border-orange-200",
  conforme: "bg-green-100 text-green-700 border-green-200",
};

const uploadLinkStateLabels: Record<string, string> = {
  active: "Lien actif",
  expired: "Lien expiré",
  closed: "Mission clôturée",
};

function formatDate(value: Date | string | null | undefined) {
  if (!value) return "-";
  try {
    return new Date(value).toLocaleDateString("fr-FR", {
      day: "2-digit",
      month: "long",
      year: "numeric",
    });
  } catch {
    return String(value);
  }
}

function formatDateTime(value: Date | string | null | undefined) {
  if (!value) return "-";
  try {
    return new Date(value).toLocaleString("fr-FR", {
      day: "2-digit",
      month: "long",
      year: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    });
  } catch {
    return String(value);
  }
}

export default function TerrainMissions() {
  const { user, loading, logout } = useAuth({ redirectOnUnauthenticated: true });
  const { data, isLoading } = trpc.materialReturn.listMine.useQuery(undefined, {
    enabled: !loading && user?.role === "service_terrain",
    refetchInterval: 30_000,
  });

  const missions = data || [];
  const dueNow = missions.filter((entry) => entry.boardState === "terrain" || entry.boardState === "retard");
  const planned = missions.filter((entry) => entry.boardState === "planifie");
  const completed = missions.filter((entry) => entry.boardState === "conforme" || entry.boardState === "litige");

  if (loading || isLoading) {
    return (
      <div className="min-h-screen bg-muted/30 flex items-center justify-center">
        <Loader2 className="h-6 w-6 animate-spin text-primary" />
      </div>
    );
  }

  if (!user || user.role !== "service_terrain") {
    return (
      <div className="min-h-screen bg-muted/30 flex items-center justify-center p-6">
        <Card className="max-w-lg w-full">
          <CardHeader>
            <CardTitle>Accès non disponible</CardTitle>
            <CardDescription>
              Cet espace est réservé aux comptes du service terrain / récupération.
            </CardDescription>
          </CardHeader>
        </Card>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-muted/30">
      <header className="border-b bg-background/95 backdrop-blur">
        <div className="container flex flex-col gap-4 py-6 md:flex-row md:items-center md:justify-between">
          <div>
            <p className="text-sm font-medium text-primary">Service terrain / récupération</p>
            <h1 className="text-2xl font-semibold tracking-tight">Mes missions matériel CCDS</h1>
            <p className="text-sm text-muted-foreground mt-1">
              Retrouve les récupérations qui te sont affectées, ouvre le lien terrain et garde une trace de ce qui a déjà été validé.
            </p>
          </div>
          <div className="flex items-center gap-3">
            <div className="text-right">
              <p className="text-sm font-medium">{user?.name || "Compte terrain"}</p>
              <p className="text-xs text-muted-foreground">{user?.email || "Email non renseigné"}</p>
            </div>
            <Button variant="outline" onClick={() => logout()}>
              <LogOut className="mr-2 h-4 w-4" />
              Déconnexion
            </Button>
          </div>
        </div>
      </header>

      <main className="container py-6 space-y-6">
        <div className="grid gap-4 md:grid-cols-3">
          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-medium">À traiter</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{dueNow.length}</div>
              <p className="text-xs text-muted-foreground">Missions à ouvrir ou à finaliser maintenant</p>
            </CardContent>
          </Card>
          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-medium">Planifiées</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{planned.length}</div>
              <p className="text-xs text-muted-foreground">Récupérations prévues dans les prochains jours</p>
            </CardContent>
          </Card>
          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-medium">Traitées</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{completed.length}</div>
              <p className="text-xs text-muted-foreground">Retours déjà validés depuis ce compte terrain</p>
            </CardContent>
          </Card>
        </div>

        <Card className="border-primary/10">
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <ClipboardList className="h-5 w-5 text-primary" />
              Missions de récupération
            </CardTitle>
            <CardDescription>
              Les dossiers remontent ici dès que ton adresse email est affectée au service terrain, puis restent visibles après validation.
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            {missions.length === 0 ? (
              <div className="rounded-lg border border-dashed px-6 py-10 text-center">
                <ClipboardList className="mx-auto h-10 w-10 text-muted-foreground/50" />
                <p className="mt-4 font-medium">Aucune mission terrain pour le moment</p>
                <p className="mt-1 text-sm text-muted-foreground">
                  Dès qu’une demande de matériel te sera affectée, elle apparaîtra ici automatiquement.
                </p>
              </div>
            ) : (
              missions.map((entry) => (
                <div key={entry.requestId} className="rounded-lg border bg-background p-4">
                  <div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
                    <div className="space-y-2">
                      <div className="flex flex-wrap items-center gap-2">
                        <h2 className="font-semibold">{entry.title}</h2>
                        <Badge className={boardStateClasses[entry.boardState] || "bg-slate-100 text-slate-700 border-slate-200"}>
                          {entry.boardStateLabel}
                        </Badge>
                        <Badge variant="outline">
                          {uploadLinkStateLabels[entry.uploadLinkState] || entry.uploadLinkState}
                        </Badge>
                        {entry.issueFlag ? (
                          <Badge variant="destructive">Réserves / litige</Badge>
                        ) : null}
                      </div>
                      <p className="text-sm text-muted-foreground">{entry.associationName}</p>
                      <div className="grid gap-2 pt-1 text-sm text-muted-foreground md:grid-cols-2">
                        <p className="flex items-center gap-2">
                          <MapPin className="h-4 w-4" />
                          {entry.commune || "Commune non renseignée"}
                        </p>
                        <p className="flex items-center gap-2">
                          <CalendarClock className="h-4 w-4" />
                          Restitution prévue le {formatDate(entry.restitutionDate)}
                        </p>
                      </div>
                      <div className="grid gap-2 pt-1 text-sm md:grid-cols-2">
                        <p>
                          <span className="text-muted-foreground">Service :</span>{" "}
                          <span className="font-medium">{entry.serviceLabel || "-"}</span>
                        </p>
                        <p>
                          <span className="text-muted-foreground">Lien valable jusqu’au :</span>{" "}
                          <span className="font-medium">{formatDate(entry.uploadTokenExpiresAt)}</span>
                        </p>
                        <p>
                          <span className="text-muted-foreground">Dernière relance :</span>{" "}
                          <span className="font-medium">{formatDateTime(entry.lastReminderSentAt)}</span>
                        </p>
                        <p>
                          <span className="text-muted-foreground">Dernière validation :</span>{" "}
                          <span className="font-medium">{formatDateTime(entry.validatedAt || entry.uploadedAt)}</span>
                        </p>
                      </div>
                      {entry.uploadLinkState === "expired" ? (
                        <p className="text-sm text-red-700 flex items-center gap-2 pt-1">
                          <AlertTriangle className="h-4 w-4" />
                          Le lien terrain a expiré. La logistique doit le réactiver avant une nouvelle validation.
                        </p>
                      ) : null}
                      {entry.uploadLinkState === "closed" ? (
                        <p className="text-sm text-green-700 flex items-center gap-2 pt-1">
                          <CheckCircle2 className="h-4 w-4" />
                          Mission déjà finalisée depuis le terrain.
                        </p>
                      ) : null}
                    </div>

                    <div className="flex w-full flex-col gap-2 lg:w-auto">
                      {entry.uploadLink ? (
                        <a href={entry.uploadLink} target="_blank" rel="noopener noreferrer">
                          <Button className="w-full lg:w-auto" disabled={entry.uploadLinkState === "expired"}>
                            <ArrowUpRight className="mr-2 h-4 w-4" />
                            Ouvrir le lien terrain
                          </Button>
                        </a>
                      ) : null}
                      {entry.finalPdfUrl ? (
                        <a
                          href={buildMaterialReturnFinalPdfViewerHref({
                            url: entry.finalPdfUrl,
                            returnTo: "/terrain",
                            title: "Consulter la fiche finale de mission",
                            downloadName: `fiche-finale-mission-${entry.requestId}.pdf`,
                          })}
                        >
                          <Button variant="outline" className="w-full lg:w-auto">
                            <Download className="mr-2 h-4 w-4" />
                            Télécharger la fiche finale
                          </Button>
                        </a>
                      ) : null}
                    </div>
                  </div>
                </div>
              ))
            )}
          </CardContent>
        </Card>
      </main>
    </div>
  );
}
