"use client";

import { useState, useEffect } from "react";

type LandingMode = "open" | "exclusive";

export default function AdminLandingPage() {
  const [mode, setMode] = useState<LandingMode>("open");
  const [saving, setSaving] = useState(false);
  const [saved, setSaved] = useState(false);
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch("/api/admin/landing-mode")
      .then((res) => {
        if (!res.ok) throw new Error("Forbidden");
        return res.json();
      })
      .then((data) => {
        setMode(data.mode);
        setLoading(false);
      })
      .catch(() => {
        setError("Failed to load — admin access required.");
        setLoading(false);
      });
  }, []);

  async function handleSave() {
    setSaving(true);
    setSaved(false);
    setError("");
    try {
      const res = await fetch("/api/admin/landing-mode", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ mode }),
      });
      if (!res.ok) {
        const data = await res.json();
        throw new Error(data.error || "Failed to save");
      }
      setSaved(true);
      setTimeout(() => setSaved(false), 3000);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to save");
    } finally {
      setSaving(false);
    }
  }

  return (
    <div
      className="min-h-screen flex items-center justify-center p-6"
      style={{ background: "#080809", color: "#e8e9eb" }}
    >
      <div
        className="w-full max-w-md rounded-xl p-8"
        style={{
          backdropFilter: "blur(12px) saturate(1.2)",
          WebkitBackdropFilter: "blur(12px) saturate(1.2)",
          background: "rgba(255,255,255,0.05)",
          border: "1px solid rgba(255,255,255,0.12)",
          boxShadow: "0 8px 32px rgba(0,0,0,0.3)",
        }}
      >
        <h1 className="text-xl font-semibold mb-1">Landing Page Mode</h1>
        <p className="text-sm text-gray-400 mb-6">
          Control which funnel visitors see on the homepage.
        </p>

        {loading ? (
          <p className="text-sm text-gray-400">Loading...</p>
        ) : error && !saving ? (
          <p className="text-sm text-red-400 mb-4">{error}</p>
        ) : null}

        {!loading && (
          <>
            <fieldset className="space-y-3 mb-6">
              <label
                className={`flex items-center gap-3 rounded-lg px-4 py-3 cursor-pointer transition-colors ${
                  mode === "open"
                    ? "bg-white/10 border border-violet-500/50"
                    : "bg-white/[0.02] border border-white/[0.06] hover:border-white/[0.12]"
                }`}
              >
                <input
                  type="radio"
                  name="landing-mode"
                  value="open"
                  checked={mode === "open"}
                  onChange={() => setMode("open")}
                  className="accent-violet-500"
                />
                <div>
                  <div className="font-medium text-sm">Open Funnel</div>
                  <div className="text-xs text-gray-400">
                    Standard landing page. Anyone can sign up.
                  </div>
                </div>
              </label>

              <label
                className={`flex items-center gap-3 rounded-lg px-4 py-3 cursor-pointer transition-colors ${
                  mode === "exclusive"
                    ? "bg-white/10 border border-violet-500/50"
                    : "bg-white/[0.02] border border-white/[0.06] hover:border-white/[0.12]"
                }`}
              >
                <input
                  type="radio"
                  name="landing-mode"
                  value="exclusive"
                  checked={mode === "exclusive"}
                  onChange={() => setMode("exclusive")}
                  className="accent-violet-500"
                />
                <div>
                  <div className="font-medium text-sm">Exclusive Funnel</div>
                  <div className="text-xs text-gray-400">
                    Waitlist / invite-only landing page.
                  </div>
                </div>
              </label>
            </fieldset>

            <button
              onClick={handleSave}
              disabled={saving}
              className="w-full rounded-lg px-4 py-2.5 text-sm font-medium transition-colors disabled:opacity-50"
              style={{
                background: "rgba(124,58,237,0.8)",
                border: "1px solid rgba(124,58,237,0.5)",
              }}
            >
              {saving ? "Saving..." : "Save & Apply"}
            </button>

            {saved && (
              <p className="text-sm text-green-400 mt-3 text-center">
                Landing mode updated.
              </p>
            )}
          </>
        )}
      </div>
    </div>
  );
}
