"use client";

import { useEffect, useState } from "react";

interface AuthorizedBot {
  id: string;
  botUserId: string;
  name: string;
  createdAt: string;
}

export default function AuthorizedBotsPage() {
  const [bots, setBots] = useState<AuthorizedBot[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  // Form state
  const [showForm, setShowForm] = useState(false);
  const [formName, setFormName] = useState("");
  const [formBotUserId, setFormBotUserId] = useState("");
  const [saving, setSaving] = useState(false);

  async function loadBots() {
    const res = await fetch("/api/authorized-bots");
    setBots(await res.json());
    setLoading(false);
  }

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

  function resetForm() {
    setShowForm(false);
    setFormName("");
    setFormBotUserId("");
    setError("");
  }

  async function handleSave() {
    if (!formBotUserId.trim()) { setError("Bot Slack User ID is required"); return; }
    if (!formName.trim()) { setError("Display name is required"); return; }

    if (!/^U[A-Z0-9]+$/.test(formBotUserId.trim())) {
      setError("Bot Slack User ID must start with 'U' followed by uppercase letters/numbers (e.g. U12345ABC)");
      return;
    }

    setSaving(true);
    setError("");

    try {
      const res = await fetch("/api/authorized-bots", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ botUserId: formBotUserId.trim(), name: formName.trim() }),
      });

      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        setError(data.error || "Failed to save");
        setSaving(false);
        return;
      }

      await loadBots();
      resetForm();
    } catch (err: any) {
      setError(err.message);
    }
    setSaving(false);
  }

  async function handleDelete(id: string, name: string) {
    if (!confirm(`Remove authorized bot "${name}"? It will no longer be able to invoke gemmbot on your behalf.`)) return;
    await fetch(`/api/authorized-bots/${id}`, { method: "DELETE" });
    await loadBots();
  }

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

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

      {/* Info card */}
      <div className="card mb-6">
        <p style={{ marginTop: 0 }}>
          Authorize Slack bots to invoke Gemmbot on your behalf. When an authorized bot mentions Gemmbot,
          the message is processed as if you sent it. You are automatically added to the thread so you can follow up.
        </p>
        <p className="text-muted text-sm" style={{ marginBottom: 0 }}>
          You can also manage authorized bots from Slack using the <code>bots</code> command (e.g. <code>bots add @MyBot</code>).
        </p>
      </div>

      {/* Existing bots */}
      {bots.length > 0 && (
        <div className="mb-6">
          <h2 className="mb-4">Your Authorized Bots</h2>
          {bots.map((bot) => (
            <div key={bot.id} className="card mb-4">
              <div className="flex justify-between items-center">
                <div>
                  <strong>{bot.name}</strong>
                  <span className="badge badge-muted" style={{ marginLeft: "0.75rem" }}>{bot.botUserId}</span>
                </div>
                <button className="btn btn-danger" onClick={() => handleDelete(bot.id, bot.name)} style={{ fontSize: "0.85rem" }}>
                  Remove
                </button>
              </div>
              <p className="text-sm text-muted mt-1">
                Added {new Date(bot.createdAt).toLocaleDateString()}
              </p>
            </div>
          ))}
        </div>
      )}

      {/* Add form */}
      {!showForm ? (
        <div className="card">
          <h2 style={{ marginTop: 0 }}>Add Authorized Bot</h2>
          <p className="text-muted text-sm mb-4">
            To find a bot&apos;s Slack User ID, open the bot&apos;s profile in Slack and look for the ID starting with &quot;U&quot;.
          </p>
          <button className="btn btn-primary" onClick={() => setShowForm(true)}>
            Add Bot
          </button>
        </div>
      ) : (
        <div className="card">
          <div className="flex justify-between items-center mb-4">
            <h2 style={{ marginTop: 0, marginBottom: 0 }}>Add Authorized Bot</h2>
            <button className="btn" onClick={resetForm} style={{ fontSize: "0.85rem" }}>Cancel</button>
          </div>

          <div className="mb-4">
            <label className="label" htmlFor="bot-name">Display Name *</label>
            <input
              id="bot-name"
              className="input"
              value={formName}
              onChange={(e) => setFormName(e.target.value)}
              placeholder="e.g. My Automation Bot"
            />
          </div>

          <div className="mb-4">
            <label className="label" htmlFor="bot-user-id">Bot Slack User ID *</label>
            <input
              id="bot-user-id"
              className="input"
              value={formBotUserId}
              onChange={(e) => setFormBotUserId(e.target.value.toUpperCase())}
              placeholder="e.g. U12345ABC"
              style={{ fontFamily: "var(--font-mono)", maxWidth: "300px" }}
            />
            <p className="text-muted text-sm mt-1">
              The Slack User ID of the bot (starts with &quot;U&quot;). Find it in the bot&apos;s Slack profile.
            </p>
          </div>

          {error && <p className="text-sm mb-4" style={{ color: "var(--danger)" }}>{error}</p>}

          <button className="btn btn-primary" onClick={handleSave} disabled={saving}>
            {saving ? "Saving..." : "Add Bot"}
          </button>
        </div>
      )}
    </div>
  );
}
