import React, { useEffect, useState } from "react";
import {
  getCurrentUser,
  updateOwnProfile,
  requestNewPin,
  uploadAvatar,
  API_BASE,
} from "../../api";
import {
  FiSave,
  FiKey,
  FiAtSign,
  FiTag,
  FiUpload,
  FiImage,
  FiAlertTriangle,
  FiDroplet,
  FiRefreshCw,
} from "react-icons/fi";

/* ---------- Theme: Order-Background ---------- */
const DEFAULT_BG1 = "#0a6bff"; // sanftes Blau
const DEFAULT_BG2 = "#00e0aa"; // Türkisgrün

const toBool = (v) => v === true || v === 1 || v === "1" || v === "true";


function readOrderColors() {
  const c1 = localStorage.getItem("order_bg1") || DEFAULT_BG1;
  const c2 = localStorage.getItem("order_bg2") || DEFAULT_BG2;
  return { c1, c2 };
}
function applyOrderColors(c1, c2) {
  document.documentElement.style.setProperty("--order-bg1", c1);
  document.documentElement.style.setProperty("--order-bg2", c2);
  window.dispatchEvent(new CustomEvent("order-bg-change", { detail: { bg1: c1, bg2: c2 } }));
}

/* ---------- Komponente ---------- */
export default function SettingsPage() {
  const [form, setForm] = useState({ alias: "", paypal: "", visible: true });
  const [currentPassword, setCurrentPassword] = useState("");
  const [newPassword, setNewPassword] = useState("");
  const [newPassword2, setNewPassword2] = useState("");
  const [loading, setLoading] = useState(false);
  const [msg, setMsg] = useState(null);

  // Avatar
  const [avatarUrl, setAvatarUrl] = useState(null);
  const [file, setFile] = useState(null);
  const [preview, setPreview] = useState(null);
  const [uploading, setUploading] = useState(false);

  // Theme-Farben
  const initial = readOrderColors();
  const [bg1, setBg1] = useState(initial.c1);
  const [bg2, setBg2] = useState(initial.c2);

  useEffect(() => {
    (async () => {
      const user = await getCurrentUser();
      setForm({
        alias: user.alias || "",
        paypal: user.paypal_email || "",
        visible: toBool(user.public_stats ?? user.visible_in_stats),
      });
      // Avatar-URL absolutieren, falls relativ
      const raw = user.avatar_url || null;
      setAvatarUrl(raw ? (raw.startsWith("http") ? raw : `${API_BASE}${raw}`) : null);

      applyOrderColors(bg1, bg2);
    })();
  }, []);

  function setField(key, val) {
    setForm((f) => ({ ...f, [key]: val }));
  }

  async function save() {
    setLoading(true);
    setMsg(null);

    // Passwortvalidierung 
    if (newPassword || newPassword2 || currentPassword) {
      if (!currentPassword) return stop("Aktuelles Passwort ist erforderlich.");
      if (newPassword.length < 8) return stop("Neues Passwort zu kurz (min. 8 Zeichen).");
      if (newPassword !== newPassword2) return stop("Neue Passwörter stimmen nicht überein.");
    }

    function stop(m) {
      setMsg(m);
      setLoading(false);
      return;
    }

    const vis = toBool(form.visible);
    const patch = {
      alias: form.alias,
      paypal_email: form.paypal,
      public_stats: vis,
      visible_in_stats: vis,
    };

    try {
      await updateOwnProfile(patch);
      const fresh = await getCurrentUser();
      setForm(f => ({ ...f, visible: toBool(fresh.public_stats ?? fresh.visible_in_stats) }));
      setMsg("Änderungen gespeichert.");

      // Theme-Farben persistieren + anwenden
      localStorage.setItem("order_bg1", bg1);
      localStorage.setItem("order_bg2", bg2);
      applyOrderColors(bg1, bg2);

      setMsg("Änderungen gespeichert.");
      setCurrentPassword("");
      setNewPassword("");
      setNewPassword2("");
    } catch (e) {
      setMsg(e?.message || "Fehler beim Speichern.");
    } finally {
      setLoading(false);
    }
  }

  async function handleNewPin() {
    try {
      await requestNewPin();
      setMsg("Neuer PIN wurde angefordert.");
    } catch {
      setMsg("Fehler beim Anfordern des PIN.");
    }
  }

  // --- Avatar ---
  function onFileChange(e) {
    const f = e.target.files?.[0];
    setFile(f || null);
    if (preview) URL.revokeObjectURL(preview);
    setPreview(f ? URL.createObjectURL(f) : null);
  }

  async function onUploadAvatar() {
    if (!file) { setMsg("Bitte zuerst eine Bilddatei auswählen."); return; }
    setUploading(true);
    setMsg(null);
    try {
      const res = await uploadAvatar(file);
      if (res?.avatar_url) {
        const abs = res.avatar_url.startsWith("http") ? res.avatar_url : `${API_BASE}${res.avatar_url}`;
        // Cache-Bust
        setAvatarUrl(`${abs}?v=${Date.now()}`);
        setMsg("Profilbild aktualisiert.");
      } else {
        setMsg("Upload erfolgreich, aber keine Avatar-URL erhalten.");
      }
      setFile(null);
      if (preview) URL.revokeObjectURL(preview);
      setPreview(null);
    } catch (e) {
      setMsg("Fehler beim Hochladen des Profilbilds.");
    } finally {
      setUploading(false);
    }
  }

  function resetColors() {
    setBg1(DEFAULT_BG1);
    setBg2(DEFAULT_BG2);
    applyOrderColors(DEFAULT_BG1, DEFAULT_BG2);
  }

  const gradientStyle = {
    background: `linear-gradient(135deg, ${bg1} 0%, ${bg2} 100%)`,
  };

  return (
    <div
      className="p-4 md:p-6 space-y-6"
      style={{ contentVisibility: "auto", containIntrinsicSize: "900px" }}
    >
      <h1 className="text-white/90 text-xl font-semibold">Einstellungen</h1>

      {/* Panels */}
      <div className="grid gap-6 lg:grid-cols-2">
        {/* Profilbild */}
        <Panel title="Profilbild" icon={FiImage}>
          <div className="flex items-center gap-4">
            <div className="w-24 h-24 rounded-full overflow-hidden bg-slate-800 border border-white/10 flex items-center justify-center">
              {preview ? (
                <img src={preview} alt="Preview" className="w-full h-full object-cover" loading="lazy" decoding="async" />
              ) : avatarUrl ? (
                <img src={avatarUrl} alt="Avatar" className="w-full h-full object-cover" loading="lazy" decoding="async" />
              ) : (
                <span className="text-white/60 text-sm">Kein Bild</span>
              )}
            </div>

            <div className="flex-1">
              <input
                type="file"
                accept="image/*" // PNG/JPEG/GIF/WebP etc.
                onChange={onFileChange}
                className="block w-full text-sm text-white file:mr-4 file:py-2 file:px-3 file:rounded-lg file:border-0 file:bg-cyan-600 file:text-white hover:file:bg-cyan-700"
              />
              <p className="mt-2 text-xs text-white/50">Empfohlen: quadratisch, ≤ 5 MB.</p>
            </div>

            <div>
              <button
                onClick={onUploadAvatar}
                disabled={uploading || !file}
                className="flex items-center gap-2 px-3 py-2 bg-cyan-600 hover:bg-cyan-700 disabled:opacity-50 text-white rounded-lg border border-cyan-400/30"
              >
                <FiUpload /> {uploading ? "Lade hoch…" : "Hochladen"}
              </button>
            </div>
          </div>
        </Panel>

        {/* Theme für Order-Menü */}
        <Panel title="Order-Hintergrund" icon={FiDroplet}>
          <div className="grid sm:grid-cols-2 gap-4">
            <label className="block">
              <div className="text-white/70 text-sm mb-1">Farbe 1</div>
              <input
                type="color"
                value={bg1}
                onChange={(e) => { setBg1(e.target.value); applyOrderColors(e.target.value, bg2); }}
                className="w-full h-10 rounded-lg bg-transparent cursor-pointer border border-white/10"
                title="Primäre Hintergrundfarbe"
              />
            </label>
            <label className="block">
              <div className="text-white/70 text-sm mb-1">Farbe 2</div>
              <input
                type="color"
                value={bg2}
                onChange={(e) => { setBg2(e.target.value); applyOrderColors(bg1, e.target.value); }}
                className="w-full h-10 rounded-lg bg-transparent cursor-pointer border border-white/10"
                title="Sekundäre Hintergrundfarbe"
              />
            </label>
          </div>

          {/* Live-Preview */}
          <div
            className="mt-4 h-24 w-full rounded-xl border border-white/10 shadow-inner"
            style={gradientStyle}
            aria-label="Vorschau Order-Hintergrund"
            title={`${bg1} → ${bg2}`}
          />

          <div className="mt-3 flex gap-2">
            <button
              type="button"
              onClick={resetColors}
              className="inline-flex items-center gap-2 px-3 py-2 rounded-lg bg-white/10 border border-white/10 text-white/90 hover:bg-white/15"
              title="Standardfarben wiederherstellen"
            >
              <FiRefreshCw /> Zurücksetzen
            </button>
            <div className="text-white/50 text-xs self-center">
              Wird gespeichert und sofort angewandt.
            </div>
          </div>
        </Panel>

        {/* Profil-Angaben */}
        <Panel title="Profil" icon={FiTag}>
          <label className="block mb-3">
            <div className="text-white/70 text-sm mb-1">Alias</div>
            <input
              className={`w-full px-3 py-2 rounded-lg border focus:outline-none focus:ring-2 ${
                form.visible
                  ? "bg-white/10 border-white/20 text-white focus:ring-cyan-500"
                  : "bg-white/5 border-white/10 text-white/40 cursor-not-allowed opacity-60"
              }`}
              value={form.alias}
              onChange={(e) => setField("alias", e.target.value)}
              disabled={!form.visible}
            />
          </label>

          <div className="flex items-center justify-between mb-3">
            <span className="text-sm text-white/80">In Statistiken sichtbar</span>
            <button
              type="button"
              onClick={() => setField("visible", !form.visible)}
              className={`relative inline-flex h-6 w-11 items-center rounded-full transition ${
                form.visible ? "bg-cyan-500" : "bg-slate-600"
              }`}
              aria-pressed={form.visible}
              aria-label="Sichtbarkeit umschalten"
              title={form.visible ? "Sichtbar" : "Nicht sichtbar"}
            >
              <span
                className={`inline-block h-4 w-4 transform rounded-full bg-white transition ${
                  form.visible ? "translate-x-6" : "translate-x-1"
                }`}
              />
            </button>
          </div>

          <label className="block">
            <div className="flex items-center gap-2 text-sm text-white/70 mb-1">
              <FiAtSign /> <span>PayPal-Mail</span>
            </div>
            <input
              type="email"
              className="w-full px-3 py-2 rounded-lg bg-white/10 border border-white/20 text-white focus:outline-none focus:ring-2 focus:ring-cyan-500"
              value={form.paypal}
              onChange={(e) => setField("paypal", e.target.value)}
            />
          </label>
        </Panel>

        {/* Sicherheit */}
        <Panel title="Sicherheit" icon={FiKey}>
          <div className="grid gap-3">
            <input
              type="password"
              placeholder="Aktuelles Passwort"
              className="w-full px-3 py-2 rounded-lg bg-white/10 border border-white/20 text-white focus:outline-none focus:ring-2 focus:ring-cyan-500"
              value={currentPassword}
              onChange={(e) => setCurrentPassword(e.target.value)}
            />
            <input
              type="password"
              placeholder="Neues Passwort (min. 8 Zeichen)"
              className="w-full px-3 py-2 rounded-lg bg-white/10 border border-white/20 text-white focus:outline-none focus:ring-2 focus:ring-cyan-500"
              value={newPassword}
              onChange={(e) => setNewPassword(e.target.value)}
            />
            <input
              type="password"
              placeholder="Neues Passwort bestätigen"
              className="w-full px-3 py-2 rounded-lg bg-white/10 border border-white/20 text-white focus:outline-none focus:ring-2 focus:ring-cyan-500"
              value={newPassword2}
              onChange={(e) => setNewPassword2(e.target.value)}
            />
          </div>

          {(newPassword || newPassword2 || currentPassword) && (
            <div className="mt-3 text-xs text-yellow-300 flex items-center gap-2">
              <FiAlertTriangle /> Zum Ändern muss das aktuelle Passwort korrekt eingegeben werden.
            </div>
          )}

          <div className="mt-4">
            <button
              onClick={handleNewPin}
              className="flex items-center gap-2 px-3 py-2 bg-purple-600/80 hover:bg-purple-600 text-white rounded-lg border border-purple-400/30"
            >
              <FiKey /> Neuen PIN anfordern
            </button>
          </div>
        </Panel>
      </div>

      {/* Save */}
      <div className="flex justify-end">
        <button
          onClick={save}
          disabled={loading}
          className="flex items-center gap-2 px-4 py-2 bg-cyan-600 hover:bg-cyan-700 disabled:opacity-50 text-white font-semibold rounded-lg border border-cyan-400/30"
        >
          <FiSave /> {loading ? "Speichern…" : "Speichern"}
        </button>
      </div>

      {msg && <p className="mt-3 text-sm text-cyan-300">{msg}</p>}
    </div>
  );
}

/* ---------- Panel-Baustein ---------- */
function Panel({ title, icon: Icon, children }) {
  return (
    <div className="rounded-2xl bg-white/5 backdrop-blur-md border border-cyan-400/25 shadow-[0_0_0_1px_rgba(34,211,238,0.06)] p-5">
      <div className="flex items-center gap-2 mb-3">
        <Icon className="text-white/80" />
        <h2 className="text-white/90 font-semibold">{title}</h2>
      </div>
      {children}
    </div>
  );
}
