"use client";

import { useState, useEffect } from "react";
import crypto from "crypto";
import { getWebhookSettings, saveWebhookSettings } from "@/actions/wholesale";
import { AdminButton } from "@/components/admin/design-system";

type WebhookSettings = { url: string; secret: string; enabled: boolean };

export default function WebhookSettingsSection({ brandId, onMsg }: {
  brandId: string;
  onMsg: (kind: "success" | "error", text: string) => void;
}) {
  const [settings, setSettings] = useState<WebhookSettings>({ url: "", secret: "", enabled: false });
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [testing, setTesting] = useState(false);

  useEffect(() => {
    getWebhookSettings(brandId).then((s: WebhookSettings | null) => {
      if (s) {
        setSettings({ url: s.url ?? "", secret: s.secret ?? "", enabled: s.enabled });
      } else {
        setSettings({ url: "", secret: "", enabled: false });
      }
      setLoading(false);
    });
  }, [brandId]);

  async function handleSave() {
    setSaving(true);
    const result = await saveWebhookSettings({
      brandId,
      url: settings.url,
      secret: settings.secret,
      enabled: settings.enabled,
    });
    setSaving(false);
    if (result.success) {
      onMsg("success", "Webhook settings saved.");
    } else {
      onMsg("error", result.error ?? "Failed to save webhook settings.");
    }
  }

  async function handleTestDispatch() {
    if (!settings.url || !settings.secret) {
      onMsg("error", "Enter both a webhook URL and signing secret before testing.");
      return;
    }
    setTesting(true);
    onMsg("success", "Sending test webhook...");

    const testPayload = {
      event: "order_created",
      test: true,
      brand_id: brandId,
      message: "Test webhook from Route Commerce wholesale portal",
      timestamp: new Date().toISOString(),
      order_id: null,
    };
    const payloadString = JSON.stringify(testPayload);
    const signature = crypto
      .createHmac("sha256", settings.secret)
      .update(payloadString)
      .digest("hex");

    try {
      const res = await fetch(settings.url, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "X-Webhook-Signature": `sha256=${signature}`,
          "X-Webhook-Event": "order_created",
        },
        body: payloadString,
      });
      const responseText = await res.text().catch(() => "");
      if (res.ok) {
        onMsg("success", `Test delivered — ${res.status} response from your endpoint. Check wholesale_sync_log for the logged entry.`);
      } else {
        onMsg("error", `Webhook endpoint returned ${res.status}: ${responseText.slice(0, 120)}`);
      }
    } catch (err) {
      onMsg("error", `Connection failed: ${err instanceof Error ? err.message : "Network error"}`);
    }

    setTesting(false);
  }

  if (loading) {
    return <p className="text-sm text-slate-400">Loading webhook settings...</p>;
  }

  return (
    <div className="space-y-3">
      <div className="flex items-center justify-between">
        <div>
          <p className="text-sm font-medium text-[var(--admin-text-secondary)]">Webhook Enabled</p>
          <p className="text-xs text-[var(--admin-text-muted)]">When disabled, no events are queued or sent.</p>
        </div>
        <button type="button"
          onClick={() => setSettings(s => ({ ...s, enabled: !s.enabled }))}
          aria-label="Toggle webhook"
          className={`relative inline-flex h-7 w-12 items-center rounded-full transition-colors ${settings.enabled ? "bg-[var(--admin-accent)]" : "bg-[var(--admin-border)]"}`}
        >
          <span className={`inline-block h-5 w-5 transform rounded-full bg-white shadow transition-transform ${settings.enabled ? "translate-x-6" : "translate-x-1"}`} />
        </button>
      </div>

      <div>
        <label htmlFor="fld-21-webhook-url"  className="block text-sm font-medium text-[var(--admin-text-secondary)] mb-1">Webhook URL</label>
        <input id="fld-21-webhook-url"  aria-label="Https://your System.com/webhooks/wholesale"
          type="url"
          value={settings.url}
          onChange={e => setSettings(s => ({ ...s, url: e.target.value }))}
          placeholder="https://your-system.com/webhooks/wholesale"
          className="w-full rounded-xl border border-[var(--admin-border)] px-3 py-2 text-sm outline-none focus:border-[var(--admin-accent)]"
        />
      </div>

      <div>
        <label htmlFor="fld-22-signing-secret-hmac-sha256"  className="block text-sm font-medium text-[var(--admin-text-secondary)] mb-1">Signing Secret (HMAC-SHA256)</label>
        <input id="fld-22-signing-secret-hmac-sha256"  aria-label="Leave Blank To Keep Current Secret"
          type="password"
          value={settings.secret}
          onChange={e => setSettings(s => ({ ...s, secret: e.target.value }))}
          placeholder="Leave blank to keep current secret"
          className="w-full rounded-xl border border-[var(--admin-border)] px-3 py-2 text-sm outline-none focus:border-[var(--admin-accent)] font-mono"
        />
        <p className="mt-1 text-xs text-[var(--admin-text-muted)]">
          The receiver should verify the <code className="bg-[var(--admin-bg-subtle)] px-1">X-Webhook-Signature</code> header using this secret.
        </p>
      </div>

      <div className="flex items-center gap-3 pt-1">
        <AdminButton
          onClick={handleSave}
          disabled={saving}
          variant="primary"
          size="sm"
          isLoading={saving}
        >
          {saving ? "Saving..." : "Save Webhook Settings"}
        </AdminButton>
        {settings.enabled && settings.url && (
          <AdminButton
            onClick={handleTestDispatch}
            disabled={testing}
            variant="secondary"
            size="sm"
            isLoading={testing}
          >
            {testing ? "Dispatching..." : "Send Test Webhook"}
          </AdminButton>
        )}
      </div>
    </div>
  );
}
