"use client";

import { useState } from "react";

interface Webhook {
  id: string;
  url: string;
  enabled: boolean;
  events: string[];
  createdAt: string;
}

function detectKind(url: string): { label: string; emoji: string } {
  const u = url.toLowerCase();
  if (u.includes("hooks.slack.com")) return { label: "Slack", emoji: "💬" };
  if (u.includes("discord.com/api/webhooks") || u.includes("discordapp.com/api/webhooks"))
    return { label: "Discord", emoji: "🎮" };
  return { label: "Custom", emoji: "🔗" };
}

export function WebhooksClient({ boardId, initial }: { boardId: string; initial: Webhook[] }) {
  const [hooks, setHooks] = useState<Webhook[]>(initial);
  const [url, setUrl] = useState("");
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState<string | null>(null);
  const [testResult, setTestResult] = useState<Record<string, string>>({});

  async function add() {
    if (!url.trim()) return;
    setBusy(true);
    setErr(null);
    try {
      const r = await fetch(`/api/proxy/webhooks/board/${boardId}`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ url: url.trim() }),
      });
      if (!r.ok) {
        const j = await r.json().catch(() => ({} as any));
        setErr(j.message || `Failed (HTTP ${r.status}).`);
        return;
      }
      const h = await r.json();
      setHooks((arr) => [...arr, h]);
      setUrl("");
    } finally {
      setBusy(false);
    }
  }

  async function toggle(h: Webhook) {
    setHooks((arr) => arr.map((x) => (x.id === h.id ? { ...x, enabled: !x.enabled } : x)));
    await fetch(`/api/proxy/webhooks/${h.id}`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ enabled: !h.enabled }),
    });
  }

  async function remove(h: Webhook) {
    if (!confirm(`Remove this ${detectKind(h.url).label} webhook?`)) return;
    setHooks((arr) => arr.filter((x) => x.id !== h.id));
    await fetch(`/api/proxy/webhooks/${h.id}`, { method: "DELETE" });
  }

  async function test(h: Webhook) {
    setTestResult((s) => ({ ...s, [h.id]: "…" }));
    const r = await fetch(`/api/proxy/webhooks/${h.id}/test`, { method: "POST" });
    const j = await r.json().catch(() => ({}));
    setTestResult((s) => ({ ...s, [h.id]: j.ok ? "✓ sent" : `✗ ${j.status ?? j.error ?? "fail"}` }));
    setTimeout(() => setTestResult((s) => ({ ...s, [h.id]: "" })), 4000);
  }

  return (
    <>
      <div className="bg-ink-800/50 border border-white/10 rounded-xl p-5">
        <h2 className="font-semibold mb-2">Add a webhook</h2>
        <p className="text-xs text-white/40 mb-3">
          Paste a Slack incoming webhook URL, a Discord webhook URL, or any HTTPS endpoint.
          We auto-format for Slack/Discord, otherwise POST raw JSON.
        </p>
        <div className="flex gap-2 flex-wrap">
          <input
            type="url"
            value={url}
            onChange={(e) => setUrl(e.target.value)}
            placeholder="https://hooks.slack.com/services/T…/B…/…"
            className="flex-1 min-w-[280px] px-3 py-2 bg-ink-900 border border-white/10 rounded-lg placeholder-white/30 focus:outline-none focus:border-brand-500"
          />
          <button
            onClick={add}
            disabled={busy || !url.trim()}
            className="bg-brand-500 hover:bg-brand-400 text-ink-950 font-semibold px-4 py-2 rounded-lg disabled:opacity-50"
          >
            {busy ? "Adding…" : "Add"}
          </button>
        </div>
        {err && <p className="text-sm text-red-400 mt-3">{err}</p>}
      </div>

      <div>
        <h2 className="font-semibold mb-3 mt-6">Active webhooks ({hooks.length})</h2>
        {hooks.length === 0 ? (
          <div className="bg-ink-800/30 border border-white/10 rounded-xl p-8 text-center text-white/50">
            <div className="text-3xl mb-2">🔗</div>
            <p className="mb-1">No webhooks yet.</p>
            <p className="text-xs">New feedback fires to your webhook in &lt;1s.</p>
          </div>
        ) : (
          <div className="space-y-2">
            {hooks.map((h) => {
              const k = detectKind(h.url);
              return (
                <div key={h.id} className="bg-ink-800/50 border border-white/10 rounded-lg p-4">
                  <div className="flex items-start gap-3 flex-wrap">
                    <span className="text-xl">{k.emoji}</span>
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2 mb-1 flex-wrap">
                        <span className="font-semibold">{k.label}</span>
                        <span className={`text-xs px-2 py-0.5 rounded-full font-mono border ${
                          h.enabled
                            ? "bg-emerald-500/10 text-emerald-400 border-emerald-500/30"
                            : "bg-white/5 text-white/40 border-white/10"
                        }`}>{h.enabled ? "ENABLED" : "PAUSED"}</span>
                      </div>
                      <p className="text-xs text-white/40 font-mono break-all">{h.url}</p>
                    </div>
                    <div className="flex items-center gap-2">
                      <button
                        onClick={() => test(h)}
                        className="text-xs px-3 py-1.5 rounded-lg bg-ink-900 border border-white/10 hover:border-brand-500/40"
                      >
                        {testResult[h.id] || "Test"}
                      </button>
                      <button
                        onClick={() => toggle(h)}
                        className="text-xs px-3 py-1.5 rounded-lg bg-ink-900 border border-white/10 hover:border-brand-500/40"
                      >
                        {h.enabled ? "Pause" : "Resume"}
                      </button>
                      <button
                        onClick={() => remove(h)}
                        className="text-xs px-3 py-1.5 rounded-lg bg-ink-900 border border-red-500/30 text-red-400 hover:bg-red-500/10"
                      >
                        Remove
                      </button>
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </div>
    </>
  );
}
