import { ArrowLeft } from "lucide-react";
import { Link, useLocation } from "wouter";

import { Button } from "@/components/ui/button";

type PublicDocumentBackLinkProps = {
  fallbackHref?: string;
};

export default function PublicDocumentBackLink({
  fallbackHref = "/",
}: PublicDocumentBackLinkProps) {
  const [location] = useLocation();
  const queryIndex = location.indexOf("?");
  const searchParams = new URLSearchParams(queryIndex >= 0 ? location.slice(queryIndex + 1) : "");
  const rawReturnTo = searchParams.get("returnTo") || "";
  const returnTo = rawReturnTo.startsWith("/") ? rawReturnTo : fallbackHref;
  const label = returnTo.startsWith("/admin") ? "Retour à l'administration" : "Retour";

  return (
    <Link href={returnTo}>
      <Button variant="outline" className="gap-2">
        <ArrowLeft className="h-4 w-4" />
        {label}
      </Button>
    </Link>
  );
}
