import { useAuth } from "@/_core/hooks/useAuth";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { ArrowLeft, Download, ExternalLink, FileText, Loader2, Printer } from "lucide-react";
import { useMemo } from "react";
import { Link, useLocation } from "wouter";

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

export default function StatsReportArchiveView() {
  const { user, loading } = useAuth({ redirectOnUnauthenticated: true });
  const [location] = useLocation();

  const searchParams = useMemo(() => {
    const queryIndex = location.indexOf("?");
    return new URLSearchParams(queryIndex >= 0 ? location.slice(queryIndex + 1) : "");
  }, [location]);

  const reportUrl = searchParams.get("url") || "";
  const reportName = searchParams.get("name") || "rapport-statistiques.pdf";
  const periodLabel = searchParams.get("period") || "Rapport statistique";
  const generatedAt = searchParams.get("generatedAt");
  const returnTo = "/admin?tab=analytics";

  const canAccess =
    user?.role === "accueil" || user?.role === "admin" || user?.role === "super_admin";

  if (loading) {
    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 || !canAccess) {
    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>
              Cette consultation est réservée à l’accueil, aux administrateurs et au super administrateur.
            </CardDescription>
          </CardHeader>
        </Card>
      </div>
    );
  }

  if (!reportUrl) {
    return (
      <div className="min-h-screen bg-muted/30 py-8">
        <main className="container max-w-3xl space-y-6">
          <div className="flex items-center justify-start">
            <Link href={returnTo}>
              <Button variant="outline" className="gap-2">
                <ArrowLeft className="h-4 w-4" />
                Retour à l’historique
              </Button>
            </Link>
          </div>

          <Card>
            <CardHeader>
              <CardTitle>Rapport introuvable</CardTitle>
              <CardDescription>
                Le lien du rapport archivé est manquant ou invalide.
              </CardDescription>
            </CardHeader>
          </Card>
        </main>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-muted/30 py-8">
      <main className="container max-w-5xl space-y-6">
        <div className="flex items-center justify-start">
          <Link href={returnTo}>
            <Button variant="outline" className="gap-2">
              <ArrowLeft className="h-4 w-4" />
              Retour à l’historique
            </Button>
          </Link>
        </div>

        <Card className="border-primary/20">
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <FileText className="h-5 w-5 text-primary" />
              {periodLabel}
            </CardTitle>
            <CardDescription>
              Consulte le rapport archivé, puis reviens facilement à l’historique des exports statistiques.
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="rounded-lg border bg-white p-4 space-y-2">
              <p className="text-sm">
                <span className="text-muted-foreground">Fichier :</span>{" "}
                <span className="font-medium">{reportName}</span>
              </p>
              <p className="text-sm">
                <span className="text-muted-foreground">Généré le :</span>{" "}
                <span className="font-medium">{formatDateTime(generatedAt)}</span>
              </p>
            </div>

            <div className="flex flex-wrap gap-3">
              <Link href={returnTo}>
                <Button variant="outline">
                  <ArrowLeft className="mr-2 h-4 w-4" />
                  Retour à l’historique
                </Button>
              </Link>
              <Button type="button" variant="outline" onClick={() => window.open(reportUrl, "_blank", "noopener,noreferrer")}>
                <ExternalLink className="mr-2 h-4 w-4" />
                Ouvrir dans un nouvel onglet
              </Button>
              <Button type="button" variant="outline" onClick={() => window.open(reportUrl, "_blank", "noopener,noreferrer")?.print()}>
                <Printer className="mr-2 h-4 w-4" />
                Imprimer
              </Button>
              <a href={reportUrl} target="_blank" rel="noopener noreferrer" download={reportName}>
                <Button>
                  <Download className="mr-2 h-4 w-4" />
                  Télécharger le PDF
                </Button>
              </a>
            </div>

            <div className="rounded-lg border bg-white overflow-hidden">
              <div className="flex flex-col gap-3 border-b bg-muted/20 px-4 py-3 md:flex-row md:items-center md:justify-between">
                <div>
                  <p className="text-sm font-semibold">Prévisualisation du rapport</p>
                  <p className="text-xs text-muted-foreground">
                    Le bouton retour reste disponible pendant toute la consultation.
                  </p>
                </div>
                <Link href={returnTo}>
                  <Button variant="outline" size="sm">
                    <ArrowLeft className="mr-2 h-4 w-4" />
                    Retour
                  </Button>
                </Link>
              </div>
              <iframe
                src={reportUrl}
                title={periodLabel}
                className="h-[74vh] w-full bg-white"
              />
            </div>

            <div className="flex justify-end">
              <Link href={returnTo}>
                <Button variant="outline">
                  <ArrowLeft className="mr-2 h-4 w-4" />
                  Retour à l’historique
                </Button>
              </Link>
            </div>
          </CardContent>
        </Card>
      </main>
    </div>
  );
}
