"use client";

import { useEffect, useState } from "react";

interface SetupStatus {
  name: string;
  authMode: string;
  hasSlackBotToken: boolean;
  hasSlackAppToken: boolean;
  slackConfigured: boolean;
  githubAppId: string;
  githubAppInstallId: string;
  hasGithubAppPrivateKey: boolean;
}

export default function AdminSetupPage() {
  const [status, setStatus] = useState<SetupStatus | null>(null);
  const [loading, setLoading] = useState(true);

  // Slack fields
  const [savingSlack, setSavingSlack] = useState(false);
  const [slackMessage, setSlackMessage] = useState("");
  const [botToken, setBotToken] = useState("");
  const [appToken, setAppToken] = useState("");

  // GitHub App fields
  const [savingGithub, setSavingGithub] = useState(false);
  const [githubMessage, setGithubMessage] = useState("");
  const [githubAppId, setGithubAppId] = useState("");
  const [githubAppInstallId, setGithubAppInstallId] = useState("");
  const [githubAppPrivateKey, setGithubAppPrivateKey] = useState("");

  async function loadStatus() {
    const res = await fetch("/api/admin/setup");
    if (res.ok) {
      const data = await res.json();
      setStatus(data);
      setGithubAppId(data.githubAppId);
      setGithubAppInstallId(data.githubAppInstallId);
    }
    setLoading(false);
  }

  useEffect(() => { loadStatus(); }, []);

  async function saveSlackTokens() {
    if (!botToken && !appToken) return;
    setSavingSlack(true);
    setSlackMessage("");

    const body: Record<string, string> = {};
    if (botToken) body.slackBotToken = botToken;
    if (appToken) body.slackAppToken = appToken;

    const res = await fetch("/api/admin/setup", {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(body),
    });

    if (res.ok) {
      const data = await res.json().catch(() => ({}));
      const restartMsg = data.restarted
        ? "The bot is restarting to apply the new tokens."
        : "Tokens saved (bot restart may be needed).";
      setSlackMessage(`Slack tokens saved. ${restartMsg}`);
      setBotToken("");
      setAppToken("");
      await loadStatus();
    } else {
      const data = await res.json().catch(() => ({}));
      setSlackMessage(`Error: ${data.error || "Failed to save"}`);
    }
    setSavingSlack(false);
  }

  async function saveGithubConfig() {
    setSavingGithub(true);
    setGithubMessage("");

    const body: Record<string, string> = {};
    if (githubAppId !== (status?.githubAppId || "")) body.githubAppId = githubAppId;
    if (githubAppInstallId !== (status?.githubAppInstallId || "")) body.githubAppInstallId = githubAppInstallId;
    if (githubAppPrivateKey) body.githubAppPrivateKey = githubAppPrivateKey;

    if (Object.keys(body).length === 0) {
      setGithubMessage("No changes to save.");
      setSavingGithub(false);
      return;
    }

    const res = await fetch("/api/admin/setup", {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(body),
    });

    if (res.ok) {
      setGithubMessage("GitHub App config saved.");
      setGithubAppPrivateKey("");
      await loadStatus();
    } else {
      const data = await res.json().catch(() => ({}));
      setGithubMessage(`Error: ${data.error || "Failed to save"}`);
    }
    setSavingGithub(false);
  }

  if (loading) return <div><p className="text-muted">Loading...</p></div>;
  if (!status) return <div><p className="text-muted">No deployment found.</p></div>;

  const inputStyle = { width: "100%", padding: "0.5rem", borderRadius: "0.375rem", border: "1px solid var(--border)" };
  const labelStyle = { display: "block" as const, marginBottom: "0.25rem", fontWeight: 500 };

  const githubConfigured = !!status.githubAppId && !!status.githubAppInstallId && status.hasGithubAppPrivateKey;

  return (
    <div>
      <h1>Setup</h1>

      <div className="card mb-6">
        <h2 style={{ marginTop: 0 }}>Deployment</h2>
        <p><strong>Name:</strong> {status.name}</p>
        <p><strong>Auth mode:</strong> {status.authMode}</p>
      </div>

      <div className="card mb-6">
        <h2 style={{ marginTop: 0 }}>Slack Connection</h2>

        {status.slackConfigured ? (
          <div className="mb-4">
            <p>
              <span className="badge badge-success">Connected</span>
              {" "}Slack tokens are configured. The bot should be connected.
            </p>
            <p className="text-muted text-sm">
              To update tokens, enter new values below. Leave a field empty to keep the current value.
            </p>
          </div>
        ) : (
          <div className="mb-4">
            <p>
              <span className="badge badge-danger">Not configured</span>
              {" "}Enter your Slack app credentials to connect the bot.
            </p>
            <p className="text-muted text-sm">
              Create a Slack app with Socket Mode enabled, then paste the tokens here.
              The bot will connect automatically once both tokens are saved.
            </p>
          </div>
        )}

        <div className="mb-4">
          <label htmlFor="botToken" style={labelStyle}>Bot User OAuth Token</label>
          <input
            id="botToken"
            type="password"
            placeholder={status.hasSlackBotToken ? "••••••••••• (configured)" : "xoxb-..."}
            value={botToken}
            onChange={(e) => setBotToken(e.target.value)}
            style={inputStyle}
          />
        </div>

        <div className="mb-4">
          <label htmlFor="appToken" style={labelStyle}>App-Level Token (Socket Mode)</label>
          <input
            id="appToken"
            type="password"
            placeholder={status.hasSlackAppToken ? "••••••••••• (configured)" : "xapp-..."}
            value={appToken}
            onChange={(e) => setAppToken(e.target.value)}
            style={inputStyle}
          />
        </div>

        <button className="btn" onClick={saveSlackTokens} disabled={savingSlack || (!botToken && !appToken)}>
          {savingSlack ? "Saving..." : "Save Slack Tokens"}
        </button>

        {slackMessage && (
          <p className={`mt-4 ${slackMessage.startsWith("Error") ? "text-danger" : "text-success"}`}>
            {slackMessage}
          </p>
        )}
      </div>

      <div className="card mb-6">
        <h2 style={{ marginTop: 0 }}>GitHub App</h2>

        {githubConfigured ? (
          <div className="mb-4">
            <p>
              <span className="badge badge-success">Configured</span>
              {" "}GitHub App is set up. Bot sessions will have GitHub access.
            </p>
            <p className="text-muted text-sm">
              To update, change the values below. Leave the private key empty to keep the current value.
            </p>
          </div>
        ) : (
          <div className="mb-4">
            <p>
              <span className="badge badge-warning">Optional</span>
              {" "}Configure a GitHub App to give bot sessions access to your repositories.
            </p>
            <p className="text-muted text-sm">
              Create a GitHub App for your org, install it on desired repos, then enter the details here.
            </p>
          </div>
        )}

        <div className="mb-4">
          <label htmlFor="githubAppId" style={labelStyle}>App ID</label>
          <input
            id="githubAppId"
            type="text"
            placeholder="123456"
            value={githubAppId}
            onChange={(e) => setGithubAppId(e.target.value)}
            style={inputStyle}
          />
        </div>

        <div className="mb-4">
          <label htmlFor="githubAppInstallId" style={labelStyle}>Installation ID</label>
          <input
            id="githubAppInstallId"
            type="text"
            placeholder="12345678"
            value={githubAppInstallId}
            onChange={(e) => setGithubAppInstallId(e.target.value)}
            style={inputStyle}
          />
        </div>

        <div className="mb-4">
          <label htmlFor="githubAppPrivateKey" style={labelStyle}>Private Key (PEM)</label>
          <textarea
            id="githubAppPrivateKey"
            placeholder={status.hasGithubAppPrivateKey ? "••••••••••• (configured)" : "-----BEGIN RSA PRIVATE KEY-----\n..."}
            value={githubAppPrivateKey}
            onChange={(e) => setGithubAppPrivateKey(e.target.value)}
            rows={4}
            style={{ ...inputStyle, fontFamily: "monospace", fontSize: "0.85rem", resize: "vertical" }}
          />
        </div>

        <button className="btn" onClick={saveGithubConfig} disabled={savingGithub}>
          {savingGithub ? "Saving..." : "Save GitHub App Config"}
        </button>

        {githubMessage && (
          <p className={`mt-4 ${githubMessage.startsWith("Error") ? "text-danger" : "text-success"}`}>
            {githubMessage}
          </p>
        )}
      </div>
    </div>
  );
}
