"use client";

import { useRouter } from "next/navigation";
import { useState } from "react";
import { ChevronDown, Clapperboard, ImageIcon, Plus, Scissors } from "lucide-react";
import { useTranslations } from "next-intl";

import { Button } from "@/components/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import type { ProjectType } from "@/lib/projects";

interface NewProjectMenuProps {
  triggerLabel?: string;
  triggerClassName?: string;
  align?: "start" | "center" | "end";
}

export function NewProjectMenu({
  triggerLabel,
  triggerClassName,
  align = "end",
}: NewProjectMenuProps) {
  const t = useTranslations("auto.componentsDashboardNewProjectMenu");
  const router = useRouter();
  const [isCreating, setIsCreating] = useState(false);
  const label = triggerLabel ?? t("newProject");

  const createProject = async (type: ProjectType) => {
    setIsCreating(true);
    try {
      const response = await fetch("/api/projects", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ type }),
      });

      const data = (await response.json()) as {
        project?: { id: string; type: ProjectType };
        error?: string;
      };

      if (!response.ok || !data.project) {
        return;
      }

      if (data.project.type === "video") {
        router.push(`/studio/video/${data.project.id}`);
        return;
      }
      if (data.project.type === "image") {
        router.push(`/studio/image/${data.project.id}`);
        return;
      }
      router.push("/studio/trimmer");
    } finally {
      setIsCreating(false);
    }
  };

  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <Button className={triggerClassName} disabled={isCreating}>
          <Plus className="h-4 w-4" aria-hidden />
          {isCreating ? t("creating") : label}
          <ChevronDown className="h-4 w-4 opacity-80" aria-hidden />
        </Button>
      </DropdownMenuTrigger>
      <DropdownMenuContent align={align} className="w-56">
        <DropdownMenuItem
          className="cursor-pointer gap-2"
          onClick={() => router.push("/studio/video/new")}
        >
          <Clapperboard className="h-4 w-4 text-primary-600" />
          {t("videoProject")}
        </DropdownMenuItem>
        <DropdownMenuItem
          className="cursor-pointer gap-2"
          onClick={() => createProject("image")}
        >
          <ImageIcon className="h-4 w-4 text-violet-600" />
          {t("imageProject")}
        </DropdownMenuItem>
        <DropdownMenuItem
          className="cursor-pointer gap-2"
          onClick={() => createProject("trimmer")}
        >
          <Scissors className="h-4 w-4 text-amber-600" />
          {t("trimCropVideo")}
        </DropdownMenuItem>
      </DropdownMenuContent>
    </DropdownMenu>
  );
}
