import { useState, useEffect, useCallback, useMemo } from "react";
import { useParams, useNavigate, useLocation } from "react-router-dom";
import { motion, AnimatePresence } from "framer-motion";
import {
  Save,
  X,
  Music,
  Mic2,
  Home,
  Wand2,
  Check,
  RotateCcw,
  ArrowLeft,
  AlertCircle,
} from "lucide-react";
import api from "@utils/api";
import { useTheme } from "@context/ThemeContext";
import LyricsRichTextEditor from "@components/LyricsRichTextEditor";

// Chord definitions
const CHORD_ROOTS = [
  "C",
  "C#",
  "D",
  "D#",
  "E",
  "F",
  "F#",
  "G",
  "G#",
  "A",
  "A#",
  "B",
];
const CHORD_TYPES = [
  "",
  "m",
  "7",
  "m7",
  "maj7",
  "dim",
  "aug",
  "sus2",
  "sus4",
  "add9",
];

// Common chord progressions
const COMMON_PROGRESSIONS = [
  { name: "I-V-vi-IV (Pop)", chords: ["C", "G", "Am", "F"] },
  { name: "I-IV-V-I (Blues)", chords: ["G", "C", "D", "G"] },
  { name: "vi-IV-I-V (Emotional)", chords: ["Am", "F", "C", "G"] },
  { name: "I-vi-IV-V (50s)", chords: ["C", "Am", "F", "G"] },
  { name: "ii-V-I (Jazz)", chords: ["Dm7", "G7", "Cmaj7"] },
  { name: "I-V-vi-iii-IV (Canon)", chords: ["D", "A", "Bm", "F#m", "G"] },
];

// Section headers to skip when applying chords
const SECTION_HEADERS = [
  "verse",
  "chorus",
  "bridge",
  "pre-chorus",
  "prechorus",
  "pre chorus",
  "intro",
  "outro",
  "interlude",
  "hook",
  "tag",
  "ending",
  "instrumental",
  "v1",
  "v2",
  "v3",
  "v4",
  "c1",
  "c2",
  "c3",
  "ch1",
  "ch2",
  "ch3",
  "verse 1",
  "verse 2",
  "verse 3",
  "verse 4",
  "chorus 1",
  "chorus 2",
  "chorus 3",
  "bridge 1",
  "bridge 2",
  "[verse]",
  "[chorus]",
  "[bridge]",
  "[intro]",
  "[outro]",
  "(verse)",
  "(chorus)",
  "(bridge)",
  "(intro)",
  "(outro)",
];

export default function SongEditorPage() {
  const { id } = useParams();
  const navigate = useNavigate();
  const location = useLocation();
  const { isDark } = useTheme();
  // Check if we're creating a new song (no id in params)
  const isNew = !id;

  // Check for uploaded data from location state
  const uploadedData = location.state?.uploadedData;

  const [form, setForm] = useState({
    title: uploadedData?.title || "",
    artist: uploadedData?.artist || "",
    singer: "",
    band: "",
    key_chord: uploadedData?.key_chord || uploadedData?.chords || "",
    lyrics: uploadedData?.lyrics || "",
  });
  const [loading, setLoading] = useState(!isNew && !uploadedData);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState(isNew ? "" : "");

  // Chord Progression State
  const [showChordPanel, setShowChordPanel] = useState(false);
  const [selectedProgression, setSelectedProgression] = useState(null);
  const [customProgression, setCustomProgression] = useState([]);
  const [progressionMode, setProgressionMode] = useState("preset");

  // Fetch existing song if editing
  useEffect(() => {
    console.log("SongEditorPage mounted - isNew:", isNew, "id:", id);

    if (!isNew) {
      const fetchSong = async () => {
        try {
          const res = await api.get(`/songs/${id}`);
          if (res.data.success) {
            setForm(res.data.song);
            setError(""); // Clear any previous errors
          }
        } catch (err) {
          console.error("Error loading song:", err);
          setError("Failed to load song");
        } finally {
          setLoading(false);
        }
      };
      fetchSong();
    } else {
      // For new songs, ensure loading is false and clear any errors
      console.log("Creating new song - clearing errors");
      setLoading(false);
      setError("");
    }
  }, [id, isNew]);

  // Check if a line is a section header
  const isSectionHeader = (line) => {
    const trimmed = line.trim().toLowerCase();
    if (!trimmed) return false;
    if (SECTION_HEADERS.some((h) => trimmed === h || trimmed === h + ":"))
      return true;
    if (
      /^[\[\(]?(?:verse|chorus|bridge|intro|outro|pre-?chorus|interlude|hook|tag|ending|instrumental|v\d|c\d|ch\d)[\d\s]*[\]\)]?:?$/i.test(
        trimmed,
      )
    ) {
      return true;
    }
    return false;
  };

  // Apply chord progression to lyrics
  const applyChordProgression = useCallback((lyrics, progression) => {
    if (!lyrics || !progression || progression.length === 0) return lyrics;

    // First remove existing chords
    const cleanLyrics = lyrics.replace(/\[[^\]]+\]/g, "");
    const lines = cleanLyrics.split("\n");
    let chordIndex = 0;

    const processedLines = lines.map((line) => {
      const trimmed = line.trim();
      if (!trimmed || isSectionHeader(trimmed)) return line;
      const chord = progression[chordIndex % progression.length];
      chordIndex++;
      return `[${chord}]${line}`;
    });

    return processedLines.join("\n");
  }, []);

  // Handle apply progression
  const handleApplyProgression = () => {
    const progression =
      progressionMode === "preset"
        ? selectedProgression?.chords
        : customProgression;

    if (!progression || progression.length === 0) return;

    const newLyrics = applyChordProgression(form.lyrics, progression);
    setForm({ ...form, lyrics: newLyrics });
    setShowChordPanel(false);
  };

  // Remove all chords
  const handleRemoveChords = () => {
    const cleanLyrics = (form.lyrics || "").replace(/\[[^\]]+\]/g, "");
    setForm({ ...form, lyrics: cleanLyrics });
  };

  // Add chord to custom progression
  const addToCustomProgression = (root) => {
    setCustomProgression((prev) => [...prev, root]);
  };

  // Remove chord from custom progression
  const removeFromCustomProgression = (index) => {
    setCustomProgression((prev) => prev.filter((_, i) => i !== index));
  };

  // Convert pasted chord-over-lyrics format to embedded [Chord] format
  const convertChordsOverLyrics = (text) => {
    if (!text) return { lyrics: "", detectedChords: [] };

    const lines = text.split("\n");
    const result = [];
    const allChords = new Set();

    // Chord pattern: line with mostly chords and spaces
    const chordPattern =
      /^[\sA-G#b/()m\d]*[A-G][#b]?(?:m|maj|min|dim|aug|sus|add|2|4|5|6|7|9|11|13)*[\sA-G#b/()m\d]*$/;
    const singleChordPattern =
      /([A-G][#b]?(?:m|maj|min|dim|aug|sus|add)?[0-9]*)/g;

    console.log("🎵 Converting chords-over-lyrics format...");
    console.log("Total lines:", lines.length);

    for (let i = 0; i < lines.length; i++) {
      const currentLine = lines[i];
      const nextLine = lines[i + 1];

      // Check if current line is a chord line (has chords, next line is lyrics)
      const isChordLine =
        currentLine &&
        currentLine.trim().length > 0 &&
        chordPattern.test(currentLine.trim()) &&
        nextLine !== undefined;

      if (isChordLine && nextLine) {
        console.log(`Line ${i} is chord line:`, currentLine);
        console.log(`Line ${i + 1} is lyrics:`, nextLine);

        // Extract chords with their positions
        const chords = [];
        let match;
        const chordRegex = /([A-G][#b]?(?:m|maj|min|dim|aug|sus|add)?[0-9]*)/g;

        while ((match = chordRegex.exec(currentLine)) !== null) {
          chords.push({
            chord: match[1],
            position: match.index,
          });
          allChords.add(match[1]);
        }

        console.log("Detected chords:", chords);

        // Build lyric line with embedded chords
        let embeddedLine = "";
        let lastPos = 0;

        chords.forEach(({ chord, position }) => {
          // Get text from lyrics line up to chord position
          const textUpToChord = nextLine.substring(lastPos, position);
          embeddedLine += textUpToChord;

          // Add chord in brackets
          embeddedLine += `[${chord}]`;
          lastPos = position;
        });

        // Add remaining lyrics
        embeddedLine += nextLine.substring(lastPos);
        console.log("Embedded line:", embeddedLine);
        result.push(embeddedLine);

        // Skip the lyrics line since we processed it
        i++;
      } else if (!isChordLine) {
        // Regular line (not a chord line)
        result.push(currentLine);
      }
      // Skip standalone chord lines that don't have lyrics below
    }

    console.log("✅ Conversion complete!");
    console.log("Detected chords:", Array.from(allChords));
    console.log("Result lyrics:", result.join("\n"));

    return {
      lyrics: result.join("\n"),
      detectedChords: Array.from(allChords),
    };
  };

  // Save song
  const handleSave = async () => {
    if (!form.title.trim()) {
      setError("Title is required");
      return;
    }

    setSaving(true);
    setError("");

    try {
      // Strip HTML tags from lyrics if any
      let cleanLyrics = form.lyrics || "";
      const tempDiv = document.createElement("div");
      tempDiv.innerHTML = cleanLyrics;
      cleanLyrics = tempDiv.textContent || tempDiv.innerText || cleanLyrics;

      // Convert chord-over-lyrics format to embedded [Chord] format
      const { lyrics: convertedLyrics, detectedChords } =
        convertChordsOverLyrics(cleanLyrics);

      // Auto-detect key from first chord if key not set
      let songKey = form.key_chord;
      if (!songKey && detectedChords.length > 0) {
        songKey = detectedChords[0];
      }

      // Build the data to save
      const saveData = {
        ...form,
        lyrics: convertedLyrics,
        key_chord: songKey || form.key_chord || "",
        chords: detectedChords.join(", "),
      };

      let res;
      if (isNew) {
        res = await api.post("/songs", saveData);
      } else {
        res = await api.put(`/songs/${id}`, saveData);
      }

      if (res.data.success) {
        navigate(`/song/${res.data.song?.id || id}`);
      } else {
        setError(res.data.message || "Failed to save song");
      }
    } catch (err) {
      setError(err.response?.data?.message || "Failed to save song");
    } finally {
      setSaving(false);
    }
  };

  // Theme-aware classes
  const textPrimary = isDark ? "text-white" : "text-gray-900";
  const textSecondary = isDark ? "text-white/70" : "text-gray-600";
  const textMuted = isDark ? "text-white/50" : "text-gray-500";
  const bgCard = isDark ? "bg-slate-800/80" : "bg-white";
  const borderColor = isDark ? "border-white/10" : "border-gray-200";
  const inputClass = `w-full px-4 py-3 rounded-lg outline-none transition-all
    ${
      isDark
        ? "bg-white/5 border border-white/10 focus:border-cyan-500/50 text-white placeholder-white/40"
        : "bg-gray-50 border border-gray-200 focus:border-cyan-500 text-gray-900 placeholder-gray-400"
    }`;

  if (loading) {
    return (
      <div
        className={`min-h-screen flex items-center justify-center ${textMuted}`}
      >
        <div className="text-center">
          <div className="w-12 h-12 border-2 border-t-cyan-500 border-cyan-500/20 rounded-full animate-spin mx-auto mb-4"></div>
          <p>Loading song...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="max-w-4xl mx-auto pb-20">
      {/* Header */}
      <div className="mb-6">
        <button
          onClick={() => navigate(-1)}
          className={`flex items-center gap-2 mb-4 ${textMuted} hover:text-cyan-500 transition-colors`}
        >
          <ArrowLeft size={16} />
          <span className="text-sm">Back</span>
        </button>

        <div className="flex items-start justify-between gap-4">
          <div>
            <h1
              className={`text-2xl sm:text-3xl font-bold ${textPrimary} mb-2`}
            >
              {isNew ? "Create New Song" : "Edit Song"}
            </h1>
            <p className={textMuted}>
              {isNew
                ? "Add a new song to your database"
                : `Editing: ${form.title || "Untitled"}`}
            </p>
          </div>

          <button
            onClick={() => setShowChordPanel(!showChordPanel)}
            className={`p-2.5 rounded-lg transition-colors
              ${
                showChordPanel
                  ? "bg-violet-500 text-white"
                  : isDark
                    ? "bg-white/10 text-white hover:bg-white/20"
                    : "bg-gray-100 text-gray-700 hover:bg-gray-200"
              }`}
          >
            <Wand2 size={18} />
          </button>
        </div>
      </div>

      {/* Error Message */}
      {error && (
        <motion.div
          initial={{ opacity: 0, y: -10 }}
          animate={{ opacity: 1, y: 0 }}
          className="mb-6 p-4 rounded-lg bg-red-500/10 border border-red-500/30 flex items-center gap-3 text-red-500"
        >
          <AlertCircle size={18} />
          <span className="text-sm">{error}</span>
          <button onClick={() => setError("")} className="ml-auto">
            <X size={16} />
          </button>
        </motion.div>
      )}

      {/* Chord Progression Panel */}
      <AnimatePresence>
        {showChordPanel && (
          <motion.div
            initial={{ opacity: 0, height: 0 }}
            animate={{ opacity: 1, height: "auto" }}
            exit={{ opacity: 0, height: 0 }}
            className={`mb-6 rounded-xl overflow-hidden border ${borderColor} ${bgCard}`}
          >
            <div className="p-5">
              <div className="flex items-center justify-between mb-4">
                <h3
                  className={`font-semibold ${textPrimary} flex items-center gap-2`}
                >
                  <Wand2 size={18} className="text-violet-500" />
                  Apply Chord Progression
                </h3>
                <button
                  onClick={() => setShowChordPanel(false)}
                  className={`p-1.5 rounded-lg ${isDark ? "hover:bg-white/10" : "hover:bg-gray-100"}`}
                >
                  <X size={16} className={textMuted} />
                </button>
              </div>

              {/* Mode Toggle */}
              <div
                className={`flex gap-2 mb-4 p-1 rounded-lg ${isDark ? "bg-white/5" : "bg-gray-100"}`}
              >
                <button
                  onClick={() => setProgressionMode("preset")}
                  className={`flex-1 py-2 px-3 rounded-md text-sm font-medium transition-colors
                    ${
                      progressionMode === "preset"
                        ? isDark
                          ? "bg-white/10 text-white"
                          : "bg-white text-gray-900 shadow-sm"
                        : textMuted
                    }`}
                >
                  Common Progressions
                </button>
                <button
                  onClick={() => setProgressionMode("custom")}
                  className={`flex-1 py-2 px-3 rounded-md text-sm font-medium transition-colors
                    ${
                      progressionMode === "custom"
                        ? isDark
                          ? "bg-white/10 text-white"
                          : "bg-white text-gray-900 shadow-sm"
                        : textMuted
                    }`}
                >
                  Build Custom
                </button>
              </div>

              {/* Preset Progressions */}
              {progressionMode === "preset" && (
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-2 mb-4">
                  {COMMON_PROGRESSIONS.map((prog, idx) => (
                    <button
                      key={idx}
                      onClick={() => setSelectedProgression(prog)}
                      className={`p-3 rounded-lg text-left transition-all border
                        ${
                          selectedProgression === prog
                            ? isDark
                              ? "bg-violet-500/20 border-violet-500/50 text-white"
                              : "bg-violet-100 border-violet-400 text-violet-900"
                            : isDark
                              ? "bg-white/5 border-white/10 hover:bg-white/10 text-white"
                              : "bg-gray-50 border-gray-200 hover:bg-gray-100 text-gray-900"
                        }`}
                    >
                      <div className="font-medium text-sm mb-1">
                        {prog.name}
                      </div>
                      <div
                        className={`text-xs ${isDark ? "text-white/60" : "text-gray-500"}`}
                      >
                        {prog.chords.join(" → ")}
                      </div>
                    </button>
                  ))}
                </div>
              )}

              {/* Custom Progression Builder */}
              {progressionMode === "custom" && (
                <div className="mb-4">
                  <div
                    className={`min-h-[48px] p-3 rounded-lg mb-3 flex flex-wrap gap-2 items-center
                    ${isDark ? "bg-white/5 border border-white/10" : "bg-gray-50 border border-gray-200"}`}
                  >
                    {customProgression.length === 0 ? (
                      <span className={textMuted + " text-sm"}>
                        Click chords below to build progression...
                      </span>
                    ) : (
                      customProgression.map((chord, idx) => (
                        <span
                          key={idx}
                          onClick={() => removeFromCustomProgression(idx)}
                          className={`px-3 py-1.5 rounded-lg text-sm font-bold cursor-pointer transition-colors
                            ${
                              isDark
                                ? "bg-amber-500/20 text-amber-400 hover:bg-red-500/20 hover:text-red-400"
                                : "bg-amber-100 text-amber-700 hover:bg-red-100 hover:text-red-700"
                            }`}
                        >
                          {chord} ×
                        </span>
                      ))
                    )}
                  </div>

                  <div className="grid grid-cols-6 sm:grid-cols-12 gap-1">
                    {CHORD_ROOTS.map((root) => (
                      <button
                        key={root}
                        onClick={() => addToCustomProgression(root)}
                        className={`p-2 rounded text-sm font-medium transition-colors
                          ${
                            isDark
                              ? "bg-white/5 hover:bg-white/15 text-white"
                              : "bg-gray-100 hover:bg-gray-200 text-gray-900"
                          }`}
                      >
                        {root}
                      </button>
                    ))}
                  </div>
                  <div className="grid grid-cols-5 gap-1 mt-2">
                    {CHORD_TYPES.slice(1).map((type) => (
                      <button
                        key={type}
                        onClick={() =>
                          customProgression.length > 0 &&
                          setCustomProgression((prev) => {
                            const updated = [...prev];
                            const last = updated[updated.length - 1];
                            if (
                              !CHORD_TYPES.slice(1).some((t) =>
                                last.endsWith(t),
                              )
                            ) {
                              updated[updated.length - 1] = last + type;
                            }
                            return updated;
                          })
                        }
                        className={`p-2 rounded text-xs font-medium transition-colors
                          ${
                            isDark
                              ? "bg-white/5 hover:bg-white/15 text-white"
                              : "bg-gray-100 hover:bg-gray-200 text-gray-900"
                          }`}
                      >
                        +{type}
                      </button>
                    ))}
                  </div>
                </div>
              )}

              {/* Action Buttons */}
              <div className="flex flex-wrap gap-2">
                <button
                  onClick={handleApplyProgression}
                  disabled={
                    (progressionMode === "preset" && !selectedProgression) ||
                    (progressionMode === "custom" &&
                      customProgression.length === 0)
                  }
                  className="px-4 py-2 rounded-lg text-sm font-medium bg-violet-500 hover:bg-violet-600 text-white transition-colors flex items-center gap-2 disabled:opacity-40"
                >
                  <Check size={14} />
                  Apply to Lyrics
                </button>
                <button
                  onClick={handleRemoveChords}
                  className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors flex items-center gap-2
                    ${
                      isDark
                        ? "bg-red-500/20 hover:bg-red-500/30 text-red-400"
                        : "bg-red-100 hover:bg-red-200 text-red-700"
                    }`}
                >
                  <RotateCcw size={14} />
                  Remove All Chords
                </button>
              </div>

              <p className={`mt-3 text-xs ${textMuted}`}>
                💡 Chords apply to each lyric line. Section headers are
                automatically skipped.
              </p>
            </div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* Form */}
      <div className={`rounded-2xl p-6 sm:p-8 border ${borderColor} ${bgCard}`}>
        <div className="space-y-5">
          {/* Title */}
          <div>
            <label
              className={`block text-sm font-medium ${textSecondary} mb-2`}
            >
              Title <span className="text-red-500">*</span>
            </label>
            <input
              type="text"
              value={form.title}
              onChange={(e) => setForm({ ...form, title: e.target.value })}
              placeholder="Enter song title..."
              className={inputClass}
            />
          </div>

          {/* Artist & Key Row */}
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <div>
              <label
                className={`block text-sm font-medium ${textSecondary} mb-2`}
              >
                Artist
              </label>
              <input
                type="text"
                value={form.artist}
                onChange={(e) => setForm({ ...form, artist: e.target.value })}
                placeholder="Original artist..."
                className={inputClass}
              />
            </div>
            <div>
              <label
                className={`block text-sm font-medium ${textSecondary} mb-2`}
              >
                Key
              </label>
              <select
                value={form.key_chord}
                onChange={(e) =>
                  setForm({ ...form, key_chord: e.target.value })
                }
                className={inputClass}
              >
                <option value="">Select key...</option>
                {CHORD_ROOTS.map((root) => (
                  <option key={root} value={root}>
                    {root}
                  </option>
                ))}
                {CHORD_ROOTS.map((root) => (
                  <option key={root + "m"} value={root + "m"}>
                    {root}m
                  </option>
                ))}
              </select>
            </div>
          </div>

          {/* Singer & Band Row */}
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <div>
              <label
                className={`block text-sm font-medium ${textSecondary} mb-2`}
              >
                Singer
              </label>
              <input
                type="text"
                value={form.singer}
                onChange={(e) => setForm({ ...form, singer: e.target.value })}
                placeholder="Who sings this at your church..."
                className={inputClass}
              />
            </div>
            <div>
              <label
                className={`block text-sm font-medium ${textSecondary} mb-2`}
              >
                Band
              </label>
              <input
                type="text"
                value={form.band}
                onChange={(e) => setForm({ ...form, band: e.target.value })}
                placeholder="Hillsong, Bethel, Elevation, etc..."
                className={inputClass}
              />
            </div>
          </div>

          {/* Lyrics - Rich Text Editor */}
          <div>
            <label
              className={`block text-sm font-medium ${textSecondary} mb-2`}
            >
              Lyrics
              <span className={`ml-2 text-xs ${textMuted}`}>
                Copy and paste from any source with formatting preserved
              </span>
            </label>
            <LyricsRichTextEditor
              content={form.lyrics || ""}
              onChange={(html) => setForm({ ...form, lyrics: html })}
              placeholder="Enter your lyrics here... You can paste from Word, websites, or type directly with full formatting support."
            />
          </div>

          {/* Actions */}
          <div className="flex gap-3 pt-4">
            <button
              onClick={handleSave}
              disabled={saving}
              className="flex-1 py-3 rounded-lg bg-cyan-500 hover:bg-cyan-600 disabled:opacity-50 text-white font-medium transition-colors flex items-center justify-center gap-2"
            >
              <Save size={18} />
              {saving ? "Saving..." : isNew ? "Create Song" : "Save Changes"}
            </button>
            <button
              onClick={() => navigate(-1)}
              className={`px-6 py-3 rounded-lg transition-colors
                ${
                  isDark
                    ? "bg-white/10 hover:bg-white/20 text-white"
                    : "bg-gray-100 hover:bg-gray-200 text-gray-900"
                }`}
            >
              Cancel
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
