"use client";

import { useEffect, useState } from "react";

interface UserProfile {
  id: string;
  email: string;
  name: string;
  slackUserId: string | null;
  role: string;
  aboutUser: string | null;
  modelInstructions: string | null;
  hasGithubToken: boolean;
  hasWireguardConfig: boolean;
}

export default function SettingsPage() {
  const [user, setUser] = useState<UserProfile | null>(null);
  const [slackUserId, setSlackUserId] = useState("");
  const [aboutUser, setAboutUser] = useState("");
  const [modelInstructions, setModelInstructions] = useState("");
  const [saving, setSaving] = useState(false);
  const [saved, setSaved] = useState(false);

  // VPN state
  const [hasVpn, setHasVpn] = useState(false);
  const [vpnConfig, setVpnConfig] = useState("");
  const [vpnSaving, setVpnSaving] = useState(false);
  const [vpnSaved, setVpnSaved] = useState(false);
  const [vpnError, setVpnError] = useState("");

  // Claude OAuth state
  const [claudeConnected, setClaudeConnected] = useState(false);
  const [claudeLoading, setClaudeLoading] = useState(false);
  const [claudeAuthUrl, setClaudeAuthUrl] = useState("");
  const [claudeCode, setClaudeCode] = useState("");
  const [claudeError, setClaudeError] = useState("");

  useEffect(() => {
    fetch("/api/users/me")
      .then((r) => r.json())
      .then((data) => {
        setUser(data);
        setSlackUserId(data.slackUserId || "");
        setAboutUser(data.aboutUser || "");
        setModelInstructions(data.modelInstructions || "");
        setHasVpn(data.hasWireguardConfig || false);
      });
    // Check if Claude is connected
    fetch("/api/secrets")
      .then((r) => r.json())
      .then((secrets: any[]) => {
        setClaudeConnected(secrets.some((s) => s.key === "CLAUDE_CODE_OAUTH_TOKEN"));
      });
  }, []);

  async function saveProfile() {
    setSaving(true);
    setSaved(false);
    await fetch("/api/users/me", {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ slackUserId: slackUserId || null, aboutUser: aboutUser || null, modelInstructions: modelInstructions || null }),
    });
    setSaving(false);
    setSaved(true);
    setTimeout(() => setSaved(false), 2000);
  }

  async function startClaudeAuth() {
    setClaudeLoading(true);
    setClaudeError("");
    setClaudeCode("");
    try {
      const res = await fetch("/api/auth/claude");
      const data = await res.json();
      setClaudeAuthUrl(data.authorizeUrl);
    } catch (err: any) {
      setClaudeError(err.message);
    }
    setClaudeLoading(false);
  }

  async function submitClaudeCode() {
    setClaudeLoading(true);
    setClaudeError("");
    try {
      const res = await fetch("/api/auth/claude", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ code: claudeCode }),
      });
      const data = await res.json();
      if (data.connected) {
        setClaudeConnected(true);
        setClaudeAuthUrl("");
        setClaudeCode("");
      } else {
        setClaudeError(data.error || "Failed to connect");
      }
    } catch (err: any) {
      setClaudeError(err.message);
    }
    setClaudeLoading(false);
  }

  async function disconnectClaude() {
    if (!confirm("Disconnect Claude Code? You'll need to re-authorize.")) return;
    await fetch("/api/auth/claude", { method: "DELETE" });
    setClaudeConnected(false);
  }

  async function saveVpnConfig() {
    setVpnSaving(true);
    setVpnError("");
    setVpnSaved(false);
    try {
      const res = await fetch("/api/users/me/vpn", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ config: vpnConfig }),
      });
      if (!res.ok) {
        const data = await res.json();
        setVpnError(data.error || "Failed to save");
      } else {
        setHasVpn(true);
        setVpnConfig("");
        setVpnSaved(true);
        setTimeout(() => setVpnSaved(false), 2000);
      }
    } catch (err: any) {
      setVpnError(err.message);
    }
    setVpnSaving(false);
  }

  async function deleteVpnConfig() {
    if (!confirm("Remove your VPN configuration? Sessions will no longer have VPN access.")) return;
    await fetch("/api/users/me/vpn", { method: "DELETE" });
    setHasVpn(false);
  }

  if (!user) return <div className="container"><p className="text-muted">Loading...</p></div>;

  return (
    <div>
      <h1 className="mb-6">Settings</h1>

      {/* Profile */}
      <div className="card mb-6">
        <h2 className="mb-4">Profile</h2>
        <div className="mb-4">
          <span className="label">Email</span>
          <p>{user.email}</p>
        </div>
        <div className="mb-4">
          <span className="label">Role</span>
          <span className={`badge ${user.role === "ADMIN" ? "badge-warning" : "badge-muted"}`}>{user.role}</span>
        </div>
        <div className="mb-4">
          <label className="label" htmlFor="slackUserId">Slack User ID</label>
          <input
            id="slackUserId"
            className="input"
            value={slackUserId}
            onChange={(e) => setSlackUserId(e.target.value)}
            placeholder="e.g. UPERJQ2JJ"
          />
          <p className="text-muted text-sm mt-1">
            Required for the bot to identify you. Find it in your Slack profile &gt; More &gt; Copy member ID.
          </p>
        </div>
        <div className="mb-4">
          <label className="label" htmlFor="aboutUser">About you</label>
          <textarea
            id="aboutUser"
            className="input"
            value={aboutUser}
            onChange={(e) => setAboutUser(e.target.value)}
            rows={3}
            placeholder="Tell the bot about yourself — your role, responsibilities, preferences..."
          />
          <p className="text-muted text-sm mt-1">
            Context about who you are. Helps the bot tailor its responses to your background.
          </p>
        </div>
        <div className="mb-4">
          <label className="label" htmlFor="modelInstructions">Model instructions</label>
          <textarea
            id="modelInstructions"
            className="input"
            value={modelInstructions}
            onChange={(e) => setModelInstructions(e.target.value)}
            rows={4}
            placeholder="Rules, guidelines, and behavioral directives for the bot..."
          />
          <p className="text-muted text-sm mt-1">
            Instructions the bot should follow. These are appended to the system prompt.
          </p>
        </div>
        <div className="flex gap-2 items-center">
          <button className="btn btn-primary" onClick={saveProfile} disabled={saving}>
            {saving ? "Saving..." : "Save"}
          </button>
          {saved && <span className="text-sm" style={{ color: "var(--success)" }}>Saved</span>}
        </div>
      </div>

      {/* Claude Code OAuth */}
      <div className="card mb-6">
        <div className="flex justify-between items-center mb-4">
          <h2>Claude Code</h2>
          {claudeConnected && <span className="badge badge-success">Connected</span>}
        </div>

        {claudeConnected ? (
          <div>
            <p className="text-muted text-sm mb-4">
              Your Claude Code account is connected. The bot will use your OAuth token when running Claude on your behalf.
            </p>
            <button className="btn btn-danger" onClick={disconnectClaude}>Disconnect</button>
          </div>
        ) : claudeAuthUrl ? (
          <div>
            <p className="text-sm mb-4">
              1. Open this link and authorize the application:<br />
              <a href={claudeAuthUrl} target="_blank" rel="noopener noreferrer" style={{ wordBreak: "break-all" }}>
                {claudeAuthUrl.substring(0, 80)}...
              </a>
            </p>
            <p className="text-sm mb-4">2. Copy the authorization code and paste it below:</p>
            <div className="flex gap-2">
              <input
                className="input"
                value={claudeCode}
                onChange={(e) => setClaudeCode(e.target.value)}
                placeholder="Paste authorization code here..."
              />
              <button className="btn btn-primary" onClick={submitClaudeCode} disabled={claudeLoading || !claudeCode}>
                {claudeLoading ? "Connecting..." : "Connect"}
              </button>
            </div>
          </div>
        ) : (
          <div>
            <p className="text-muted text-sm mb-4">
              Connect your Claude Code account to use the bot. This authorizes the bot to run Claude on your behalf.
            </p>
            <button className="btn btn-primary" onClick={startClaudeAuth} disabled={claudeLoading}>
              {claudeLoading ? "Loading..." : "Connect Claude Code"}
            </button>
          </div>
        )}
        {claudeError && <p className="text-sm mt-2" style={{ color: "var(--danger)" }}>{claudeError}</p>}
      </div>

      {/* VPN (WireGuard) */}
      <div className="card mb-6">
        <div className="flex justify-between items-center mb-4">
          <h2>VPN (WireGuard)</h2>
          {hasVpn && <span className="badge badge-success">Configured</span>}
        </div>

        <p className="text-muted text-sm mb-4">
          Upload your WireGuard configuration to give your bot sessions VPN access.
          This is needed for accessing data sources behind private networks (e.g. client databases).
          The config is stored encrypted — only your sessions can use it.
        </p>

        {hasVpn ? (
          <div>
            <p className="text-sm mb-4">
              Your WireGuard config is saved. Your bot sessions will have VPN access via <code>vpn-exec</code>.
            </p>
            <button className="btn btn-danger" onClick={deleteVpnConfig}>Remove VPN Config</button>
          </div>
        ) : (
          <div>
            <label className="label" htmlFor="vpnConfig">WireGuard config (.conf)</label>
            <textarea
              id="vpnConfig"
              className="input"
              value={vpnConfig}
              onChange={(e) => setVpnConfig(e.target.value)}
              rows={8}
              placeholder={"[Interface]\nPrivateKey = ...\nAddress = ...\n\n[Peer]\nPublicKey = ...\nEndpoint = ...\nAllowedIPs = ..."}
              style={{ fontFamily: "monospace", fontSize: "0.85rem" }}
            />
            <div className="flex gap-2 items-center mt-2">
              <button className="btn btn-primary" onClick={saveVpnConfig} disabled={vpnSaving || !vpnConfig.trim()}>
                {vpnSaving ? "Saving..." : "Save VPN Config"}
              </button>
              {vpnSaved && <span className="text-sm" style={{ color: "var(--success)" }}>Saved</span>}
            </div>
            {vpnError && <p className="text-sm mt-2" style={{ color: "var(--danger)" }}>{vpnError}</p>}
          </div>
        )}
      </div>
    </div>
  );
}
