"use client";

import { useEffect, useState } from "react";
import { ApiError, get, post, put } from "@/lib/api";
import { Badge, Field, Notice, Spinner } from "@/components/ui";

type SlackStatus = { channel: string; webhookSet: boolean; configured: boolean };
type TestResult = { ok: boolean; detail?: string; error?: string };

export default function SlackSettings() {
  const [data, setData] = useState<SlackStatus | null>(null);
  const [channel, setChannel] = useState("");
  const [webhookUrl, setWebhookUrl] = useState("");
  const [errors, setErrors] = useState<string[]>([]);
  const [saved, setSaved] = useState(false);
  const [busy, setBusy] = useState(false);
  const [test, setTest] = useState<TestResult | null>(null);
  const [testBusy, setTestBusy] = useState(false);
  const [loadError, setLoadError] = useState<string | null>(null);

  function hydrate(d: SlackStatus) {
    setData(d);
    setChannel(d.channel);
    setWebhookUrl(""); // write-only — never prefilled
  }

  useEffect(() => {
    get<SlackStatus>("slack").then(hydrate).catch((e) => setLoadError((e as Error).message));
  }, []);

  if (loadError) return <Notice kind="error">Could not load Slack config: {loadError}</Notice>;
  if (!data) return <Spinner label="Loading Slack configuration…" />;

  async function save(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setBusy(true);
    setSaved(false);
    setErrors([]);
    const payload: Record<string, string> = { channel };
    if (webhookUrl !== "") payload.webhookUrl = webhookUrl;
    try {
      hydrate(await put<SlackStatus>("slack", payload));
      setSaved(true);
    } catch (err) {
      setErrors(err instanceof ApiError && err.errors.length ? err.errors : [(err as Error).message]);
    } finally {
      setBusy(false);
    }
  }

  async function runTest() {
    setTestBusy(true);
    setTest(null);
    try {
      setTest(await post<TestResult>("slack/test"));
    } catch (err) {
      setTest({ ok: false, error: (err as Error).message });
    } finally {
      setTestBusy(false);
    }
  }

  return (
    <section aria-labelledby="slack-h" className="space-y-6">
      <h2 id="slack-h" className="text-xl font-semibold text-slate-900">Slack notifications</h2>
      <p className="-mt-4 text-sm text-slate-600">
        Terminal Ergonode-push failures and the cost kill-switch post here. Without a webhook, alerts are logged instead of sent.
      </p>

      {saved && <Notice kind="success">Slack configuration saved.</Notice>}
      {errors.length > 0 && <Notice kind="error"><ul className="list-disc pl-5">{errors.map((er, i) => <li key={i}>{er}</li>)}</ul></Notice>}

      <form onSubmit={save} className="space-y-6">
        <div className="card grid gap-5 sm:grid-cols-2">
          <Field label="IT channel" htmlFor="slack-channel" hint="e.g. #it-alerts">
            <input id="slack-channel" value={channel} onChange={(e) => setChannel(e.target.value)} className="input" autoComplete="off" />
          </Field>
          <Field
            label="Incoming webhook URL"
            htmlFor="slack-webhook"
            hint={data.webhookSet ? "A webhook is stored. Leave blank to keep it." : "Paste a Slack incoming-webhook URL."}
          >
            <input
              id="slack-webhook"
              type="password"
              value={webhookUrl}
              onChange={(e) => setWebhookUrl(e.target.value)}
              placeholder={data.webhookSet ? "•••••••• (set)" : "https://hooks.slack.com/services/…"}
              className="input"
              autoComplete="new-password"
            />
          </Field>
        </div>

        <p className="text-xs text-slate-500">
          Status: {data.configured ? <Badge kind="ok">webhook set</Badge> : <Badge kind="warn">log-only</Badge>}. The webhook URL is
          write-only — stored in the config store for the PoC; move it to the Digt secrets store in production.
        </p>

        <div className="flex flex-wrap gap-3">
          <button type="submit" className="btn-primary" disabled={busy}>{busy ? "Saving…" : "Save Slack settings"}</button>
          <button type="button" className="btn-secondary" onClick={runTest} disabled={testBusy}>{testBusy ? "Sending…" : "Send test message"}</button>
        </div>
      </form>

      {test && (
        <div className="card" aria-live="polite">
          <h3 className="mb-1 font-semibold text-slate-900">
            Test message {test.ok ? <Badge kind="ok">sent</Badge> : <Badge kind="danger">not sent</Badge>}
          </h3>
          <p className="text-sm text-slate-600">{test.detail || test.error}</p>
        </div>
      )}
    </section>
  );
}
