"use client";

import { useRef, useState } from "react";
import { ChevronDown, ChevronUp, Loader2, Mic2, Search, Sparkles, Trash2, X } from "lucide-react";
import type { AudioTrack } from "@/lib/constants";
import type { LyricsSearchResult } from "@/app/api/sys/lyrics/search/route";

type Props = {
  track: AudioTrack;
  onUpdate: (patch: Partial<AudioTrack>) => void;
  isPremium?: boolean;
  onRequirePremium?: () => void;
};

export default function TrackLyricsManager({ track, onUpdate, isPremium = false, onRequirePremium }: Props) {
  const [open, setOpen] = useState(false);
  const [showPremiumModal, setShowPremiumModal] = useState(false);

  const handleOptionClick = (apply: () => void) => {
    if (isPremium) {
      apply();
    } else {
      setShowPremiumModal(true);
    }
  };
  const [query, setQuery] = useState(track.name?.replace(/\.[^/.]+$/, "") || "");
  const [results, setResults] = useState<LyricsSearchResult[]>([]);
  const [searching, setSearching] = useState(false);
  const [hasSearched, setHasSearched] = useState(false);
  const [showCustom, setShowCustom] = useState(false);
  const [customText, setCustomText] = useState(track.lyrics || "");
  const debounceRef = useRef<NodeJS.Timeout | null>(null);

  const hasLyrics = Boolean(track.lyrics?.trim());

  // Search lyrics from LRCLIB
  const performSearch = async (searchTerm: string) => {
    const term = searchTerm.trim();
    if (term.length < 2) {
      setResults([]);
      setHasSearched(false);
      setSearching(false);
      return;
    }

    setSearching(true);
    setHasSearched(true);
    try {
      const res = await fetch(`/api/sys/lyrics/search?q=${encodeURIComponent(term)}`);
      const data = await res.json();
      if (data?.ok && Array.isArray(data.results)) {
        setResults(data.results);
      } else {
        setResults([]);
      }
    } catch (err) {
      console.error("Lyrics search error:", err);
      setResults([]);
    } finally {
      setSearching(false);
    }
  };

  const handleQueryChange = (val: string) => {
    setQuery(val);
    if (debounceRef.current) clearTimeout(debounceRef.current);
    if (!val.trim() || val.trim().length < 2) {
      setResults([]);
      setHasSearched(false);
      return;
    }
    debounceRef.current = setTimeout(() => {
      performSearch(val);
    }, 350);
  };

  const selectSong = (song: LyricsSearchResult) => {
    onUpdate({
      lyrics: song.syncedLyrics || song.plainLyrics || "",
      lyrics_title: song.trackName,
      lyrics_artist: song.artistName,
      lyrics_synced: song.isSynced,
    });
    setOpen(false);
    setResults([]);
  };

  const removeLyrics = () => {
    onUpdate({
      lyrics: undefined,
      lyrics_title: undefined,
      lyrics_artist: undefined,
      lyrics_synced: false,
    });
    setCustomText("");
    setShowCustom(false);
  };

  const saveCustom = () => {
    if (!customText.trim()) {
      removeLyrics();
      return;
    }
    const isLrc = customText.includes("[00:") || /\[\d{2}:\d{2}/.test(customText);
    onUpdate({
      lyrics: customText.trim(),
      lyrics_title: track.name || "Custom Track",
      lyrics_artist: "Custom",
      lyrics_synced: isLrc,
    });
    setShowCustom(false);
    setOpen(false);
  };

  return (
    <div
      style={{
        marginTop: 6,
        padding: "8px 10px",
        borderRadius: 9,
        background: "rgba(0, 0, 0, 0.03)",
        border: hasLyrics ? "1px solid rgba(245, 202, 202, 0.28)" : "1px solid rgba(0, 0, 0, 0.06)",
        fontSize: 12,
      }}
    >
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 6, minWidth: 0 }}>
          <Mic2 size={13} style={{ color: hasLyrics ? "#f5caca" : "rgba(0, 0, 0, 0.4)", flexShrink: 0 }} />
          {hasLyrics ? (
            <div style={{ minWidth: 0, display: "flex", alignItems: "center", gap: 6 }}>
              <span style={{ color: "#000000", fontWeight: 600, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                {track.lyrics_title || track.name}
              </span>
              {track.lyrics_artist && (
                <span style={{ color: "rgba(0, 0, 0, 0.45)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                  · {track.lyrics_artist}
                </span>
              )}
              <span
                style={{
                  fontSize: 9,
                  fontWeight: 800,
                  textTransform: "uppercase",
                  padding: "1px 5px",
                  borderRadius: 4,
                  background: track.lyrics_synced ? "rgba(245, 202, 202, 0.18)" : "rgba(0, 0, 0, 0.08)",
                  color: track.lyrics_synced ? "#f5caca" : "rgba(0, 0, 0, 0.7)",
                  border: track.lyrics_synced ? "1px solid rgba(245, 202, 202, 0.35)" : "1px solid rgba(0, 0, 0, 0.12)",
                  flexShrink: 0,
                }}
              >
                {track.lyrics_synced ? "Synced" : "Plain"}
              </span>
            </div>
          ) : (
            <span style={{ color: "rgba(0, 0, 0, 0.5)" }}>No lyrics configured</span>
          )}
        </div>

        <div style={{ display: "flex", alignItems: "center", gap: 5, flexShrink: 0 }}>
          {hasLyrics && (
            <button
              type="button"
              onClick={removeLyrics}
              title="Remove lyrics"
              style={{
                background: "transparent",
                border: "none",
                color: "#ffffff",
                cursor: "pointer",
                padding: "2px 5px",
                borderRadius: 4,
                display: "flex",
                alignItems: "center",
              }}
            >
              <Trash2 size={12} />
            </button>
          )}

          <button
            type="button"
            onClick={() => {
              setOpen((prev) => !prev);
              if (!open && !results.length && query) {
                performSearch(query);
              }
            }}
            style={{
              background: open ? "rgba(245, 202, 202, 0.15)" : "rgba(0, 0, 0, 0.06)",
              color: open ? "#f5caca" : "rgba(0, 0, 0, 0.8)",
              border: "1px solid rgba(0, 0, 0, 0.1)",
              borderRadius: 5,
              padding: "3px 8px",
              cursor: "pointer",
              fontSize: 11,
              fontWeight: 600,
              display: "flex",
              alignItems: "center",
              gap: 4,
            }}
          >
            {hasLyrics ? (open ? "Close" : "Change") : (open ? "Close" : "+ Lyrics")}
            {open ? <ChevronUp size={12} /> : <ChevronDown size={12} />}
          </button>
        </div>
      </div>

      {/* Lyrics Appearance Options */}
      {hasLyrics && (
        <div style={{ marginTop: 9, paddingTop: 9, borderTop: "1px solid rgba(0, 0, 0, 0.07)" }}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 7 }}>
            <span style={{ fontSize: 11, fontWeight: 700, color: "rgba(0, 0, 0, 0.8)", display: "flex", alignItems: "center", gap: 5 }}>
              <Sparkles size={11} color="#f5caca" /> Lyrics Style
            </span>
            <span style={{ fontSize: 9, fontWeight: 800, color: "#f5caca", background: "rgba(245, 202, 202, 0.12)", border: "1px solid rgba(245, 202, 202, 0.28)", padding: "1px 6px", borderRadius: 4, letterSpacing: "0.04em" }}>
              PREMIUM
            </span>
          </div>

          <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 4, marginBottom: 7 }}>
            {[
              { id: "glass", label: "Glass" },
              { id: "neon", label: "Neon" },
              { id: "karaoke", label: "Karaoke" },
              { id: "minimal", label: "Minimal" },
            ].map((st) => {
              const active = (track.lyrics_style || "glass") === st.id;
              return (
                <button
                  key={st.id}
                  type="button"
                  onClick={() => handleOptionClick(() => onUpdate({ lyrics_style: st.id as AudioTrack["lyrics_style"] }))}
                  style={{
                    padding: "4px 2px",
                    fontSize: 10.5,
                    fontWeight: active ? 750 : 500,
                    borderRadius: 5,
                    border: active ? "1px solid #f5caca" : "1px solid rgba(0, 0, 0, 0.08)",
                    background: active ? "rgba(245, 202, 202, 0.16)" : "rgba(0, 0, 0, 0.03)",
                    color: active ? "#f5caca" : "rgba(0, 0, 0, 0.7)",
                    cursor: "pointer",
                    textAlign: "center",
                    transition: "all 0.14s ease",
                  }}
                >
                  {st.label}
                </button>
              );
            })}
          </div>

          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 6 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 3 }}>
              <span style={{ fontSize: 10, color: "rgba(0, 0, 0, 0.45)", marginRight: 2 }}>Align:</span>
              {[
                { id: "left", label: "Left" },
                { id: "center", label: "Center" },
                { id: "right", label: "Right" },
              ].map((al) => {
                const active = (track.lyrics_align || "center") === al.id;
                return (
                  <button
                    key={al.id}
                    type="button"
                    onClick={() => handleOptionClick(() => onUpdate({ lyrics_align: al.id as AudioTrack["lyrics_align"] }))}
                    style={{
                      padding: "2px 7px",
                      fontSize: 10,
                      fontWeight: active ? 750 : 500,
                      borderRadius: 4,
                      border: active ? "1px solid #f5caca" : "1px solid rgba(0, 0, 0, 0.08)",
                      background: active ? "rgba(245, 202, 202, 0.16)" : "rgba(0, 0, 0, 0.03)",
                      color: active ? "#f5caca" : "rgba(0, 0, 0, 0.6)",
                      cursor: "pointer",
                    }}
                  >
                    {al.label}
                  </button>
                );
              })}
            </div>

            <button
              type="button"
              onClick={() => handleOptionClick(() => onUpdate({ lyrics_glow: !track.lyrics_glow }))}
              style={{
                display: "inline-flex",
                alignItems: "center",
                gap: 4,
                padding: "2px 8px",
                fontSize: 10,
                fontWeight: track.lyrics_glow ? 750 : 500,
                borderRadius: 4,
                border: track.lyrics_glow ? "1px solid #f5caca" : "1px solid rgba(0, 0, 0, 0.08)",
                background: track.lyrics_glow ? "rgba(245, 202, 202, 0.16)" : "rgba(0, 0, 0, 0.03)",
                color: track.lyrics_glow ? "#f5caca" : "rgba(0, 0, 0, 0.6)",
                cursor: "pointer",
              }}
            >
              Glow
            </button>
          </div>
        </div>
      )}

      {/* Expanded Search Drawer */}
      {open && (
        <div style={{ marginTop: 10, paddingTop: 10, borderTop: "1px solid rgba(0, 0, 0, 0.06)" }}>
          {!showCustom ? (
            <>
              <div style={{ position: "relative", display: "flex", alignItems: "center" }}>
                <Search size={13} style={{ position: "absolute", left: 10, color: "rgba(0, 0, 0, 0.4)", pointerEvents: "none" }} />
                <input
                  type="text"
                  value={query}
                  onChange={(e) => handleQueryChange(e.target.value)}
                  placeholder="Search song title or artist (e.g. Drake God's Plan)..."
                  style={{
                    width: "100%",
                    padding: "7px 30px 7px 28px",
                    borderRadius: 7,
                    border: "1px solid rgba(0, 0, 0, 0.14)",
                    background: "rgba(0, 0, 0, 0.35)",
                    color: "#000000",
                    fontSize: 12,
                    outline: "none",
                  }}
                  autoFocus
                />
                {searching ? (
                  <Loader2 size={13} className="spin" style={{ position: "absolute", right: 10, color: "#f5caca" }} />
                ) : query ? (
                  <button
                    type="button"
                    onClick={() => {
                      setQuery("");
                      setResults([]);
                      setHasSearched(false);
                    }}
                    style={{ position: "absolute", right: 8, background: "none", border: "none", color: "rgba(0, 0, 0, 0.4)", cursor: "pointer" }}
                  >
                    <X size={12} />
                  </button>
                ) : null}
              </div>

              {/* Search Results List */}
              <div style={{ marginTop: 8, maxHeight: 180, overflowY: "auto", display: "flex", flexDirection: "column", gap: 4 }}>
                {results.map((song) => (
                  <div
                    key={song.id}
                    onClick={() => selectSong(song)}
                    style={{
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "space-between",
                      gap: 8,
                      padding: "7px 9px",
                      borderRadius: 6,
                      background: "rgba(0, 0, 0, 0.03)",
                      border: "1px solid rgba(0, 0, 0, 0.06)",
                      cursor: "pointer",
                      transition: "background 0.15s ease",
                    }}
                    onMouseEnter={(e) => (e.currentTarget.style.background = "rgba(245, 202, 202, 0.1)")}
                    onMouseLeave={(e) => (e.currentTarget.style.background = "rgba(0, 0, 0, 0.03)")}
                  >
                    <div style={{ minWidth: 0 }}>
                      <div style={{ fontWeight: 650, color: "#000000", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                        {song.trackName}
                      </div>
                      <div style={{ fontSize: 11, color: "rgba(0, 0, 0, 0.5)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                        {song.artistName} {song.albumName ? `· ${song.albumName}` : ""}
                      </div>
                    </div>
                    <span
                      style={{
                        fontSize: 9,
                        fontWeight: 800,
                        textTransform: "uppercase",
                        padding: "2px 6px",
                        borderRadius: 4,
                        background: song.isSynced ? "rgba(245, 202, 202, 0.2)" : "rgba(0, 0, 0, 0.06)",
                        color: song.isSynced ? "#f5caca" : "rgba(0, 0, 0, 0.6)",
                        border: song.isSynced ? "1px solid rgba(245, 202, 202, 0.35)" : "1px solid rgba(0, 0, 0, 0.1)",
                        flexShrink: 0,
                      }}
                    >
                      {song.isSynced ? "Synced" : "Plain"}
                    </span>
                  </div>
                ))}

                {query.trim().length >= 2 && hasSearched && !searching && results.length === 0 && (
                  <div style={{ padding: "14px 8px", textAlign: "center", color: "rgba(0, 0, 0, 0.45)", fontSize: 11.5 }}>
                    No songs with lyrics found for &quot;{query.trim()}&quot;.
                  </div>
                )}

                {!query.trim() && !hasSearched && (
                  <div style={{ padding: "14px 8px", textAlign: "center", color: "rgba(0, 0, 0, 0.32)", fontSize: 11.5 }}>
                    Search by track title and artist to auto-link synced lyrics.
                  </div>
                )}
              </div>

              <div style={{ marginTop: 8, display: "flex", justifyContent: "flex-end" }}>
                <button
                  type="button"
                  onClick={() => setShowCustom(true)}
                  style={{
                    background: "none",
                    border: "none",
                    color: "rgba(0, 0, 0, 0.45)",
                    fontSize: 11,
                    textDecoration: "underline",
                    cursor: "pointer",
                    padding: 0,
                  }}
                >
                  or paste custom lyrics
                </button>
              </div>
            </>
          ) : (
            <div>
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 6 }}>
                <span style={{ color: "#000000", fontWeight: 600, fontSize: 11.5 }}>Custom Lyrics (LRC or Plain Text)</span>
                <button
                  type="button"
                  onClick={() => setShowCustom(false)}
                  style={{ background: "none", border: "none", color: "rgba(0, 0, 0, 0.5)", fontSize: 11, cursor: "pointer" }}
                >
                  Back to Search
                </button>
              </div>
              <textarea
                value={customText}
                onChange={(e) => setCustomText(e.target.value)}
                placeholder="[00:15.30] Example synced line&#10;[00:19.45] Or just paste plain lyrics..."
                rows={5}
                style={{
                  width: "100%",
                  padding: 8,
                  borderRadius: 6,
                  border: "1px solid rgba(0, 0, 0, 0.12)",
                  background: "rgba(0, 0, 0, 0.4)",
                  color: "#000000",
                  fontSize: 11.5,
                  fontFamily: "monospace",
                  outline: "none",
                  resize: "vertical",
                }}
              />
              <div style={{ display: "flex", justifyContent: "flex-end", gap: 6, marginTop: 6 }}>
                <button
                  type="button"
                  onClick={saveCustom}
                  style={{
                    background: "#f5caca",
                    color: "#0a0c10",
                    border: "none",
                    borderRadius: 5,
                    padding: "4px 10px",
                    fontWeight: 700,
                    fontSize: 11,
                    cursor: "pointer",
                  }}
                >
                  Save Lyrics
                </button>
              </div>
            </div>
          )}
        </div>
      )}

      {showPremiumModal && (
        <div
          style={{
            position: "fixed",
            inset: 0,
            zIndex: 9999,
            background: "rgba(0, 0, 0, 0.72)",
            backdropFilter: "blur(8px)",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            padding: 16,
          }}
          onClick={() => setShowPremiumModal(false)}
        >
          <div
            onClick={(e) => e.stopPropagation()}
            style={{
              maxWidth: 380,
              width: "100%",
              borderRadius: 14,
              background: "#0d1117",
              border: "1px solid #251818",
              boxShadow: "0 24px 60px rgba(0, 0, 0, 0.7)",
              padding: "24px 22px",
              textAlign: "center",
            }}
          >
            <div
              style={{
                width: 44,
                height: 44,
                borderRadius: 12,
                background: "rgba(245, 202, 202, 0.12)",
                border: "1px solid rgba(245, 202, 202, 0.3)",
                display: "grid",
                placeItems: "center",
                margin: "0 auto 14px",
                color: "#f5caca",
              }}
            >
              <Sparkles size={22} />
            </div>
            <h3 style={{ margin: "0 0 6px", fontSize: 16, fontWeight: 700, color: "#000000" }}>
              Lifetime Premium Feature
            </h3>
            <p style={{ margin: "0 0 18px", fontSize: 13, color: "#240a0a", lineHeight: 1.5 }}>
              Custom lyrics appearance (Neon Aura, Karaoke, Minimal), custom text alignment, and active line glow are exclusive to Lifetime Premium.
            </p>
            <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
              <button
                type="button"
                onClick={() => {
                  setShowPremiumModal(false);
                  onRequirePremium?.();
                }}
                style={{
                  width: "100%",
                  padding: "10px 16px",
                  borderRadius: 8,
                  border: "1px solid #f5caca",
                  background: "#f5caca",
                  color: "#081016",
                  fontSize: 13,
                  fontWeight: 750,
                  cursor: "pointer",
                }}
              >
                Unlock with Premium — $6.99
              </button>
              <button
                type="button"
                onClick={() => setShowPremiumModal(false)}
                style={{
                  width: "100%",
                  padding: "8px 16px",
                  borderRadius: 8,
                  border: "1px solid rgba(0, 0, 0, 0.08)",
                  background: "transparent",
                  color: "#240a0a",
                  fontSize: 12,
                  fontWeight: 600,
                  cursor: "pointer",
                }}
              >
                Maybe later
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
