"use client";

import { useCallback, useRef, useState } from "react";
import Link from "next/link";
import { useTranslations } from "next-intl";
import { Crown, Loader2 } from "lucide-react";

import { VideoPlayOverlay } from "@/components/sections/VideoPlayOverlay";
import { getTemplatePreviewVideoSrc } from "@/lib/template-preview-media";
import type { VideoCatalogTemplate } from "@/lib/video-templates-catalog";
import { getVideoTemplateImageSrc } from "@/lib/video-templates-catalog";
import { cn } from "@/lib/utils";

interface VideoTemplateCompactCardProps {
  template: VideoCatalogTemplate;
  onUse: () => void;
  isUsing?: boolean;
  className?: string;
}

export function VideoTemplateCompactCard({
  template,
  onUse,
  isUsing = false,
  className,
}: VideoTemplateCompactCardProps) {
  const t = useTranslations("auto.componentsTemplatesVideoVideoTemplateCompactCard");
  const [isHovered, setIsHovered] = useState(false);
  const videoRef = useRef<HTMLVideoElement>(null);
  const imageSrc = getVideoTemplateImageSrc(template.id);
  const videoSrc = getTemplatePreviewVideoSrc(template.id);
  const detailHref = `/templates/${template.id}`;

  const handleEnter = useCallback(() => {
    setIsHovered(true);
    const video = videoRef.current;
    if (video) {
      video.currentTime = 0;
      void video.play().catch(() => undefined);
    }
  }, []);

  const handleLeave = useCallback(() => {
    setIsHovered(false);
    videoRef.current?.pause();
  }, []);

  const handleUseClick = (event: React.MouseEvent<HTMLButtonElement>) => {
    event.preventDefault();
    event.stopPropagation();
    if (!isUsing) onUse();
  };

  return (
    <div
      className={cn(
        "group w-[220px] shrink-0 sm:w-[240px]",
        className
      )}
    >
      <div
        className="relative aspect-[16/10] overflow-hidden rounded-xl border border-gray-100 bg-neutral-100 shadow-sm transition-shadow group-hover:shadow-md"
        onMouseEnter={handleEnter}
        onMouseLeave={handleLeave}
      >
        <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("viewTemplateAria", { name: template.name })}
        >
          {/* eslint-disable-next-line @next/next/no-img-element */}
          <img
            src={imageSrc}
            alt=""
            className={cn(
              "absolute inset-0 h-full w-full object-cover transition-opacity duration-300",
              isHovered ? "opacity-0" : "opacity-100"
            )}
          />
          <video
            ref={videoRef}
            src={videoSrc}
            muted
            loop
            playsInline
            preload="metadata"
            className={cn(
              "absolute inset-0 h-full w-full object-cover transition-opacity duration-300",
              isHovered ? "opacity-100" : "opacity-0"
            )}
            aria-hidden
          />
        </Link>

        {isHovered ? (
          <div className="pointer-events-none absolute inset-0 z-[1]">
            <VideoPlayOverlay size="sm" />
          </div>
        ) : null}

        {template.premium ? (
          <span className="pointer-events-none absolute left-2 top-2 z-[2] flex h-6 w-6 items-center justify-center rounded-md bg-amber-400/95 text-white shadow-sm">
            <Crown className="h-3.5 w-3.5" aria-hidden />
          </span>
        ) : null}
        {template.supports4k ? (
          <span className="pointer-events-none absolute right-2 top-2 z-[2] rounded bg-neutral-900/75 px-1.5 py-0.5 text-[10px] font-bold uppercase tracking-wide text-amber-300">
            4K
          </span>
        ) : null}

        {isHovered ? (
          <div className="absolute inset-x-0 bottom-0 z-[3] bg-gradient-to-t from-neutral-900/80 via-neutral-900/40 to-transparent p-3 pt-10">
            <button
              type="button"
              disabled={isUsing}
              onClick={handleUseClick}
              className="w-full rounded-lg bg-blue-600 px-3 py-2 text-xs font-semibold text-white shadow-lg 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"
            >
              {isUsing ? t("opening") : t("useTemplate")}
            </button>
          </div>
        ) : null}

        {isUsing ? (
          <span className="absolute inset-0 z-[4] flex items-center justify-center bg-black/40">
            <Loader2 className="h-6 w-6 animate-spin text-white" aria-hidden />
          </span>
        ) : null}
      </div>

      <Link
        href={detailHref}
        className="mt-2 line-clamp-2 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 focus-visible:ring-offset-2 rounded-sm"
      >
        {template.name}
      </Link>
      <p className="mt-0.5 text-xs text-neutral-500">
        {t("sceneCount", { count: template.sceneCount })}
      </p>
    </div>
  );
}
