"use client";

import { useCallback, useState } from "react";
import Link from "next/link";
import { AnimatePresence, motion } from "framer-motion";
import { useTranslations } from "next-intl";

import { Button } from "@/components/ui/button";
import { OptimizedImage } from "@/components/ui/optimized-image";
import { getTemplatePreviewVideoSrc } from "@/lib/template-preview-media";
import { cn } from "@/lib/utils";

export interface TemplateCardProps {
  templateId: string;
  name: string;
  category: string;
  imageSrc: string;
  /** Explicit Mixkit (or other) preview clip; falls back to hashed seed URL */
  previewVideoUrl?: string;
  /** Seed for picking a preview clip when previewVideoUrl is omitted */
  previewSeed?: string;
  className?: string;
  priority?: boolean;
  onUseTemplate?: () => void;
  isUsingTemplate?: boolean;
  /** Translated CTA labels (optional — component falls back to English) */
  useTemplateLabel?: string;
  openingLabel?: string;
}

const fadeTransition = { duration: 0.3, ease: "easeOut" as const };

export function TemplateCard({
  templateId,
  name,
  category,
  imageSrc,
  previewVideoUrl,
  previewSeed,
  className,
  priority = false,
  onUseTemplate,
  isUsingTemplate = false,
  useTemplateLabel,
  openingLabel,
}: TemplateCardProps) {
  const t = useTranslations("auto.componentsSectionsTemplateCard");
  const resolvedUseTemplateLabel = useTemplateLabel ?? t("useTemplateLabel");
  const resolvedOpeningLabel = openingLabel ?? t("openingLabel");
  const [isHovered, setIsHovered] = useState(false);
  const seed = previewSeed ?? name;
  const videoSrc = previewVideoUrl ?? getTemplatePreviewVideoSrc(seed);
  const detailHref = `/templates/${templateId}`;

  const handleMouseEnter = useCallback(() => setIsHovered(true), []);
  const handleMouseLeave = useCallback(() => setIsHovered(false), []);

  return (
    <article
      className={cn(
        "group relative overflow-hidden rounded-xl border border-gray-100 bg-white shadow-sm transition-shadow duration-300 hover:shadow-md",
        className
      )}
      onMouseEnter={handleMouseEnter}
      onMouseLeave={handleMouseLeave}
    >
      <div className="relative aspect-[4/3] overflow-hidden bg-neutral-900">
        <Link
          href={detailHref}
          className="absolute inset-0 z-0 block no-underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-600 focus-visible:ring-offset-2"
          aria-label={t("viewTemplateAriaLabel", { name })}
        >
          <OptimizedImage
            src={imageSrc}
            alt={name}
            fill
            priority={priority}
            sizes="(max-width: 640px) 100vw, (max-width: 1024px) 50vw, 25vw"
            className="object-cover"
          />
        </Link>

        <AnimatePresence>
          {isHovered ? (
            <motion.div
              key="preview-video"
              className="pointer-events-none absolute inset-0 z-[1]"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              transition={fadeTransition}
            >
              <video
                src={videoSrc}
                autoPlay
                muted
                loop
                playsInline
                preload="metadata"
                className="h-full w-full object-cover"
                aria-hidden
              />
            </motion.div>
          ) : null}
        </AnimatePresence>

        <AnimatePresence>
          {isHovered ? (
            <motion.div
              key="use-template-cta"
              className="absolute inset-x-0 bottom-0 z-[2] bg-gradient-to-t from-neutral-900/80 via-neutral-900/40 to-transparent p-3 pt-10"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              transition={fadeTransition}
            >
              <Button
                type="button"
                size="sm"
                disabled={isUsingTemplate}
                className="w-full bg-blue-600 shadow-lg hover:bg-blue-700 focus-visible:ring-offset-neutral-900"
                onClick={(event) => {
                  event.stopPropagation();
                  onUseTemplate?.();
                }}
              >
                {isUsingTemplate ? resolvedOpeningLabel : resolvedUseTemplateLabel}
              </Button>
            </motion.div>
          ) : null}
        </AnimatePresence>
      </div>

      <div className="flex items-start justify-between gap-3 p-4">
        <Link
          href={detailHref}
          className="font-heading text-sm font-semibold text-gray-900 no-underline hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-600 rounded-sm"
        >
          {name}
        </Link>
        <span className="shrink-0 rounded-full bg-neutral-100 px-2.5 py-0.5 text-xs font-medium text-neutral-600">
          {category}
        </span>
      </div>
    </article>
  );
}
