"use client";

import { useMemo, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { Clapperboard, Search, Sparkles } from "lucide-react";
import { useTranslations } from "next-intl";

import { SceneBrowserModal } from "@/components/studio/SceneBrowserModal";
import { VideoNewOptionCard } from "@/components/studio/video/VideoNewOptionCard";
import { VideoNewPresetCard } from "@/components/studio/video/VideoNewPresetCard";
import { toast } from "@/components/ui/use-toast";
import { cn } from "@/lib/utils";
import { TEMPLATE_GALLERY_ITEMS } from "@/components/sections/template-gallery-data";
import { createVideoProject } from "@/lib/create-video-project";

export function VideoProjectNewContent() {
  const t = useTranslations("auto.componentsStudioVideoVideoProjectNewContent");
  const router = useRouter();
  const [sceneModalOpen, setSceneModalOpen] = useState(false);
  const [loadingKey, setLoadingKey] = useState<string | null>(null);
  const [search, setSearch] = useState("");

  const presets = useMemo(() => {
    const query = search.trim().toLowerCase();
    if (!query) return TEMPLATE_GALLERY_ITEMS;
    return TEMPLATE_GALLERY_ITEMS.filter((item) =>
      item.name.toLowerCase().includes(query)
    );
  }, [search]);

  const startProject = async (
    key: string,
    options?: { name?: string; presetId?: string }
  ) => {
    setLoadingKey(key);
    const result = await createVideoProject(options);
    setLoadingKey(null);

    if (!result.ok) {
      toast({ title: result.error });
      return;
    }

    router.push(`/studio/video/${result.projectId}`);
  };

  return (
    <>
      <header className="flex items-center gap-3 border-b border-gray-100 bg-white px-6 py-4">
        <Link
          href="/dashboard"
          className="flex items-center gap-2 rounded-lg focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-600"
        >
          <span className="flex h-9 w-9 items-center justify-center rounded-lg bg-blue-600 text-white">
            <Sparkles className="h-5 w-5" aria-hidden />
          </span>
          <span className="font-heading text-lg font-bold text-neutral-900">
            FlatRender
          </span>
        </Link>
        <span className="text-sm text-gray-400" aria-hidden>
          /
        </span>
        <span className="text-sm font-medium text-gray-600">{t("breadcrumbCreate")}</span>
      </header>

      <div className="mx-auto max-w-6xl px-4 pb-16 sm:px-6 lg:px-8">
        <h1 className="mt-12 text-center font-heading text-2xl font-semibold text-neutral-900">
          {t("heading")}
        </h1>

        <div className="mx-auto mt-8 grid max-w-2xl grid-cols-1 gap-6 sm:grid-cols-2">
          <VideoNewOptionCard
            title={t("selectScenesTitle")}
            description={t("selectScenesDescription")}
            gradientFrom="from-blue-100"
            gradientTo="to-violet-100"
            icon={Clapperboard}
            iconClassName="text-blue-500"
            isLoading={loadingKey === "scenes"}
            onClick={() => setSceneModalOpen(true)}
          />
          <VideoNewOptionCard
            title={t("createWithAiTitle")}
            description={t("createWithAiDescription")}
            gradientFrom="from-violet-100"
            gradientTo="to-pink-100"
            icon={Sparkles}
            iconClassName="text-violet-500"
            isLoading={loadingKey === "ai"}
            onClick={() => void startProject("ai", { name: t("aiProjectName") })}
          />
        </div>

        <div className="relative my-10">
          <div className="absolute inset-0 flex items-center" aria-hidden>
            <div className="w-full border-t border-gray-200" />
          </div>
          <div className="relative flex justify-center">
            <span className="bg-gray-50 px-4 text-sm font-medium text-gray-400">
              {t("or")}
            </span>
          </div>
        </div>

        <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
          <h2 className="font-semibold text-gray-900">{t("startWithPresets")}</h2>
          <div className="relative w-full sm:max-w-xs">
            <Search
              className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"
              aria-hidden
            />
            <input
              type="search"
              placeholder={t("searchPresetsPlaceholder")}
              value={search}
              onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
                setSearch(e.target.value)
              }
              className={cn(
                "flex h-10 w-full rounded-lg border border-gray-200 bg-white px-3 py-2 pl-9 text-sm",
                "placeholder:text-gray-400 focus-visible:outline-none focus-visible:ring-2",
                "focus-visible:ring-blue-600 focus-visible:ring-offset-2"
              )}
            />
          </div>
        </div>

        <div className="mt-6 flex gap-4 overflow-x-auto pb-2 scroll-smooth [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
          {presets.map((preset) => (
            <VideoNewPresetCard
              key={preset.id}
              preset={preset}
              onClick={() => router.push(`/templates/${preset.id}`)}
            />
          ))}
        </div>
      </div>

      <SceneBrowserModal
        open={sceneModalOpen}
        onOpenChange={setSceneModalOpen}
        onScenesAdd={(scenes) => {
          // On the new-project page use the first selected scene name for the project
          const firstName = scenes[0]?.name ?? t("newVideoName");
          void (async () => {
            setLoadingKey("scenes");
            const result = await createVideoProject({
              name: firstName,
              initialSceneName: firstName,
            });
            setLoadingKey(null);
            if (!result.ok) {
              toast({ title: result.error });
              return;
            }
            router.push(`/studio/video/${result.projectId}`);
          })();
        }}
      />
    </>
  );
}
