"use client";

import { useState, useEffect, useCallback } from "react";
import { createPortal } from "react-dom";
import {
  getSettings,
  saveSettings,
  type BeadsMapSettings,
} from "@/lib/settings";

interface SettingsModalProps {
  isOpen: boolean;
  onClose: () => void;
}

export function SettingsModal({ isOpen, onClose }: SettingsModalProps) {
  const [apiKey, setApiKey] = useState("");
  const [voiceId, setVoiceId] = useState("");
  const [model, setModel] = useState("");
  const [showKey, setShowKey] = useState(false);
  const [mounted, setMounted] = useState(false);
  const [isGateProtected, setIsGateProtected] = useState(false);

  // SSR guard for createPortal
  useEffect(() => {
    setMounted(true);
  }, []);

  // Load current settings when modal opens
  useEffect(() => {
    if (isOpen) {
      const s = getSettings();
      setApiKey(s.elevenLabsApiKey || "");
      setVoiceId(s.elevenLabsVoiceId);
      setModel(s.elevenLabsModel);
      setShowKey(false);

      // Check if dashboard is password-protected
      fetch("/api/auth")
        .then((r) => r.json())
        .then((data) => setIsGateProtected(data.protected === true))
        .catch(() => setIsGateProtected(false));
    }
  }, [isOpen]);

  // Escape key
  useEffect(() => {
    if (!isOpen) return;
    const handler = (e: KeyboardEvent) => {
      if (e.key === "Escape") onClose();
    };
    window.addEventListener("keydown", handler);
    return () => window.removeEventListener("keydown", handler);
  }, [isOpen, onClose]);

  const handleLockDashboard = useCallback(async () => {
    try {
      await fetch("/api/auth", { method: "DELETE" });
    } catch {
      // If delete fails, still redirect — middleware will catch it
    }
    window.location.href = "/login";
  }, []);

  const handleSave = useCallback(() => {
    const updates: Partial<BeadsMapSettings> = {
      elevenLabsApiKey: apiKey.trim() || undefined,
      elevenLabsVoiceId: voiceId.trim() || "UgBBYS2sOqTuMpoF3BR0",
      elevenLabsModel: model || "eleven_flash_v2_5",
    };
    saveSettings(updates);
    onClose();
  }, [apiKey, voiceId, model, onClose]);

  if (!isOpen || !mounted) return null;

  return createPortal(
    <div
      className="fixed inset-0 z-[100] flex items-center justify-center"
      style={{ backgroundColor: "rgba(0,0,0,0.4)", backdropFilter: "blur(4px)" }}
      onClick={onClose}
    >
      <div
        className="bg-white dark:bg-zinc-900 rounded-xl shadow-2xl w-[90vw] max-w-md flex flex-col"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div className="flex items-center justify-between px-5 py-3.5 border-b border-zinc-100 dark:border-zinc-800">
          <h2 className="text-sm font-semibold text-zinc-900 dark:text-zinc-100">Settings</h2>
          <button
            onClick={onClose}
            className="p-1 text-zinc-400 dark:text-zinc-400 hover:text-zinc-600 dark:hover:text-zinc-300 transition-colors"
          >
            <svg
              className="w-4 h-4"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
              strokeWidth={2}
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                d="M6 18L18 6M6 6l12 12"
              />
            </svg>
          </button>
        </div>

        {/* Body */}
        <div className="px-5 py-4 space-y-4 overflow-y-auto max-h-[60vh]">
          {/* Section header */}
          <h3 className="text-[11px] font-semibold uppercase tracking-widest text-teal-600 dark:text-teal-400">
            Text-to-Speech
          </h3>

          {/* API Key */}
          <div>
            <label className="block text-xs font-medium text-zinc-700 dark:text-zinc-300 mb-1">
              ElevenLabs API Key
            </label>
            <div className="relative">
              <input
                type={showKey ? "text" : "password"}
                value={apiKey}
                onChange={(e) => setApiKey(e.target.value)}
                placeholder="sk_..."
                className="w-full rounded-lg border border-zinc-200 dark:border-zinc-700 bg-zinc-50 dark:bg-zinc-800 px-3 py-2 text-sm text-zinc-900 dark:text-zinc-100 placeholder:text-zinc-400 dark:placeholder:text-zinc-500 focus:outline-none focus:ring-2 focus:ring-emerald-500/30 focus:border-emerald-500 pr-10"
              />
              <button
                type="button"
                onClick={() => setShowKey((v) => !v)}
                className="absolute right-2 top-1/2 -translate-y-1/2 p-1 text-zinc-400 dark:text-zinc-400 hover:text-zinc-600 dark:hover:text-zinc-300 transition-colors"
                title={showKey ? "Hide key" : "Show key"}
              >
                {showKey ? (
                  <svg
                    className="w-4 h-4"
                    fill="none"
                    viewBox="0 0 24 24"
                    strokeWidth={1.5}
                    stroke="currentColor"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      d="M3.98 8.223A10.477 10.477 0 001.934 12C3.226 16.338 7.244 19.5 12 19.5c.993 0 1.953-.138 2.863-.395M6.228 6.228A10.45 10.45 0 0112 4.5c4.756 0 8.773 3.162 10.065 7.498a10.523 10.523 0 01-4.293 5.774M6.228 6.228L3 3m3.228 3.228l3.65 3.65m7.894 7.894L21 21m-3.228-3.228l-3.65-3.65m0 0a3 3 0 10-4.243-4.243m4.242 4.242L9.88 9.88"
                    />
                  </svg>
                ) : (
                  <svg
                    className="w-4 h-4"
                    fill="none"
                    viewBox="0 0 24 24"
                    strokeWidth={1.5}
                    stroke="currentColor"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      d="M2.036 12.322a1.012 1.012 0 010-.639C3.423 7.51 7.36 4.5 12 4.5c4.638 0 8.573 3.007 9.963 7.178.07.207.07.431 0 .639C20.577 16.49 16.64 19.5 12 19.5c-4.638 0-8.573-3.007-9.963-7.178z"
                    />
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"
                    />
                  </svg>
                )}
              </button>
            </div>
            <p className="mt-1 text-[11px] text-zinc-400 dark:text-zinc-400">
              Get your key at{" "}
              <a
                href="https://elevenlabs.io/app/settings/api-keys"
                target="_blank"
                rel="noopener noreferrer"
                className="underline underline-offset-2 text-teal-500 hover:text-teal-600"
              >
                elevenlabs.io/app/settings
              </a>
            </p>
          </div>

          {/* Voice ID */}
          <div>
            <label className="block text-xs font-medium text-zinc-700 dark:text-zinc-300 mb-1">
              Voice ID
            </label>
            <input
              type="text"
              value={voiceId}
              onChange={(e) => setVoiceId(e.target.value)}
              placeholder="UgBBYS2sOqTuMpoF3BR0"
              className="w-full rounded-lg border border-zinc-200 dark:border-zinc-700 bg-zinc-50 dark:bg-zinc-800 px-3 py-2 text-sm text-zinc-900 dark:text-zinc-100 placeholder:text-zinc-400 dark:placeholder:text-zinc-500 focus:outline-none focus:ring-2 focus:ring-emerald-500/30 focus:border-emerald-500"
            />
            <p className="mt-1 text-[11px] text-zinc-400 dark:text-zinc-400">
              Default: Mark - Natural Conversations. Find voice IDs in the{" "}
              <a
                href="https://elevenlabs.io/app/voice-library"
                target="_blank"
                rel="noopener noreferrer"
                className="underline underline-offset-2 text-teal-500 hover:text-teal-600"
              >
                ElevenLabs Voice Library
              </a>
              .
            </p>
          </div>

          {/* Model */}
          <div>
            <label className="block text-xs font-medium text-zinc-700 dark:text-zinc-300 mb-1">
              Model
            </label>
            <select
              value={model}
              onChange={(e) => setModel(e.target.value)}
              className="w-full rounded-lg border border-zinc-200 dark:border-zinc-700 bg-zinc-50 dark:bg-zinc-800 px-3 py-2 text-sm text-zinc-900 dark:text-zinc-100 focus:outline-none focus:ring-2 focus:ring-emerald-500/30 focus:border-emerald-500"
            >
              <option value="eleven_flash_v2_5">
                Flash v2.5 (default, fastest &amp; cheapest)
              </option>
              <option value="eleven_turbo_v2_5">
                Turbo v2.5 (fast, good quality)
              </option>
              <option value="eleven_multilingual_v2">
                Multilingual v2 (highest quality)
              </option>
            </select>
          </div>

          {/* Divider */}
          <div className="border-t border-zinc-100 dark:border-zinc-800 pt-4">
            <h3 className="text-[11px] font-semibold uppercase tracking-widest text-teal-600 dark:text-teal-400 mb-2">
              Public API
            </h3>
            <p className="text-xs text-zinc-500 dark:text-zinc-400 leading-relaxed">
              Heartbeads exposes a read-only REST API for AI agents, CI/CD
              bots, and integrations.{" "}
              {isGateProtected
                ? "API requests require the dashboard password as a Bearer token. "
                : "No authentication required. "}
              <a
                href="/api/docs"
                target="_blank"
                rel="noopener noreferrer"
                className="underline underline-offset-2 text-teal-500 hover:text-teal-600"
              >
                View API documentation
              </a>
            </p>
          </div>

          {/* Dashboard Access — only shown when password-protected */}
          {isGateProtected && (
            <div className="border-t border-zinc-100 dark:border-zinc-800 pt-4">
              <h3 className="text-[11px] font-semibold uppercase tracking-widest text-teal-600 dark:text-teal-400 mb-2">
                Dashboard Access
              </h3>
              <p className="text-xs text-zinc-500 dark:text-zinc-400 leading-relaxed mb-3">
                This instance is password-protected. The{" "}
                <span className="font-medium text-zinc-600 dark:text-zinc-400">Sign In</span>{" "}
                button in the navbar is for{" "}
                <span className="font-medium text-zinc-600 dark:text-zinc-400">
                  ATProto/Bluesky
                </span>{" "}
                &mdash; used for posting comments, likes, and claiming
                tasks. The dashboard password controls who can view the
                graph and access the API.
              </p>
              <button
                onClick={handleLockDashboard}
                type="button"
                className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg border border-zinc-200 dark:border-zinc-700 text-xs font-medium text-zinc-600 dark:text-zinc-400 hover:bg-zinc-50 dark:hover:bg-zinc-800 hover:border-zinc-300 dark:hover:border-zinc-600 transition-colors"
              >
                <svg
                  className="w-3.5 h-3.5"
                  fill="none"
                  viewBox="0 0 24 24"
                  strokeWidth={1.5}
                  stroke="currentColor"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    d="M16.5 10.5V6.75a4.5 4.5 0 10-9 0v3.75m-.75 11.25h10.5a2.25 2.25 0 002.25-2.25v-6.75a2.25 2.25 0 00-2.25-2.25H6.75a2.25 2.25 0 00-2.25 2.25v6.75a2.25 2.25 0 002.25 2.25z"
                  />
                </svg>
                Lock dashboard
              </button>
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="flex items-center justify-end gap-2 px-5 py-3.5 border-t border-zinc-100 dark:border-zinc-800">
          <button
            onClick={onClose}
            className="px-4 py-2 text-sm font-medium text-zinc-500 dark:text-zinc-400 hover:text-zinc-700 dark:hover:text-zinc-200 rounded-lg hover:bg-zinc-50 dark:hover:bg-zinc-800 transition-colors"
          >
            Cancel
          </button>
          <button
            onClick={handleSave}
            className="px-4 py-2 text-sm font-medium text-white rounded-lg bg-emerald-500 hover:bg-emerald-600 transition-colors"
          >
            Save
          </button>
        </div>
      </div>
    </div>,
    document.body
  );
}
