"use client";

import { useState } from "react";
import { useTranslations } from "next-intl";
import { useRouter } from "next/navigation";
import { GitFork } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import { toast } from "sonner";

export function ForkCollectionButton({ collectionId }: { collectionId: string }) {
  const t = useTranslations("collections");
  const tSocial = useTranslations("social");
  const [forking, setForking] = useState(false);
  const router = useRouter();

  async function handleFork() {
    setForking(true);
    try {
      const res = await fetch(`/api/v1/collections/${collectionId}/fork`, { method: "POST" });
      if (!res.ok) {
        const data = await res.json() as { error?: string };
        throw new Error(data.error ?? t("forkFailed"));
      }
      const { id } = await res.json() as { id: string };
      toast.success(tSocial("collectionForked"));
      router.push(`/collections/${id}`);
    } catch (err) {
      toast.error(err instanceof Error ? err.message : t("forkFailed"));
      setForking(false);
    }
  }

  return (
    <TooltipProvider>
      <Tooltip>
        <TooltipTrigger render={
          <Button variant="ghost" size="icon" onClick={() => { void handleFork(); }} disabled={forking} aria-label={t("forkCollection")}>
            <GitFork className="h-4 w-4" />
          </Button>
        } />
        <TooltipContent>{forking ? t("forking") : t("forkCollection")}</TooltipContent>
      </Tooltip>
    </TooltipProvider>
  );
}
