import { useState, useEffect } from "react";
import api from "../api/client";
import {
  LANGUAGE_MASTER_LIST,
  getLanguageName,
  formatDuration,
  normalizeColor,
} from "./melodyUtils";

const DEFAULT_NOTE_ASSIGNMENT_COLORS = [
  "#67E8F9", "#5EEAD4", "#6EE7B7", "#86EFAC",
  "#BEF264", "#FDE68A", "#FCD34D", "#FBBF24",
  "#FDBA74", "#FB923C", "#F97316", "#FB7185",
  "#F87171", "#EF4444", "#DC2626", "#B91C1C",
];

const headingStyle = { color: "var(--text-heading)" };
const mutedStyle = { color: "var(--text-muted)" };

export default function MelodySettings() {
  const [settings, setSettings] = useState(null);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState("");
  const [success, setSuccess] = useState("");

  const [langToAdd, setLangToAdd] = useState("");
  const cssColorDefault = (typeof window !== "undefined" && window.getComputedStyle)
    ? getComputedStyle(document.documentElement).getPropertyValue("--color-default").trim()
    : "var(--color-default)";
  const [colorToAdd, setColorToAdd] = useState(cssColorDefault);
  const [colorHexInput, setColorHexInput] = useState(cssColorDefault);
  const [durationToAdd, setDurationToAdd] = useState("");
  const [colorModalBell, setColorModalBell] = useState(null);
  const [modalColor, setModalColor] = useState("#67E8F9");
  const [modalColorInput, setModalColorInput] = useState("#67E8F9");

  useEffect(() => {
    loadSettings();
  }, []);

  const loadSettings = async () => {
    setLoading(true);
    try {
      const data = await api.get("/settings/melody");
      setSettings({
        ...data,
        note_assignment_colors: (data.note_assignment_colors || DEFAULT_NOTE_ASSIGNMENT_COLORS).slice(0, 16),
      });
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  const saveSettings = async (updated) => {
    setSaving(true);
    setError("");
    setSuccess("");
    try {
      const result = await api.put("/settings/melody", updated);
      setSettings(result);
      setSuccess("Settings saved.");
      setTimeout(() => setSuccess(""), 2000);
    } catch (err) {
      setError(err.message);
    } finally {
      setSaving(false);
    }
  };

  const addLanguage = () => {
    if (!langToAdd || settings.available_languages.includes(langToAdd)) return;
    const updated = {
      ...settings,
      available_languages: [...settings.available_languages, langToAdd],
    };
    setLangToAdd("");
    saveSettings(updated);
  };

  const removeLanguage = (code) => {
    if (settings.available_languages.length <= 1) return;
    const updated = {
      ...settings,
      available_languages: settings.available_languages.filter((c) => c !== code),
      primary_language:
        settings.primary_language === code
          ? settings.available_languages.find((c) => c !== code)
          : settings.primary_language,
    };
    saveSettings(updated);
  };

  const setPrimaryLanguage = (code) => {
    saveSettings({ ...settings, primary_language: code });
  };

  const addColor = () => {
    const color = colorHexInput.startsWith("#") ? colorHexInput : `#${colorHexInput}`;
    if (!/^#[0-9A-Fa-f]{6}$/.test(color)) return;
    if (settings.quick_colors.includes(color)) return;
    const updated = {
      ...settings,
      quick_colors: [...settings.quick_colors, color],
    };
    saveSettings(updated);
  };

  const removeColor = (color) => {
    const updated = {
      ...settings,
      quick_colors: settings.quick_colors.filter((c) => c !== color),
    };
    saveSettings(updated);
  };

  const addDuration = () => {
    const val = parseInt(durationToAdd, 10);
    if (isNaN(val) || val < 0) return;
    if (settings.duration_values.includes(val)) return;
    const updated = {
      ...settings,
      duration_values: [...settings.duration_values, val].sort((a, b) => a - b),
    };
    setDurationToAdd("");
    saveSettings(updated);
  };

  const removeDuration = (val) => {
    const updated = {
      ...settings,
      duration_values: settings.duration_values.filter((v) => v !== val),
    };
    saveSettings(updated);
  };

  const openNoteColorModal = (index) => {
    const current = settings.note_assignment_colors?.[index] || DEFAULT_NOTE_ASSIGNMENT_COLORS[index];
    setModalColor(current);
    setModalColorInput(current);
    setColorModalBell(index);
  };

  const applyNoteColor = () => {
    if (colorModalBell == null) return;
    const candidate = modalColorInput.startsWith("#") ? modalColorInput : `#${modalColorInput}`;
    if (!/^#[0-9A-Fa-f]{6}$/.test(candidate)) return;
    const next = [...(settings.note_assignment_colors || DEFAULT_NOTE_ASSIGNMENT_COLORS)];
    next[colorModalBell] = candidate;
    saveSettings({ ...settings, note_assignment_colors: next.slice(0, 16) });
    setColorModalBell(null);
  };

  const resetNoteColor = () => {
    if (colorModalBell == null) return;
    const fallback = DEFAULT_NOTE_ASSIGNMENT_COLORS[colorModalBell];
    setModalColor(fallback);
    setModalColorInput(fallback);
  };

  if (loading) {
    return <div className="text-center py-8" style={mutedStyle}>Loading...</div>;
  }

  if (!settings) {
    return (
      <div className="text-sm rounded-md p-3 border" style={{ backgroundColor: "var(--danger-bg)", borderColor: "var(--danger)", color: "var(--danger-text)" }}>
        {error || "Failed to load settings."}
      </div>
    );
  }

  const availableLangsToAdd = LANGUAGE_MASTER_LIST.filter(
    (l) => !settings.available_languages.includes(l.code)
  );

  const btnPrimary = "px-4 py-2 text-sm rounded-md disabled:opacity-50 disabled:cursor-not-allowed transition-colors";

  return (
    <div>
      <h1 className="text-2xl font-bold mb-6" style={headingStyle}>Melody Settings</h1>

      {error && (
        <div className="text-sm rounded-md p-3 mb-4 border" style={{ backgroundColor: "var(--danger-bg)", borderColor: "var(--danger)", color: "var(--danger-text)" }}>
          {error}
        </div>
      )}
      {success && (
        <div className="text-sm rounded-md p-3 mb-4 border" style={{ backgroundColor: "var(--success-bg)", borderColor: "var(--success)", color: "var(--success-text)" }}>
          {success}
        </div>
      )}

      <div className="grid grid-cols-1 xl:grid-cols-2 gap-6">
        {/* --- Languages Section --- */}
        <section className="ui-section-card">
          <div className="ui-section-card__title-row">
            <h2 className="ui-section-card__header-title">Available Languages</h2>
          </div>
          <div className="space-y-2 mb-4">
            {settings.available_languages.map((code) => (
              <div
                key={code}
                className="flex items-center justify-between px-3 py-2 rounded-md"
                style={{ backgroundColor: "var(--bg-primary)" }}
              >
                <div className="flex items-center gap-3">
                  <span className="text-sm font-mono uppercase w-8" style={mutedStyle}>{code}</span>
                  <span className="text-sm" style={{ color: "var(--text-primary)" }}>{getLanguageName(code)}</span>
                  {settings.primary_language === code && (
                    <span className="px-2 py-0.5 text-xs rounded-full" style={{ backgroundColor: "var(--badge-blue-bg)", color: "var(--badge-blue-text)" }}>Primary</span>
                  )}
                </div>
                <div className="flex items-center gap-2">
                  {settings.primary_language !== code && (
                    <button type="button" onClick={() => setPrimaryLanguage(code)} className="text-xs" style={{ color: "var(--accent)" }} disabled={saving}>Set Primary</button>
                  )}
                  {settings.available_languages.length > 1 && (
                    <button type="button" onClick={() => removeLanguage(code)} className="text-xs" style={{ color: "var(--danger)" }} disabled={saving}>Remove</button>
                  )}
                </div>
              </div>
            ))}
          </div>
          <div className="flex gap-2">
            <select value={langToAdd} onChange={(e) => setLangToAdd(e.target.value)} className="flex-1 px-3 py-2 rounded-md text-sm border">
              <option value="">Select language...</option>
              {availableLangsToAdd.map((l) => (<option key={l.code} value={l.code}>{l.name} ({l.code})</option>))}
            </select>
            <button type="button" onClick={addLanguage} disabled={!langToAdd || saving} className={btnPrimary} style={{ backgroundColor: "var(--btn-primary)", color: "var(--text-white)" }}>Add</button>
          </div>
        </section>

        {/* --- Quick Colors Section --- */}
        <section className="ui-section-card">
          <div className="ui-section-card__title-row">
            <h2 className="ui-section-card__header-title">Quick Selection Colors</h2>
          </div>
          <div className="flex flex-wrap gap-3 mb-4">
            {settings.quick_colors.map((color) => (
              <div key={color} className="relative group">
                <div
                  className="w-10 h-10 rounded-lg border-2 shadow-sm cursor-default"
                  style={{ backgroundColor: normalizeColor(color), borderColor: "var(--border-primary)" }}
                  title={color}
                />
                <button
                  type="button"
                  onClick={() => removeColor(color)}
                  disabled={saving}
                  className="absolute -top-1.5 -right-1.5 w-5 h-5 rounded-full text-xs opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center"
                  style={{ backgroundColor: "var(--danger-btn)", color: "var(--text-white)" }}
                >
                  &times;
                </button>
              </div>
            ))}
          </div>
          <div className="flex items-center gap-2">
            <input
              type="color"
              value={colorToAdd}
              onChange={(e) => { setColorToAdd(e.target.value); setColorHexInput(e.target.value); }}
              className="w-10 h-10 rounded cursor-pointer border"
              style={{ borderColor: "var(--border-primary)" }}
            />
            <input
              type="text"
              value={colorHexInput}
              onChange={(e) => { setColorHexInput(e.target.value); if (/^#[0-9A-Fa-f]{6}$/.test(e.target.value)) setColorToAdd(e.target.value); }}
              placeholder="#RRGGBB"
              className="w-28 px-3 py-2 rounded-md text-sm font-mono border"
            />
            <button type="button" onClick={addColor} disabled={saving} className={btnPrimary} style={{ backgroundColor: "var(--btn-primary)", color: "var(--text-white)" }}>Add</button>
          </div>
        </section>

        {/* --- Duration Presets Section --- */}
        <section className="ui-section-card xl:col-span-2">
          <div className="ui-section-card__title-row">
            <h2 className="ui-section-card__header-title">Duration Presets (seconds)</h2>
          </div>
          <div className="flex flex-wrap gap-2 mb-4">
            {settings.duration_values.map((val) => (
              <div
                key={val}
                className="group flex items-center gap-1 px-3 py-1.5 rounded-full border"
                style={{ backgroundColor: "var(--bg-primary)", borderColor: "var(--border-secondary)" }}
              >
                <span className="text-sm" style={{ color: "var(--text-primary)" }}>{formatDuration(val)}</span>
                <span className="text-xs ml-1" style={mutedStyle}>({val}s)</span>
                <button
                  type="button"
                  onClick={() => removeDuration(val)}
                  disabled={saving}
                  className="ml-1 opacity-0 group-hover:opacity-100 transition-opacity text-xs"
                  style={{ color: "var(--danger)" }}
                >
                  &times;
                </button>
              </div>
            ))}
          </div>
          <div className="flex items-center gap-2">
            <input
              type="number"
              min="0"
              value={durationToAdd}
              onChange={(e) => setDurationToAdd(e.target.value)}
              onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); addDuration(); } }}
              placeholder="Seconds (e.g. 45)"
              className="w-40 px-3 py-2 rounded-md text-sm border"
            />
            <button type="button" onClick={addDuration} disabled={saving || !durationToAdd} className={btnPrimary} style={{ backgroundColor: "var(--btn-primary)", color: "var(--text-white)" }}>Add</button>
          </div>
        </section>

        {/* --- Note Assignment Colors --- */}
        <section className="ui-section-card xl:col-span-2">
          <div className="ui-section-card__title-row">
            <h2 className="ui-section-card__header-title">Note Assignment Color Coding</h2>
          </div>
          <p className="text-xs mb-4" style={mutedStyle}>
            Colors used in Composer, Playback, and View table dots. Click a bell to customize.
          </p>
          <div className="grid gap-3" style={{ gridTemplateColumns: "repeat(auto-fill, minmax(86px, 1fr))" }}>
            {Array.from({ length: 16 }, (_, idx) => {
              const color = settings.note_assignment_colors?.[idx] || DEFAULT_NOTE_ASSIGNMENT_COLORS[idx];
              return (
                <button
                  key={idx}
                  type="button"
                  onClick={() => openNoteColorModal(idx)}
                  className="flex flex-col items-center gap-1.5 rounded-md py-2 border"
                  style={{ borderColor: "var(--border-primary)", backgroundColor: "var(--bg-primary)" }}
                  title={`Bell ${idx + 1}`}
                >
                  <span
                    className="inline-flex items-center justify-center rounded-full text-xs font-semibold"
                    style={{
                      width: "30px",
                      height: "30px",
                      backgroundColor: color,
                      color: "#111827",
                      boxShadow: `0 0 8px 2px ${color}66`,
                    }}
                  >
                    {idx + 1}
                  </span>
                  <span className="text-[11px] font-mono" style={{ color: "var(--text-muted)" }}>
                    {color}
                  </span>
                </button>
              );
            })}
          </div>
        </section>
      </div>

      {colorModalBell != null && (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center p-4"
          style={{ backgroundColor: "rgba(0,0,0,0.55)" }}
          onClick={() => setColorModalBell(null)}
        >
          <div
            className="w-full max-w-md rounded-lg border shadow-xl p-5"
            style={{ backgroundColor: "var(--bg-card)", borderColor: "var(--border-primary)" }}
            onClick={(e) => e.stopPropagation()}
          >
            <h3 className="text-base font-semibold mb-1" style={headingStyle}>Bell {colorModalBell + 1} Color</h3>
            <p className="text-xs mb-4" style={mutedStyle}>Pick a custom color for this bell number.</p>
            <div className="flex items-center gap-3 mb-4">
              <input
                type="color"
                value={modalColor}
                onChange={(e) => { setModalColor(e.target.value); setModalColorInput(e.target.value); }}
                className="w-14 h-10 rounded cursor-pointer border"
                style={{ borderColor: "var(--border-primary)" }}
              />
              <input
                type="text"
                value={modalColorInput}
                onChange={(e) => {
                  const v = e.target.value;
                  setModalColorInput(v);
                  if (/^#[0-9A-Fa-f]{6}$/.test(v)) setModalColor(v);
                }}
                className="flex-1 px-3 py-2 rounded-md text-sm font-mono border"
              />
              <span
                className="inline-flex items-center justify-center rounded-full text-xs font-semibold"
                style={{ width: "30px", height: "30px", backgroundColor: modalColor, color: "#111827" }}
              >
                {colorModalBell + 1}
              </span>
            </div>
            <div className="flex justify-end gap-2">
              <button
                type="button"
                onClick={resetNoteColor}
                className="px-3 py-1.5 text-sm rounded-md border"
                style={{ borderColor: "var(--border-primary)", color: "var(--text-secondary)", backgroundColor: "var(--bg-card-hover)" }}
              >
                Reset
              </button>
              <button
                type="button"
                onClick={() => setColorModalBell(null)}
                className="px-3 py-1.5 text-sm rounded-md border"
                style={{ borderColor: "var(--border-primary)", color: "var(--text-secondary)", backgroundColor: "var(--bg-card-hover)" }}
              >
                Cancel
              </button>
              <button
                type="button"
                onClick={applyNoteColor}
                disabled={!/^#[0-9A-Fa-f]{6}$/.test(modalColorInput.startsWith("#") ? modalColorInput : `#${modalColorInput}`)}
                className="px-3 py-1.5 text-sm rounded-md"
                style={{ backgroundColor: "var(--btn-primary)", color: "var(--text-white)" }}
              >
                Save Color
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
