"use client";

import { useState } from "react";
import { toast } from "sonner";
import { ChevronDown, ChevronUp, RotateCcw } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";

const ALL_EVENTS = ["user.signed_up", "support_ticket.created", "report.filed"] as const;

type AdminWebhookEventType = (typeof ALL_EVENTS)[number];

type Webhook = {
  id: string;
  url: string;
  events: string[];
  active: boolean;
  createdAt: string;
};

type Delivery = {
  id: string;
  event: string;
  statusCode: number | null;
  success: boolean;
  attempts: number;
  createdAt: string;
};

type CreateWebhookResponse = {
  id: string;
  url: string;
  events: string[];
  secret: string;
  active: boolean;
  createdAt: string;
};

function formatDate(iso: string) {
  return new Date(iso).toLocaleDateString(undefined, { year: "numeric", month: "short", day: "numeric" });
}

function formatDateTime(iso: string) {
  return new Date(iso).toLocaleString(undefined, { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" });
}

export function AdminWebhooksManager({ initialWebhooks }: { initialWebhooks: Webhook[] }) {
  const [webhookList, setWebhookList] = useState<Webhook[]>(initialWebhooks);
  const [url, setUrl] = useState("");
  const [selectedEvents, setSelectedEvents] = useState<AdminWebhookEventType[]>([]);
  const [creating, setCreating] = useState(false);
  const [newSecret, setNewSecret] = useState<{ id: string; secret: string } | null>(null);
  const [copied, setCopied] = useState(false);
  const [deliveries, setDeliveries] = useState<Record<string, Delivery[]>>({});
  const [loadingDeliveries, setLoadingDeliveries] = useState<string | null>(null);
  const [expandedDeliveries, setExpandedDeliveries] = useState<Set<string>>(new Set());
  const [redelivering, setRedelivering] = useState<string | null>(null);

  function toggleEvent(event: AdminWebhookEventType) {
    setSelectedEvents((prev) => (prev.includes(event) ? prev.filter((e) => e !== event) : [...prev, event]));
  }

  async function handleCreate(e: React.FormEvent) {
    e.preventDefault();
    if (!url.trim()) return;
    setCreating(true);
    try {
      const res = await fetch("/api/v1/admin/webhooks", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ url: url.trim(), events: selectedEvents }),
      });
      if (!res.ok) {
        const data = await res.json() as { error?: string };
        throw new Error(data.error ?? "Failed to add webhook");
      }
      const data = await res.json() as CreateWebhookResponse;
      setNewSecret({ id: data.id, secret: data.secret });
      setWebhookList((prev) => [
        { id: data.id, url: data.url, events: data.events, active: data.active, createdAt: data.createdAt },
        ...prev,
      ]);
      setUrl("");
      setSelectedEvents([]);
    } catch (err) {
      toast.error(err instanceof Error ? err.message : "Failed to add webhook");
    } finally {
      setCreating(false);
    }
  }

  async function handleDelete(id: string) {
    try {
      const res = await fetch(`/api/v1/admin/webhooks/${id}`, { method: "DELETE" });
      if (!res.ok && res.status !== 204) {
        const data = await res.json() as { error?: string };
        throw new Error(data.error ?? "Failed to delete webhook");
      }
      setWebhookList((prev) => prev.filter((w) => w.id !== id));
      if (newSecret?.id === id) setNewSecret(null);
    } catch (err) {
      toast.error(err instanceof Error ? err.message : "Failed to delete webhook");
    }
  }

  async function handleToggleActive(id: string, currentActive: boolean) {
    try {
      const res = await fetch(`/api/v1/admin/webhooks/${id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ active: !currentActive }),
      });
      if (!res.ok) {
        const data = await res.json() as { error?: string };
        throw new Error(data.error ?? "Failed to update webhook");
      }
      setWebhookList((prev) => prev.map((w) => (w.id === id ? { ...w, active: !currentActive } : w)));
    } catch (err) {
      toast.error(err instanceof Error ? err.message : "Failed to update webhook");
    }
  }

  async function handleCopySecret() {
    if (!newSecret) return;
    try {
      await navigator.clipboard.writeText(newSecret.secret);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch {
      toast.error("Copy failed");
    }
  }

  async function toggleDeliveries(webhookId: string) {
    const isExpanded = expandedDeliveries.has(webhookId);
    if (isExpanded) {
      setExpandedDeliveries((prev) => { const s = new Set(prev); s.delete(webhookId); return s; });
      return;
    }

    setExpandedDeliveries((prev) => new Set([...prev, webhookId]));
    if (deliveries[webhookId]) return;

    setLoadingDeliveries(webhookId);
    try {
      const res = await fetch(`/api/v1/admin/webhooks/${webhookId}/deliveries`);
      if (res.ok) {
        const data = await res.json() as Delivery[];
        setDeliveries((prev) => ({ ...prev, [webhookId]: data }));
      }
    } finally {
      setLoadingDeliveries(null);
    }
  }

  async function handleRedeliver(webhookId: string, deliveryId: string) {
    setRedelivering(deliveryId);
    try {
      const res = await fetch(`/api/v1/admin/webhooks/${webhookId}/redeliver`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ deliveryId }),
      });
      if (res.ok) toast.success("Redelivered");
      else toast.error("Redelivery failed");
    } finally {
      setRedelivering(null);
    }
  }

  return (
    <div className="space-y-8">
      <form onSubmit={handleCreate} className="space-y-4 rounded-xl border p-6">
        <div className="space-y-2">
          <Label htmlFor="admin-webhook-url">Endpoint URL</Label>
          <Input
            id="admin-webhook-url"
            type="url"
            placeholder="https://hooks.slack.com/services/..."
            value={url}
            onChange={(e) => setUrl(e.target.value)}
            maxLength={2048}
            required
          />
        </div>

        <div className="space-y-2">
          <Label>Events</Label>
          <p className="text-xs text-muted-foreground">Leave all unchecked to receive every event.</p>
          <div className="flex flex-wrap gap-3">
            {ALL_EVENTS.map((event) => {
              const checked = selectedEvents.includes(event);
              return (
                <label key={event} className="flex items-center gap-2 cursor-pointer select-none">
                  <input type="checkbox" className="rounded" checked={checked} onChange={() => toggleEvent(event)} />
                  <span className="text-sm font-mono">{event}</span>
                </label>
              );
            })}
          </div>
        </div>

        <Button type="submit" disabled={creating || !url.trim()}>
          {creating ? "Adding…" : "Add webhook"}
        </Button>
      </form>

      {newSecret && (
        <div className="rounded-md border border-yellow-400 bg-yellow-50 p-4 space-y-3 dark:bg-yellow-950 dark:border-yellow-700">
          <p className="text-sm font-medium text-yellow-800 dark:text-yellow-200">
            Save this secret now — it won&apos;t be shown again.
          </p>
          <p className="text-xs text-yellow-700 dark:text-yellow-300">
            Used to verify the X-Epicure-Signature header on each delivery.
          </p>
          <div className="flex items-center gap-2">
            <code className="flex-1 rounded bg-white dark:bg-black border px-3 py-2 text-sm font-mono break-all">
              {newSecret.secret}
            </code>
            <Button type="button" variant="outline" onClick={() => { void handleCopySecret(); }}>
              {copied ? "Copied" : "Copy"}
            </Button>
          </div>
          <Button type="button" variant="ghost" size="sm" onClick={() => setNewSecret(null)} className="text-muted-foreground">
            Dismiss
          </Button>
        </div>
      )}

      {webhookList.length === 0 ? (
        <p className="text-sm text-muted-foreground">No webhooks configured yet.</p>
      ) : (
        <div className="divide-y rounded-md border">
          {webhookList.map((w) => {
            const isExpanded = expandedDeliveries.has(w.id);
            const wDeliveries = deliveries[w.id] ?? [];
            return (
              <div key={w.id} className="px-4 py-3 space-y-2">
                <div className="flex items-start justify-between gap-4">
                  <div className="min-w-0 flex-1 space-y-1">
                    <p className="text-sm font-mono truncate">{w.url}</p>
                    <div className="flex items-center gap-2 text-xs text-muted-foreground">
                      <span>Added {formatDate(w.createdAt)}</span>
                      <span>·</span>
                      <Badge variant={w.active ? "default" : "secondary"} className="text-xs">
                        {w.active ? "Active" : "Inactive"}
                      </Badge>
                    </div>
                    {w.events.length > 0 ? (
                      <div className="flex flex-wrap gap-1 pt-1">
                        {w.events.map((ev) => (
                          <Badge key={ev} variant="outline" className="text-xs font-mono">{ev}</Badge>
                        ))}
                      </div>
                    ) : (
                      <p className="text-xs text-muted-foreground pt-1">All events</p>
                    )}
                  </div>
                  <div className="flex items-center gap-2 shrink-0">
                    <Button type="button" variant="ghost" size="sm" onClick={() => { void toggleDeliveries(w.id); }} className="text-muted-foreground gap-1">
                      {isExpanded ? <ChevronUp className="h-3.5 w-3.5" /> : <ChevronDown className="h-3.5 w-3.5" />}
                      Deliveries
                    </Button>
                    <Button type="button" variant="outline" size="sm" onClick={() => { void handleToggleActive(w.id, w.active); }}>
                      {w.active ? "Disable" : "Enable"}
                    </Button>
                    <Button type="button" variant="destructive" size="sm" onClick={() => { void handleDelete(w.id); }}>
                      Delete
                    </Button>
                  </div>
                </div>

                {isExpanded && (
                  <div className="mt-2 rounded-md border bg-muted/30">
                    {loadingDeliveries === w.id ? (
                      <p className="text-xs text-muted-foreground px-3 py-2">Loading…</p>
                    ) : wDeliveries.length === 0 ? (
                      <p className="text-xs text-muted-foreground px-3 py-2">No deliveries yet.</p>
                    ) : (
                      <div className="divide-y">
                        {wDeliveries.map((d) => (
                          <div key={d.id} className="flex items-center gap-3 px-3 py-2 text-xs">
                            <Badge variant={d.success ? "default" : "destructive"} className="text-xs shrink-0 w-14 justify-center">
                              {d.statusCode ?? "err"}
                            </Badge>
                            <span className="font-mono text-muted-foreground shrink-0">{d.event}</span>
                            <span className="text-muted-foreground flex-1 text-right">{formatDateTime(d.createdAt)}</span>
                            <Button
                              type="button"
                              variant="ghost"
                              size="sm"
                              className="h-6 px-2 shrink-0"
                              disabled={redelivering === d.id}
                              onClick={() => { void handleRedeliver(w.id, d.id); }}
                            >
                              <RotateCcw className="h-3 w-3" />
                            </Button>
                          </div>
                        ))}
                      </div>
                    )}
                  </div>
                )}
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}
