"use client";

import { useEffect, useRef, useState } from "react";
import { X, ChevronLeft, ChevronRight, Star, Trash2 } from "lucide-react";
import { StickerContent } from "./StickerContent";
import { useAuth } from "@/lib/auth-context";
import { useEscapeKey } from "@/lib/use-escape-key";
import type { Highlight } from "@/lib/types";

const FONT_CLASSES: Record<string, string> = {
  modern: "font-sans font-extrabold",
  classic: "font-serif font-semibold",
  signature: "italic font-medium",
  editorial: "font-serif italic font-bold",
  typewriter: "font-mono font-bold",
  neon: "font-sans font-black",
};
const SIZE_CLASSES: Record<string, string> = { sm: "text-xl", md: "text-3xl", lg: "text-5xl" };
const FILTER_CSS: Record<string, string> = {
  normal: "none",
  clarendon: "contrast(1.2) saturate(1.35) brightness(1.05)",
  gingham: "sepia(0.04) contrast(0.9) brightness(1.1) saturate(0.85)",
  moon: "grayscale(1) contrast(1.1) brightness(1.1)",
  lark: "saturate(1.15) contrast(0.9) brightness(1.1)",
  reyes: "sepia(0.4) contrast(0.85) brightness(1.15) saturate(0.75)",
  juno: "saturate(1.4) contrast(1.1) sepia(0.15)",
  ludwig: "saturate(0.7) contrast(1.05) brightness(1.05)",
  aden: "sepia(0.2) contrast(0.9) brightness(1.2) saturate(0.85) hue-rotate(-10deg)",
  perpetua: "saturate(1.1) brightness(1.05) contrast(0.95) hue-rotate(5deg)",
};

export function HighlightsRow({ username }: { username: string }) {
  const [highlights, setHighlights] = useState<Highlight[]>([]);
  const [openIndex, setOpenIndex] = useState<number | null>(null);

  useEffect(() => {
    fetch(`/api/highlights?username=${username}`)
      .then((r) => (r.ok ? r.json() : []))
      .then(setHighlights);
  }, [username]);

  if (highlights.length === 0) return null;

  return (
    <>
      <div className="flex items-center gap-4 mt-4 overflow-x-auto scrollbar-none pb-1">
        {highlights.map((h, i) => (
          <button
            key={h.id}
            onClick={() => setOpenIndex(i)}
            className="flex flex-col items-center gap-1.5 shrink-0"
          >
            <span className="w-16 h-16 rounded-full p-[2px] bg-gradient-to-br from-neutral-300 to-neutral-400 dark:from-neutral-700 dark:to-neutral-600">
              <span className="block w-full h-full rounded-full overflow-hidden bg-white dark:bg-black p-[2px]">
                <span className="flex items-center justify-center w-full h-full rounded-full overflow-hidden bg-gradient-to-br from-neutral-100 to-neutral-200 dark:from-neutral-900 dark:to-neutral-800">
                  {h.coverImageUrl ? (
                    // eslint-disable-next-line @next/next/no-img-element
                    <img src={h.coverImageUrl} alt="" className="w-full h-full object-cover" />
                  ) : (
                    <Star size={20} className="text-neutral-400" />
                  )}
                </span>
              </span>
            </span>
            <span className="text-xs font-medium max-w-[64px] truncate">{h.title}</span>
          </button>
        ))}
      </div>

      {openIndex !== null && (
        <HighlightViewer
          highlight={highlights[openIndex]}
          onClose={() => setOpenIndex(null)}
          onDeleted={() => {
            setHighlights((hs) => hs.filter((h) => h.id !== highlights[openIndex].id));
            setOpenIndex(null);
          }}
        />
      )}
    </>
  );
}

function HighlightViewer({
  highlight,
  onClose,
  onDeleted,
}: {
  highlight: Highlight;
  onClose: () => void;
  onDeleted: () => void;
}) {
  const { user: me } = useAuth();
  const [stories, setStories] = useState(highlight.stories);
  const [index, setIndex] = useState(0);
  const [confirmingDelete, setConfirmingDelete] = useState(false);
  const rafRef = useRef<number | null>(null);
  const startRef = useRef(Date.now());
  const [progress, setProgress] = useState(0);
  const DURATION = 5000;

  useEscapeKey(onClose);
  const isOwn = me?.id === highlight.owner.id;
  const story = stories[index];

  function goNext() {
    if (index < stories.length - 1) {
      setIndex((i) => i + 1);
      setProgress(0);
    } else {
      onClose();
    }
  }
  function goPrev() {
    if (index > 0) {
      setIndex((i) => i - 1);
      setProgress(0);
    }
  }

  useEffect(() => {
    startRef.current = Date.now() - progress * DURATION;
    function tick() {
      const elapsed = Date.now() - startRef.current;
      const p = Math.min(1, elapsed / DURATION);
      setProgress(p);
      if (p >= 1) {
        goNext();
        return;
      }
      rafRef.current = requestAnimationFrame(tick);
    }
    rafRef.current = requestAnimationFrame(tick);
    return () => {
      if (rafRef.current) cancelAnimationFrame(rafRef.current);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [index]);

  async function removeStory() {
    const res = await fetch(`/api/highlights/${highlight.id}/stories/${story.id}`, {
      method: "DELETE",
    }).catch(() => null);
    if (!res || !res.ok) return;
    const data = await res.json();
    if (data.deletedHighlight) {
      onDeleted();
      return;
    }
    const remaining = stories.filter((s) => s.id !== story.id);
    setStories(remaining);
    if (index >= remaining.length) setIndex(Math.max(0, remaining.length - 1));
    setConfirmingDelete(false);
  }

  if (!story) return null;

  const activeFontClass = FONT_CLASSES[story.fontStyle || "modern"];
  const sizeClass = SIZE_CLASSES[story.fontSize || "md"];

  return (
    <div className="hl-viewer-back fixed inset-0 z-50 flex items-center justify-center" onClick={onClose}>
      {index > 0 && (
        <button
          onClick={(e) => {
            e.stopPropagation();
            goPrev();
          }}
          className="hidden md:flex absolute left-8 w-10 h-10 rounded-full bg-white/10 hover:bg-white/20 items-center justify-center text-white"
        >
          <ChevronLeft size={20} />
        </button>
      )}
      <div
        className="relative w-[380px] h-[640px] rounded-2xl overflow-hidden shadow-2xl flex flex-col"
        onClick={(e) => e.stopPropagation()}
      >
        <div className={`absolute inset-0 ${story.imageUrl ? "" : `bg-gradient-to-br ${story.gradient}`}`} />
        {story.imageUrl && (
          // eslint-disable-next-line @next/next/no-img-element
          <img
            src={story.imageUrl}
            alt=""
            style={{ filter: FILTER_CSS[story.filter || "normal"] }}
            className="absolute inset-0 w-full h-full object-cover"
          />
        )}
        {story.imageUrl && <div className="absolute inset-0 bg-black/10" />}
        {story.drawingUrl && (
          // eslint-disable-next-line @next/next/no-img-element
          <img src={story.drawingUrl} alt="" className="absolute inset-0 w-full h-full object-cover pointer-events-none z-[5]" />
        )}
        {story.stickers?.map((s) => (
          <div
            key={s.id}
            style={{
              left: `${s.x}%`,
              top: `${s.y}%`,
              transform: `translate(-50%, -50%) scale(${s.scale ?? 1})`,
            }}
            className="absolute z-[6]"
          >
            <StickerContent sticker={s} />
          </div>
        ))}

        <div className="absolute top-2 left-2 right-2 flex gap-1 z-10">
          {stories.map((_, i) => (
            <div key={i} className="h-0.5 flex-1 bg-white/30 rounded-full overflow-hidden">
              <div
                className="h-full bg-white rounded-full"
                style={{ width: i < index ? "100%" : i === index ? `${progress * 100}%` : "0%" }}
              />
            </div>
          ))}
        </div>

        <div className="flex items-center justify-between px-3 pt-6 z-10">
          <span className="flex items-center gap-1.5 text-white text-sm font-semibold">
            <Star size={14} /> {highlight.title}
          </span>
          <button onClick={onClose} className="text-white/80 hover:text-white">
            <X size={20} />
          </button>
        </div>

        {story.caption && (
          <div className="flex-1 flex items-center justify-center px-8 text-center relative z-[7]">
            <p
              className={`leading-snug drop-shadow-lg ${activeFontClass} ${sizeClass}`}
              style={{
                color: story.textColor || "#ffffff",
                transform: story.textScale ? `scale(${story.textScale})` : undefined,
              }}
            >
              {story.caption}
            </p>
          </div>
        )}

        <button
          onClick={goPrev}
          className="absolute left-0 top-0 bottom-0 w-1/3 z-[8]"
          aria-label="Previous"
        />
        <button
          onClick={goNext}
          className="absolute right-0 top-0 bottom-0 w-1/3 z-[8]"
          aria-label="Next"
        />

        {isOwn && (
          <div className="flex items-center justify-end px-4 pb-4 z-10">
            {confirmingDelete ? (
              <button
                onClick={removeStory}
                className="text-red-300 text-sm font-semibold"
              >
                Confirm remove?
              </button>
            ) : (
              <button
                onClick={() => setConfirmingDelete(true)}
                className="flex items-center gap-1.5 text-white/70 text-sm font-medium hover:text-white transition-colors"
              >
                <Trash2 size={14} /> Remove from Highlight
              </button>
            )}
          </div>
        )}
      </div>
      {index < stories.length - 1 && (
        <button
          onClick={(e) => {
            e.stopPropagation();
            goNext();
          }}
          className="hidden md:flex absolute right-8 w-10 h-10 rounded-full bg-white/10 hover:bg-white/20 items-center justify-center text-white"
        >
          <ChevronRight size={20} />
        </button>
      )}
    </div>
  );
}
