import { useEffect, useState } from "react";
import { useToast } from "../toast";

export default function Settings() {
  const toast = useToast();
  const [apiBase, setApiBase] = useState("");
  const [light, setLight] = useState(false);

  useEffect(() => {
    setApiBase(localStorage.getItem("apiBase") || "");
    setLight(document.documentElement.classList.contains("light"));
  }, []);

  const save = () => {
    localStorage.setItem("apiBase", apiBase);
    toast("Saved API base — reload for WS");
  };

  const toggleTheme = () => {
    const next = !light;
    setLight(next);
    document.documentElement.classList.toggle("light", next);
    document.documentElement.classList.toggle("dark", !next);
    localStorage.setItem("theme", next ? "light" : "dark");
    toast(next ? "Light" : "Dark");
  };

  return (
    <div className="glass max-w-xl space-y-6 p-6">
      <h1 className="font-display text-2xl font-bold">Settings</h1>
      <label className="block text-sm">
        API base (empty = same host)
        <input
          value={apiBase}
          onChange={(e) => setApiBase(e.target.value)}
          className="mt-1 w-full rounded-2xl border border-white/10 bg-black/25 px-4 py-2"
          placeholder="http://192.168.4.1"
        />
      </label>
      <button type="button" onClick={save} className="rounded-2xl bg-bubble-accent px-4 py-2 font-semibold">
        Save
      </button>
      <div className="flex items-center justify-between rounded-2xl border border-white/10 bg-black/20 px-4 py-3">
        <span className="text-sm">Theme</span>
        <button type="button" onClick={toggleTheme} className="rounded-full border border-white/15 px-4 py-1 text-sm">
          {light ? "Switch to dark" : "Switch to light"}
        </button>
      </div>
      <p className="text-xs text-slate-500">
        Firmware opens a <strong>password-free</strong> SoftAP named <strong>PN532-Toolkit</strong> (lab
        default). mDNS: <code>pn532tool.local</code>
      </p>
    </div>
  );
}
