"use client";

import { useEffect, useRef, useState } from "react";
import gsap from "gsap";
import type { PublicTemplate } from "@/lib/client-api";
import { UseTemplateButton } from "@/components/dashboard/UseTemplateButton";
import { ModuleIcon } from "@/components/icons";

interface TemplatePreviewModalProps {
  template: PublicTemplate;
  open: boolean;
  onClose: () => void;
}

export function TemplatePreviewModal({
  template,
  open,
  onClose,
}: TemplatePreviewModalProps) {
  const overlayRef = useRef<HTMLDivElement>(null);
  const modalRef = useRef<HTMLDivElement>(null);
  const cardRef = useRef<HTMLDivElement>(null);
  const tlRef = useRef<gsap.core.Timeline | null>(null);
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    // eslint-disable-next-line react-hooks/set-state-in-effect
    if (open) setMounted(true);
  }, [open]);

  useEffect(() => {
    if (!mounted) return;
    const overlay = overlayRef.current;
    const modal = modalRef.current;
    const card = cardRef.current;
    if (!overlay || !modal || !card) return;

    let startRect: DOMRect | null = null;
    try {
      startRect = card.getBoundingClientRect();
    } catch {
      startRect = null;
    }

    const tl = gsap.timeline();
    tlRef.current = tl;

    if (startRect && startRect.width > 0 && open) {
      gsap.set(modal, {
        autoAlpha: 1,
        x: startRect.left + startRect.width / 2 - window.innerWidth / 2,
        y: startRect.top + startRect.height / 2 - window.innerHeight / 2,
        scaleX: startRect.width / 720,
        scaleY: startRect.height / 560,
      });
      tl.to(overlay, { autoAlpha: 1, duration: 0.25, ease: "power2.out" }, 0)
        .to(
          modal,
          {
            x: 0,
            y: 0,
            scaleX: 1,
            scaleY: 1,
            duration: 0.55,
            ease: "power3.inOut",
          },
          0,
        );
    } else if (open) {
      gsap.set(modal, { autoAlpha: 0, scale: 0.92 });
      tl.to(overlay, { autoAlpha: 1, duration: 0.2 }, 0).to(
        modal,
        { autoAlpha: 1, scale: 1, duration: 0.3, ease: "power2.out" },
        0,
      );
    } else {
      tl.to(modal, {
        autoAlpha: 0,
        scale: 0.95,
        duration: 0.2,
        ease: "power2.in",
      }).to(overlay, { autoAlpha: 0, duration: 0.2 }, 0);
    }

    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") onClose();
    };
    document.addEventListener("keydown", onKey);

    return () => {
      document.removeEventListener("keydown", onKey);
      tl.kill();
      tlRef.current = null;
    };
  }, [open, mounted, onClose]);

  useEffect(() => {
    if (!open && mounted) {
      const id = window.setTimeout(() => setMounted(false), 260);
      return () => window.clearTimeout(id);
    }
    return;
  }, [open, mounted]);

  if (!mounted) {
    return (
      <div
        ref={cardRef}
        aria-hidden
        className="invisible h-0 w-0 overflow-hidden"
      />
    );
  }

  const imageSrc = template.hoverImage ?? template.coverImage;
  const modules = template.modules.filter((m) => m.enabled);

  return (
    <>
      <div
        ref={overlayRef}
        onClick={onClose}
        className="fixed inset-0 z-50 bg-black/55"
        style={{ visibility: "hidden", opacity: 0 }}
      />
      <div
        ref={modalRef}
        className="fixed left-1/2 top-1/2 z-50 w-[calc(100vw-48px)] max-w-[720px] -translate-x-1/2 -translate-y-1/2"
        style={{ visibility: "hidden", opacity: 0 }}
      >
        <div
          ref={cardRef}
          aria-hidden
          className="invisible h-0 w-0 overflow-hidden"
        />
        <div className="overflow-hidden rounded-2xl bg-surface shadow-2xl ring-1 ring-rose-200/40">
          <div className="relative grid h-[560px] grid-rows-[55%_45%] md:grid-rows-1 md:grid-cols-[55%_45%]">
            <div className="relative overflow-hidden bg-gradient-to-br from-rose-100 via-pink-50 to-amber-50">
              {imageSrc ? (
                // eslint-disable-next-line @next/next/no-img-element
                <img
                  src={imageSrc}
                  alt={template.name}
                  className="h-full w-full object-cover"
                  draggable={false}
                />
              ) : (
                <div className="grid h-full w-full place-items-center bg-gradient-to-br from-rose-200 to-pink-200">
                  <span className="text-8xl font-bold text-white/70">
                    {template.name.charAt(0)}
                  </span>
                </div>
              )}
              <div className="absolute inset-0 bg-gradient-to-t from-black/65 via-transparent to-transparent" />
              <div className="absolute inset-x-0 bottom-0 p-6 text-white">
                <p className="text-[10px] font-semibold uppercase tracking-[0.18em] text-white/80">
                  {template.category}
                </p>
                <h2 className="mt-1 text-2xl font-bold drop-shadow-sm">
                  {template.name}
                </h2>
                <p className="mt-2 max-w-md text-sm text-white/90">
                  {template.description}
                </p>
              </div>
            </div>
            <div className="flex flex-col gap-4 p-6">
              <div className="flex items-center justify-between">
                <span className="rounded-full bg-rose-50 px-3 py-1 text-[10px] font-semibold uppercase tracking-wide text-rose-700">
                  {modules.length} modules · v
                  {template.publishedVersion ?? template.version}
                </span>
                <span className="text-xs text-muted">
                  {template.settings.requireEventDate
                    ? "Date required"
                    : "Date optional"}
                </span>
              </div>
              <div>
                <p className="text-xs font-semibold uppercase tracking-wide text-muted">
                  What&apos;s included
                </p>
                <ul className="mt-2 grid grid-cols-2 gap-1.5">
                  {modules.map((m) => (
                    <li
                      key={m.moduleId}
                      className="group relative flex items-center gap-2 overflow-hidden rounded-lg border border-rose-200/70 bg-rose-50/60 px-2.5 py-1.5 text-xs"
                    >
                      {m.image ? (
                        <>
                          {/* eslint-disable-next-line @next/next/no-img-element */}
                          <img
                            src={m.image}
                            alt=""
                            aria-hidden
                            className="absolute inset-0 h-full w-full object-cover opacity-20"
                          />
                          <div className="absolute inset-0 bg-gradient-to-r from-rose-50/95 via-rose-50/85 to-rose-50/40" />
                        </>
                      ) : null}
                      <span className="relative z-10 grid h-6 w-6 shrink-0 place-items-center overflow-hidden rounded-md border border-rose-100 bg-gradient-to-br from-rose-500 to-pink-600 text-white">
                        {m.iconImage ? (
                          // eslint-disable-next-line @next/next/no-img-element
                          <img
                            src={m.iconImage}
                            alt=""
                            className="h-full w-full object-cover"
                          />
                        ) : (
                          <ModuleIcon
                            name={m.icon}
                            className="h-3.5 w-3.5 text-white"
                          />
                        )}
                      </span>
                      <span className="relative z-10 truncate font-medium text-foreground">
                        {m.name}
                      </span>
                    </li>
                  ))}
                </ul>
              </div>
              <div className="mt-auto flex flex-col gap-2">
                <UseTemplateButton
                  templateId={template.id}
                  templateName={template.name}
                  requireEventDate={template.settings.requireEventDate}
                  requireLocation={template.settings.requireLocation}
                  className="w-full justify-center"
                />
                <button
                  type="button"
                  onClick={onClose}
                  className="text-xs font-medium text-muted hover:text-foreground"
                >
                  Close preview
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </>
  );
}
