import { useEffect, useRef, useState } from "react";
import { useParams, Link } from "react-router-dom";
import { apiFetch } from "../lib/api";

type MusicDetail = {
  id: string;
  title: string;
  subtitle: string | null;
  audioFile: string;
};

type LoadState = "loading" | "ok" | "error";

function fmt(seconds: number): string {
  if (!isFinite(seconds) || seconds < 0) return "0:00";
  const m = Math.floor(seconds / 60);
  const s = Math.floor(seconds % 60);
  return `${m}:${s.toString().padStart(2, "0")}`;
}

export default function MusicPage() {
  const { id } = useParams();
  const audioRef = useRef<HTMLAudioElement | null>(null);

  const [music, setMusic] = useState<MusicDetail | null>(null);
  const [state, setState] = useState<LoadState>("loading");
  const [playing, setPlaying] = useState(false);
  const [needsGesture, setNeedsGesture] = useState(false);
  const [currentTime, setCurrentTime] = useState(0);
  const [duration, setDuration] = useState(0);

  useEffect(() => {
    if (!id) return;
    setState("loading");
    apiFetch<MusicDetail>(`/music/${id}`)
      .then((data) => {
        setMusic(data);
        setState("ok");
      })
      .catch(() => setState("error"));
  }, [id]);

  // Try to autoplay with sound once the audio is mounted. If the browser
  // blocks it (iOS/Android usually do), surface the tap-to-play overlay.
  useEffect(() => {
    if (!music || !audioRef.current) return;
    audioRef.current.play().catch(() => setNeedsGesture(true));
  }, [music]);

  const togglePlay = () => {
    const el = audioRef.current;
    if (!el) return;
    if (el.paused) {
      el.play().catch(() => setNeedsGesture(true));
    } else {
      el.pause();
    }
  };

  const handleSeek = (e: React.ChangeEvent<HTMLInputElement>) => {
    const el = audioRef.current;
    if (!el || !duration) return;
    const t = (Number(e.target.value) / 100) * duration;
    el.currentTime = t;
    setCurrentTime(t);
  };

  const handleUserStart = () => {
    setNeedsGesture(false);
    audioRef.current?.play().catch(() => setNeedsGesture(true));
  };

  if (state === "loading") {
    return (
      <div className="min-h-svh flex items-center justify-center bg-[var(--bg-dark-deep)]">
        <p className="text-[var(--gold)]/70 text-sm tracking-widest">加载中…</p>
      </div>
    );
  }

  if (state === "error" || !music) {
    return (
      <div className="min-h-svh flex flex-col items-center justify-center gap-4 px-6 bg-[var(--bg-dark-deep)]">
        <p className="text-[var(--gold-light)]/80">音乐不存在或已下架</p>
        <Link
          to="/"
          className="px-5 py-2 rounded-full bg-[var(--gold)] text-[var(--bg-dark)] text-sm hover:bg-[var(--gold-hover)]"
        >
          返回首页
        </Link>
      </div>
    );
  }

  const progress = duration > 0 ? (currentTime / duration) * 100 : 0;

  return (
    <div className="relative min-h-svh overflow-hidden bg-[var(--bg-dark-deep)] grain-overlay">
      {/* Ambient gradient backdrop */}
      <div
        className="absolute inset-0 pointer-events-none"
        style={{
          backgroundImage: `
            radial-gradient(ellipse 80% 50% at 50% 30%, rgba(212, 165, 116, 0.18) 0%, transparent 70%),
            radial-gradient(ellipse 60% 40% at 50% 100%, rgba(199, 91, 57, 0.10) 0%, transparent 70%)
          `,
        }}
      />

      {/* Top back */}
      <Link
        to="/"
        aria-label="返回"
        className="fixed top-4 left-4 z-20 w-10 h-10 rounded-full bg-white/5 backdrop-blur border border-white/10
          flex items-center justify-center text-[var(--gold-light)] hover:bg-white/10"
      >
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
          <path d="M15 18l-6-6 6-6" />
        </svg>
      </Link>

      <div className="relative z-10 flex flex-col items-center justify-center min-h-svh px-6 py-16">
        {/* Header */}
        <div className="text-center animate-fade-in-up">
          <div className="inline-flex items-center gap-3 mb-6">
            <span className="block w-8 h-px bg-[var(--gold)]/50" />
            <span className="text-[var(--gold)] text-[10px] tracking-[0.4em] uppercase"
              style={{ fontFamily: "'Playfair Display', serif" }}>
              CityWalk · Song
            </span>
            <span className="block w-8 h-px bg-[var(--gold)]/50" />
          </div>

          <h1
            className="text-[var(--text-inverted)] leading-tight mb-2"
            style={{
              fontSize: "clamp(2rem, 7vw, 2.75rem)",
              fontFamily: "'Playfair Display', serif",
              fontWeight: 700,
              letterSpacing: "-0.01em",
            }}
          >
            {music.title}
          </h1>

          {music.subtitle && (
            <p className="text-[var(--gold-light)]/70 text-sm tracking-[0.1em]">
              {music.subtitle}
            </p>
          )}
        </div>

        {/* Disc */}
        <div className="relative mt-14 animate-scale-in" style={{ animationDelay: "0.2s" }}>
          {/* Ripples */}
          {playing && (
            <>
              <span
                className="absolute inset-0 rounded-full pointer-events-none animate-music-ripple"
                style={{ border: "1.5px solid rgba(212, 165, 116, 0.55)" }}
              />
              <span
                className="absolute inset-0 rounded-full pointer-events-none animate-music-ripple"
                style={{ border: "1.5px solid rgba(212, 165, 116, 0.55)", animationDelay: "0.8s" }}
              />
              <span
                className="absolute inset-0 rounded-full pointer-events-none animate-music-ripple"
                style={{ border: "1.5px solid rgba(212, 165, 116, 0.55)", animationDelay: "1.6s" }}
              />
            </>
          )}

          {/* Rotating dashed ring */}
          <div
            className={`absolute -inset-3 rounded-full pointer-events-none ${playing ? "animate-music-spin" : ""}`}
            style={{
              border: "1.5px dashed rgba(212, 165, 116, 0.45)",
            }}
          />
          <div
            className="absolute -inset-8 rounded-full pointer-events-none"
            style={{
              border: "1px solid rgba(212, 165, 116, 0.12)",
            }}
          />

          {/* Central disc button */}
          <button
            onClick={togglePlay}
            aria-label={playing ? "暂停" : "播放"}
            className="relative w-56 h-56 rounded-full flex items-center justify-center transition-transform active:scale-95"
            style={{
              background: "radial-gradient(circle at 35% 30%, rgba(232, 201, 160, 0.55) 0%, rgba(212, 165, 116, 0.25) 45%, rgba(26, 26, 46, 0.9) 100%)",
              boxShadow: "0 0 60px rgba(212, 165, 116, 0.25), inset 0 1px 0 rgba(255,255,255,0.15), inset 0 -8px 24px rgba(0,0,0,0.4)",
            }}
          >
            {/* Inner darker ring for "record" feel */}
            <span className="absolute inset-6 rounded-full pointer-events-none"
              style={{
                background: "radial-gradient(circle, rgba(10,10,18,0.7) 0%, rgba(26,26,46,0.4) 60%, transparent 70%)",
                border: "1px solid rgba(212, 165, 116, 0.2)",
              }}
            />
            {/* Play / Pause glyph */}
            {playing ? (
              <svg width="36" height="36" viewBox="0 0 24 24" fill="currentColor" className="relative z-10 text-[var(--gold-light)] drop-shadow-[0_0_8px_rgba(212,165,116,0.6)]">
                <rect x="6" y="5" width="4" height="14" rx="1" />
                <rect x="14" y="5" width="4" height="14" rx="1" />
              </svg>
            ) : (
              <svg width="40" height="40" viewBox="0 0 24 24" fill="currentColor" className="relative z-10 text-[var(--gold-light)] drop-shadow-[0_0_8px_rgba(212,165,116,0.6)] ml-1">
                <path d="M8 5v14l11-7z" />
              </svg>
            )}
          </button>
        </div>

        {/* Progress & time */}
        <div className="w-full max-w-[320px] mt-14 animate-fade-in-up" style={{ animationDelay: "0.4s" }}>
          <input
            type="range"
            min={0}
            max={100}
            step={0.1}
            value={progress}
            onChange={handleSeek}
            className="w-full music-progress"
            style={{ ["--progress" as string]: `${progress}%` }}
          />
          <div className="mt-2 flex justify-between text-[11px] text-[var(--gold-light)]/70 tabular-nums tracking-wider">
            <span>{fmt(currentTime)}</span>
            <span>{fmt(duration)}</span>
          </div>
        </div>

        {/* Hint text */}
        <p className="mt-10 text-[var(--gold-light)]/40 text-[11px] tracking-[0.25em]">
          {playing ? "PLAYING · 轻点圆盘暂停" : "PAUSED · 轻点圆盘播放"}
        </p>
      </div>

      {/* Hidden audio element — preload auto so it starts buffering immediately */}
      <audio
        ref={audioRef}
        src={music.audioFile}
        preload="auto"
        playsInline
        onPlay={() => setPlaying(true)}
        onPause={() => setPlaying(false)}
        onEnded={() => setPlaying(false)}
        onTimeUpdate={(e) => setCurrentTime(e.currentTarget.currentTime)}
        onLoadedMetadata={(e) => setDuration(e.currentTarget.duration)}
      />

      {/* Tap-to-play overlay when autoplay is blocked */}
      {needsGesture && (
        <div
          className="fixed inset-0 z-30 flex flex-col items-center justify-center bg-[var(--bg-dark-deep)]/85 backdrop-blur-sm animate-overlay-fade"
          onClick={handleUserStart}
        >
          <div className="text-center px-8">
            <div className="w-20 h-20 mx-auto mb-6 rounded-full bg-[var(--gold)]/15 border border-[var(--gold)]/50 flex items-center justify-center animate-pulse-soft">
              <svg width="34" height="34" viewBox="0 0 24 24" fill="currentColor" className="text-[var(--gold)] ml-1">
                <path d="M8 5v14l11-7z" />
              </svg>
            </div>
            <p className="text-[var(--gold-light)] text-base mb-2" style={{ fontFamily: "'Playfair Display', serif" }}>
              轻点聆听
            </p>
            <p className="text-[var(--gold-light)]/50 text-xs tracking-[0.2em]">Tap anywhere to play</p>
          </div>
        </div>
      )}
    </div>
  );
}
