"use client";

import { useEffect, useState } from "react";

export default function BarikoiSettingsForm() {
  const [apiKey, setApiKey] = useState("");
  const [baseUrl, setBaseUrl] = useState("https://map.barikoi.com");
  const [tileUrlTemplate, setTileUrlTemplate] = useState(
    "https://map.barikoi.com/tile/{z}/{x}/{y}.png?key={key}"
  );
  const [hasKey, setHasKey] = useState(false);
  const [status, setStatus] = useState<string | null>(null);
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    fetch("/api/settings/barikoi")
      .then((r) => r.json())
      .then((d) => {
        setHasKey(Boolean(d.hasKey));
        if (d.baseUrl) setBaseUrl(d.baseUrl);
        if (d.tileUrlTemplate) setTileUrlTemplate(d.tileUrlTemplate);
      })
      .catch(() => {});
  }, []);

  async function onSave(e: React.FormEvent) {
    e.preventDefault();
    setSaving(true);
    setStatus(null);
    try {
      const res = await fetch("/api/settings/barikoi", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ apiKey, baseUrl, tileUrlTemplate }),
      });
      if (!res.ok) {
        const d = await res.json().catch(() => ({}));
        setStatus(d.error || "Failed to save");
        return;
      }
      setHasKey(true);
      setApiKey("");
      setStatus("Saved. Live map and location views will use this Barikoi API key.");
    } finally {
      setSaving(false);
    }
  }

  return (
    <div className="rounded-xl border border-slate-800 bg-slate-900 p-6 max-w-lg">
      <h2 className="text-lg font-medium mb-1">Barikoi Maps</h2>
      <p className="text-sm text-slate-400 mb-4">
        {hasKey ? (
          <span className="text-emerald-400">An API key is currently saved.</span>
        ) : (
          <span className="text-amber-400">No API key saved yet — live tracking map will not render tiles.</span>
        )}
      </p>
      <form onSubmit={onSave} className="space-y-4">
        <div>
          <label className="block text-xs font-medium text-slate-400 mb-1">Barikoi API Key</label>
          <input
            type="password"
            value={apiKey}
            onChange={(e) => setApiKey(e.target.value)}
            placeholder={hasKey ? "•••••••••••• (enter to replace)" : "Enter Barikoi API key"}
            required
            className="w-full rounded-md bg-slate-800 border border-slate-700 px-3 py-2 text-sm text-slate-100 focus:outline-none focus:ring-2 focus:ring-indigo-500"
          />
        </div>
        <div>
          <label className="block text-xs font-medium text-slate-400 mb-1">Base URL</label>
          <input
            type="url"
            value={baseUrl}
            onChange={(e) => setBaseUrl(e.target.value)}
            className="w-full rounded-md bg-slate-800 border border-slate-700 px-3 py-2 text-sm text-slate-100 focus:outline-none focus:ring-2 focus:ring-indigo-500"
          />
        </div>
        <div>
          <label className="block text-xs font-medium text-slate-400 mb-1">
            Tile URL template
          </label>
          <input
            type="text"
            value={tileUrlTemplate}
            onChange={(e) => setTileUrlTemplate(e.target.value)}
            className="w-full rounded-md bg-slate-800 border border-slate-700 px-3 py-2 text-sm text-slate-100 font-mono focus:outline-none focus:ring-2 focus:ring-indigo-500"
          />
          <p className="text-xs text-slate-500 mt-1">
            Must contain <code>{"{z}"}</code>, <code>{"{x}"}</code>, <code>{"{y}"}</code> and{" "}
            <code>{"{key}"}</code>. Copy the exact raster tile URL from your Barikoi developer
            dashboard — it varies by plan/API version.
          </p>
        </div>
        {status && <p className="text-sm text-slate-300">{status}</p>}
        <button
          type="submit"
          disabled={saving}
          className="rounded-md bg-indigo-600 hover:bg-indigo-500 disabled:opacity-50 text-white text-sm font-medium px-4 py-2 transition"
        >
          {saving ? "Saving..." : "Save key"}
        </button>
      </form>
      <p className="text-xs text-slate-500 mt-4">
        This key is stored server-side and only served to authenticated users with live-location access.
        It is used client-side by the map widget to load Barikoi tiles, so treat it as a publishable map key, not a secret credential.
      </p>
    </div>
  );
}
