"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { useTranslations } from "next-intl";
import { Clapperboard, Heart, Loader2 } from "lucide-react";

import { StatDot, TemplateDetailRating } from "@/components/templates/TemplateDetailRating";
import { toast } from "@/components/ui/use-toast";
import {
  createProjectFromTemplate,
  studioPathForProject,
} from "@/lib/create-project-from-template";
import {
  getVideoTemplateCategoryLabel,
  getVideoTemplateStyleImageSrc,
  TEMPLATE_STYLE_COUNT,
  toProjectTemplate,
  type TemplateDetailAspectRatio,
  type VideoCatalogTemplate,
} from "@/lib/video-templates-catalog";
import { cn } from "@/lib/utils";

const STYLE_LABEL_KEYS = [
  "styleClassic",
  "styleModern",
  "styleBold",
  "styleMinimal",
] as const;

interface TemplateDetailInfoProps {
  template: VideoCatalogTemplate;
  selectedAspect: TemplateDetailAspectRatio;
}

export function TemplateDetailInfo({ template, selectedAspect }: TemplateDetailInfoProps) {
  const t = useTranslations("auto.componentsTemplatesTemplateDetailInfo");
  const router = useRouter();
  const [selectedStyle, setSelectedStyle] = useState(0);
  const [isFavorite, setIsFavorite] = useState(false);
  const [isCreating, setIsCreating] = useState(false);

  const categoryLabel = getVideoTemplateCategoryLabel(template.videoCategory);
  const durationLabel =
    template.durationType === "flexible" ? t("durationFlexible") : t("durationFixed");

  const handleCreate = async () => {
    setIsCreating(true);
    // Build the variant matching the selected aspect (its content project id); fall
    // back to the template id (slug) which the API resolves to a default variant.
    const variant = template.variants?.find((v) => v.aspect === selectedAspect);
    const base = toProjectTemplate(template);
    const result = await createProjectFromTemplate({
      ...base,
      id: variant?.projectId ?? base.id,
    });

    if (!result.ok) {
      setIsCreating(false);
      if (result.status === 401) {
        router.push(`/auth?next=${encodeURIComponent(`/templates/${template.id}`)}`);
        return;
      }
      if (result.error.includes("Supabase is not configured")) {
        router.push("/studio/video/new");
        return;
      }
      toast({ title: t("createError", { error: result.error }) });
      return;
    }

    router.push(studioPathForProject(result.project.id, result.project.type));
  };

  return (
    <div>
      <h1 className="font-heading text-2xl font-bold text-gray-900">{template.name}</h1>

      <div className="mt-1 flex flex-wrap items-center gap-3 text-sm text-gray-500">
        <span>{t("sceneCount", { count: template.sceneCount })}</span>
        <StatDot />
        <span>{categoryLabel}</span>
        <StatDot />
        <span>{durationLabel}</span>
        <StatDot />
        <span>{selectedAspect}</span>
      </div>

      <TemplateDetailRating />

      <p className="mt-3 text-sm leading-relaxed text-gray-700">
        {template.description ?? t("fallbackDescription")}
      </p>

      <div className="mt-5">
        <p className="text-sm font-semibold text-gray-700">
          {t("availableStyles", { count: TEMPLATE_STYLE_COUNT })}
        </p>
        <div className="mt-3 flex gap-3 overflow-x-auto pb-2 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
          {Array.from({ length: TEMPLATE_STYLE_COUNT }).map((_, index) => (
            <button
              key={index}
              type="button"
              onClick={() => setSelectedStyle(index)}
              className="w-[120px] shrink-0 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-600 focus-visible:ring-offset-2"
            >
              <div
                className={cn(
                  "overflow-hidden rounded-xl border-2 transition-colors",
                  selectedStyle === index
                    ? "border-blue-600"
                    : "border-transparent"
                )}
              >
                <div className="aspect-video bg-gray-100">
                  {/* eslint-disable-next-line @next/next/no-img-element */}
                  <img
                    src={getVideoTemplateStyleImageSrc(template.id, index)}
                    alt=""
                    className="h-full w-full object-cover"
                  />
                </div>
              </div>
              <p className="mt-1 truncate text-center text-[10px] text-gray-600">
                {t(STYLE_LABEL_KEYS[index] ?? "styleClassic")}
              </p>
            </button>
          ))}
        </div>
      </div>

      <div className="mt-6 flex gap-3">
        <button
          type="button"
          onClick={() => void handleCreate()}
          disabled={isCreating}
          className="flex h-12 flex-1 items-center justify-center gap-2 rounded-xl bg-blue-600 text-sm font-semibold text-white transition-colors hover:bg-blue-700 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-600 focus-visible:ring-offset-2 disabled:opacity-70"
        >
          {isCreating ? (
            <Loader2 className="h-5 w-5 animate-spin" aria-hidden />
          ) : (
            <Clapperboard className="h-5 w-5" aria-hidden />
          )}
          {t("createNow")}
        </button>
        <button
          type="button"
          onClick={() => setIsFavorite((value) => !value)}
          aria-label={isFavorite ? t("removeFromFavorites") : t("addToFavorites")}
          aria-pressed={isFavorite}
          className="flex h-12 w-12 shrink-0 items-center justify-center rounded-xl border border-gray-200 transition-colors hover:border-rose-300 hover:bg-rose-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-600 focus-visible:ring-offset-2"
        >
          <Heart
            className={cn(
              "h-5 w-5",
              isFavorite ? "fill-rose-500 text-rose-500" : "text-gray-500"
            )}
            aria-hidden
          />
        </button>
      </div>
    </div>
  );
}
