"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { MoreVertical, ImageIcon, RefreshCw, Trash2, Loader2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { regenerateAction, deleteEpisodeAction } from "@/app/(app)/episodes/actions";

export function EpisodeActions({ episodeId }: { episodeId: string }) {
  const router = useRouter();
  const [busy, setBusy] = useState(false);

  async function regen(type: "art" | "full") {
    setBusy(true);
    const res = await regenerateAction(episodeId, type);
    setBusy(false);
    if (res.ok) {
      toast.success(type === "art" ? "Regenerating cover art…" : "Regenerating episode…");
      router.refresh();
    } else {
      toast.error(res.error ?? "Could not regenerate");
    }
  }

  async function del() {
    if (!confirm("Delete this episode? This cannot be undone.")) return;
    const res = await deleteEpisodeAction(episodeId);
    if (res.ok) {
      toast.success("Episode deleted");
      router.push("/episodes");
      router.refresh();
    } else {
      toast.error(res.error ?? "Could not delete");
    }
  }

  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <Button variant="outline" size="icon" disabled={busy}>
          {busy ? <Loader2 className="h-4 w-4 animate-spin" /> : <MoreVertical className="h-4 w-4" />}
        </Button>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="end" className="w-52">
        <DropdownMenuItem onSelect={() => regen("art")}>
          <ImageIcon className="h-4 w-4" /> Regenerate cover art
        </DropdownMenuItem>
        <DropdownMenuItem onSelect={() => regen("full")}>
          <RefreshCw className="h-4 w-4" /> Regenerate everything
        </DropdownMenuItem>
        <DropdownMenuSeparator />
        <DropdownMenuItem onSelect={del} className="text-destructive focus:text-destructive">
          <Trash2 className="h-4 w-4" /> Delete episode
        </DropdownMenuItem>
      </DropdownMenuContent>
    </DropdownMenu>
  );
}
