"use client";

import { useEffect, useMemo, useRef, useState } from "react";
import type { AudioTrack } from "@/lib/constants";

type Props = {
  track?: AudioTrack | null;
  currentTime?: number;
  isPlaying?: boolean;
  accent?: string;
  opacity?: number;
  blur?: number;
  cardWidth?: number;
  cardRadius?: number;
  onSeek?: (seconds: number) => void;
};

export type LyricLine = {
  time: number;
  text: string;
};

export function parseLRC(raw: string): LyricLine[] {
  if (!raw) return [];
  const lines = raw.split(/\r?\n/);
  const result: LyricLine[] = [];
  const regex = /\[(\d{1,2}):(\d{2})(?:\.(\d{1,3}))?\]\s*(.*)/;

  for (const line of lines) {
    const trimmed = line.trim();
    const match = regex.exec(trimmed);
    if (match) {
      const minutes = parseInt(match[1], 10);
      const seconds = parseInt(match[2], 10);
      const msPart = match[3] ? match[3].padEnd(3, "0").slice(0, 3) : "0";
      const ms = parseInt(msPart, 10);
      const time = minutes * 60 + seconds + ms / 1000;
      const text = match[4].trim();
      if (text) {
        result.push({ time, text });
      }
    }
  }

  return result.sort((a, b) => a.time - b.time);
}

export default function ProfileLyricsBox({
  track,
  currentTime = 0,
  isPlaying = false,
  accent = "#f5caca",
  cardRadius = 14,
  onSeek,
}: Props) {
  const containerRef = useRef<HTMLDivElement>(null);
  const activeLineRef = useRef<HTMLDivElement>(null);
  const [userScrolled, setUserScrolled] = useState(false);
  const scrollTimeoutRef = useRef<NodeJS.Timeout | null>(null);

  const rawLyrics = track?.lyrics || "";
  const isSynced = Boolean(track?.lyrics_synced || rawLyrics.includes("[00:"));

  const parsedLines = useMemo(() => {
    if (!isSynced) return [];
    return parseLRC(rawLyrics);
  }, [rawLyrics, isSynced]);

  const plainLines = useMemo(() => {
    if (isSynced) return [];
    return rawLyrics.split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
  }, [rawLyrics, isSynced]);

  // Find active line index based on current playback time
  const activeIndex = useMemo(() => {
    if (!parsedLines.length) return -1;
    let index = -1;
    for (let i = 0; i < parsedLines.length; i++) {
      if (currentTime >= parsedLines[i].time) {
        index = i;
      } else {
        break;
      }
    }
    return index;
  }, [currentTime, parsedLines]);

  // Auto-scroll active line smoothly into center of box
  useEffect(() => {
    if (!isSynced || userScrolled || !containerRef.current) return;
    if (activeIndex === -1) {
      containerRef.current.scrollTo({ top: 0, behavior: "smooth" });
      return;
    }
    if (activeLineRef.current) {
      activeLineRef.current.scrollIntoView({
        behavior: "smooth",
        block: "center",
        inline: "nearest",
      });
    }
  }, [activeIndex, isSynced, userScrolled]);

  // Pause auto-scroll briefly if user manually scrolls the box
  const handleScroll = () => {
    setUserScrolled(true);
    if (scrollTimeoutRef.current) clearTimeout(scrollTimeoutRef.current);
    scrollTimeoutRef.current = setTimeout(() => {
      setUserScrolled(false);
    }, 3000);
  };

  if (!rawLyrics.trim()) {
    return null;
  }

  const trackTitle = track?.lyrics_title || track?.name || "Audio Track";
  const trackArtist = track?.lyrics_artist || "";
  const lyricsStyle = track?.lyrics_style || "glass";
  const lyricsAlign = track?.lyrics_align || "center";
  const lyricsColor = track?.lyrics_color || accent;
  const lyricsGlow = Boolean(track?.lyrics_glow);

  return (
    <div
      style={{
        width: "100%",
        maxWidth: "100%",
        boxSizing: "border-box",
        borderRadius: Math.min(cardRadius, 14),
        border: lyricsStyle === "neon" ? `1px solid ${lyricsColor}` : lyricsStyle === "minimal" ? "1px solid rgba(0, 0, 0, 0.08)" : `1px solid ${accent}44`,
        background: lyricsStyle === "neon" ? "rgba(6, 8, 14, 0.88)" : lyricsStyle === "minimal" ? "rgba(10, 10, 16, 0.45)" : "rgba(15, 15, 22, 0.65)",
        backdropFilter: "blur(14px)",
        WebkitBackdropFilter: "blur(14px)",
        boxShadow: lyricsStyle === "neon" ? `0 0 35px -8px ${lyricsColor}aa, inset 0 0 20px -10px ${lyricsColor}44` : lyricsStyle === "karaoke" ? `0 20px 60px -20px ${lyricsColor}66` : `0 18px 50px -24px ${accent}55`,
        overflow: "hidden",
        position: "relative",
        display: "flex",
        flexDirection: "column",
        fontFamily: "inherit",
        transition: "border-color 0.2s ease",
      }}
    >
      {/* Top Header */}
      {lyricsStyle !== "minimal" && (
      <div
        style={{
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          padding: "9px 14px",
          borderBottom: "1px solid rgba(0, 0, 0, 0.06)",
          background: "rgba(0, 0, 0, 0.02)",
          fontSize: 12,
        }}
      >
        <div style={{ display: "flex", alignItems: "center", gap: 7, minWidth: 0 }}>
          <div
            style={{
              display: "flex",
              alignItems: "flex-end",
              gap: 2,
              height: 12,
              width: 13,
              flexShrink: 0,
            }}
          >
            <span
              style={{
                width: 2.5,
                height: isPlaying ? "100%" : "30%",
                background: accent,
                borderRadius: 1,
                animation: isPlaying ? "equalizerBar 0.8s ease-in-out infinite" : "none",
              }}
            />
            <span
              style={{
                width: 2.5,
                height: isPlaying ? "60%" : "60%",
                background: accent,
                borderRadius: 1,
                animation: isPlaying ? "equalizerBar 0.9s ease-in-out infinite 0.2s" : "none",
              }}
            />
            <span
              style={{
                width: 2.5,
                height: isPlaying ? "80%" : "40%",
                background: accent,
                borderRadius: 1,
                animation: isPlaying ? "equalizerBar 0.7s ease-in-out infinite 0.4s" : "none",
              }}
            />
          </div>
          <span
            style={{
              color: "#000000",
              fontWeight: 650,
              overflow: "hidden",
              textOverflow: "ellipsis",
              whiteSpace: "nowrap",
              letterSpacing: "-0.01em",
            }}
          >
            {trackTitle}
            {trackArtist && (
              <span style={{ color: "rgba(0, 0, 0, 0.45)", fontWeight: 400, marginLeft: 5 }}>
                · {trackArtist}
              </span>
            )}
          </span>
        </div>

        <div style={{ display: "flex", alignItems: "center", gap: 6, flexShrink: 0 }}>
          {isSynced && activeIndex === -1 && isPlaying && (
            <span
              style={{
                fontSize: 9,
                fontWeight: 700,
                letterSpacing: "0.05em",
                textTransform: "uppercase",
                padding: "2px 6px",
                borderRadius: 4,
                background: "rgba(0, 0, 0, 0.06)",
                color: "rgba(0, 0, 0, 0.55)",
                border: "1px solid rgba(0, 0, 0, 0.1)",
              }}
            >
              Intro
            </span>
          )}
          {isSynced && (
            <span
              style={{
                fontSize: 9,
                fontWeight: 800,
                letterSpacing: "0.08em",
                textTransform: "uppercase",
                padding: "2px 7px",
                borderRadius: 999,
                background: `${accent}1c`,
                color: accent,
                border: `1px solid ${accent}44`,
              }}
            >
              Synced
            </span>
          )}
        </div>
      </div>
      )}

      {/* Lyrics Viewport */}
      <div
        ref={containerRef}
        onWheel={handleScroll}
        onTouchMove={handleScroll}
        style={{
          height: 132,
          overflowY: "auto",
          position: "relative",
          padding: lyricsAlign === "left" ? "42px 24px" : lyricsAlign === "right" ? "42px 24px" : "42px 18px",
          scrollBehavior: "smooth",
          textAlign: lyricsAlign,
          maskImage: "linear-gradient(to bottom, transparent 0%, black 18%, black 82%, transparent 100%)",
          WebkitMaskImage: "linear-gradient(to bottom, transparent 0%, black 18%, black 82%, transparent 100%)",
        }}
        className="hideScrollbar"
      >
        {isSynced ? (
          <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            {parsedLines.map((line, idx) => {
              const isIntro = activeIndex === -1;
              const isActive = !isIntro && idx === activeIndex;
              const isUpcoming = isIntro && idx === 0;
              const isNearby = !isIntro && Math.abs(idx - activeIndex) <= 1;

              return (
                <div
                  key={`${line.time}-${idx}`}
                  ref={isActive ? activeLineRef : null}
                  onClick={() => onSeek?.(line.time)}
                  className="lyricLineItem"
                  style={{
                    fontSize: isActive ? 15.5 : 13.5,
                    fontWeight: isActive ? 750 : isNearby || isUpcoming ? 600 : 500,
                    lineHeight: 1.45,
                    color: isActive ? (lyricsStyle === "karaoke" ? "#000000" : lyricsColor) : "#000000",
                    opacity: isActive ? 1 : isUpcoming ? 0.6 : isNearby ? 0.44 : 0.22,
                    transform: isActive ? "scale(1.025)" : "scale(0.98)",
                    transformOrigin: lyricsAlign === "left" ? "left center" : lyricsAlign === "right" ? "right center" : "center center",
                    transition: "all 0.25s cubic-bezier(0.2, 0.8, 0.2, 1)",
                    cursor: onSeek ? "pointer" : "default",
                    textShadow: isActive ? ((lyricsGlow || lyricsStyle === "neon") ? `0 0 16px ${lyricsColor}, 0 0 32px ${lyricsColor}88` : `0 0 20px ${lyricsColor}66`) : "none",
                    background: lyricsStyle === "karaoke" && isActive ? `linear-gradient(90deg, ${lyricsColor}, #000000)` : "none",
                    WebkitBackgroundClip: lyricsStyle === "karaoke" && isActive ? "text" : undefined,
                    WebkitTextFillColor: lyricsStyle === "karaoke" && isActive ? "transparent" : undefined,
                  }}
                >
                  {line.text}
                </div>
              );
            })}
          </div>
        ) : (
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {plainLines.map((line, idx) => (
              <p
                key={idx}
                style={{
                  margin: 0,
                  fontSize: 13.5,
                  fontWeight: 500,
                  lineHeight: 1.5,
                  color: "rgba(0, 0, 0, 0.75)",
                }}
              >
                {line}
              </p>
            ))}
          </div>
        )}
      </div>

      <style>{`
        @keyframes equalizerBar {
          0%, 100% { height: 25%; }
          50% { height: 100%; }
        }
        .hideScrollbar::-webkit-scrollbar {
          display: none;
        }
        .hideScrollbar {
          -ms-overflow-style: none;
          scrollbar-width: none;
        }
        .lyricLineItem:hover {
          opacity: 0.9 !important;
        }
      `}</style>
    </div>
  );
}
