import { useState, useEffect } from "react";
import api from "../api/client";

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

  useEffect(() => {
    api.get("/settings/public-features")
      .then(setSettings)
      .catch((e) => setError(e.message || "Failed to load settings."))
      .finally(() => setLoading(false));
  }, []);

  const handleToggle = async (key, value) => {
    setError("");
    setSuccess("");
    setSaving(true);
    try {
      const updated = await api.put("/settings/public-features", { [key]: value });
      setSettings(updated);
      setSuccess("Settings saved.");
      setTimeout(() => setSuccess(""), 3000);
    } catch (e) {
      setError(e.message || "Failed to save settings.");
    } finally {
      setSaving(false);
    }
  };

  return (
    <div>
      {/* Page header */}
      <div className="mb-6">
        <h1 className="text-2xl font-bold" style={{ color: "var(--text-heading)" }}>
          Public Features
        </h1>
        <p className="text-sm mt-1" style={{ color: "var(--text-muted)" }}>
          Control which public-facing pages are accessible to end-users without requiring a login.
        </p>
      </div>

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

      {loading ? (
        <p className="text-sm" style={{ color: "var(--text-muted)" }}>Loading…</p>
      ) : settings ? (
        <div className="space-y-3">
          <FeatureToggleRow
            title="CloudFlash"
            description="Allows end-users to flash their own devices via USB directly from the browser. When disabled, the CloudFlash page is inaccessible and displays a maintenance message."
            enabled={settings.cloudflash_enabled}
            saving={saving}
            onToggle={(val) => handleToggle("cloudflash_enabled", val)}
            url="/cloudflash"
          />
        </div>
      ) : null}
    </div>
  );
}

function FeatureToggleRow({ title, description, enabled, saving, onToggle, url }) {
  return (
    <div
      className="rounded-lg border p-5"
      style={{ backgroundColor: "var(--bg-card)", borderColor: "var(--border-primary)" }}
    >
      <div className="flex items-start justify-between gap-6">
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2 mb-1">
            <span className="text-sm font-semibold" style={{ color: "var(--text-heading)" }}>
              {title}
            </span>
            <span
              className="px-2 py-0.5 text-xs rounded-full font-medium"
              style={
                enabled
                  ? { backgroundColor: "var(--success-bg)", color: "var(--success-text)" }
                  : { backgroundColor: "var(--bg-card-hover)", color: "var(--text-muted)" }
              }
            >
              {enabled ? "Live" : "Disabled"}
            </span>
          </div>
          <p className="text-xs" style={{ color: "var(--text-muted)" }}>
            {description}
          </p>
          {url && (
            <p className="text-xs mt-1.5 font-mono" style={{ color: "var(--text-link)" }}>
              {url}
            </p>
          )}
        </div>

        {/* Toggle switch */}
        <button
          type="button"
          disabled={saving}
          onClick={() => onToggle(!enabled)}
          className="flex-shrink-0 relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none disabled:opacity-50 cursor-pointer disabled:cursor-not-allowed"
          style={{ backgroundColor: enabled ? "var(--accent)" : "var(--border-primary)" }}
          aria-checked={enabled}
          role="switch"
        >
          <span
            className="inline-block h-4 w-4 transform rounded-full bg-white transition-transform"
            style={{ transform: enabled ? "translateX(20px)" : "translateX(4px)" }}
          />
        </button>
      </div>
    </div>
  );
}
