"use client";

import { useState } from "react";
import Link from "next/link";
import { useTranslations } from "next-intl";
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 = [
  "recipe.created",
  "recipe.updated",
  "recipe.published",
  "recipe.deleted",
  "meal_plan.updated",
  "shopping_list.completed",
  "comment.added",
] as const;

type WebhookEventType = (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 WebhooksManager({ initialWebhooks }: { initialWebhooks: Webhook[] }) {
  const t = useTranslations("settingsForm");
  const tCommon = useTranslations("common");
  const [webhookList, setWebhookList] = useState<Webhook[]>(initialWebhooks);
  const [url, setUrl] = useState("");
  const [selectedEvents, setSelectedEvents] = useState<WebhookEventType[]>([]);
  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: WebhookEventType) {
    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/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 ?? t("webhookCreateFailed"));
      }
      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 : t("webhookCreateFailed"));
    } finally {
      setCreating(false);
    }
  }

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

  async function handleToggleActive(id: string, currentActive: boolean) {
    try {
      const res = await fetch(`/api/v1/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 ?? t("webhookUpdateFailed"));
      }
      setWebhookList((prev) =>
        prev.map((w) => (w.id === id ? { ...w, active: !currentActive } : w))
      );
    } catch (err) {
      toast.error(err instanceof Error ? err.message : t("webhookUpdateFailed"));
    }
  }

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

  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/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/webhooks/${webhookId}/redeliver`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ deliveryId }),
      });
      if (res.ok) {
        toast.success(t("redeliverySuccess"));
      } else {
        toast.error(t("redeliveryFailed"));
      }
    } finally {
      setRedelivering(null);
    }
  }

  return (
    <div className="space-y-8">
      <div className="text-sm text-muted-foreground mb-4">
        <Link href="/settings/webhooks/docs" className="text-primary hover:underline">
          {t("webhookDocsLink")}
        </Link>
      </div>

      {/* Create form */}
      <form onSubmit={handleCreate} className="space-y-4">
        <div className="space-y-2">
          <Label htmlFor="webhook-url">{t("endpointUrlLabel")}</Label>
          <Input
            id="webhook-url"
            type="url"
            placeholder={t("webhookUrlPlaceholder")}
            value={url}
            onChange={(e) => setUrl(e.target.value)}
            maxLength={2048}
            required
          />
        </div>

        <div className="space-y-2">
          <Label>{t("eventsLabel")}</Label>
          <p className="text-xs text-muted-foreground">
            {t("eventsHint")}
          </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 ? t("webhookAdding") : t("webhookAddButton")}
        </Button>
      </form>

      {/* New secret reveal */}
      {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">
            {t("secretRevealNotice")}
          </p>
          <p className="text-xs text-yellow-700 dark:text-yellow-300">
            {t("secretUsageHint")}
          </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 ? t("copied") : t("copy")}
            </Button>
          </div>
          <Button type="button" variant="ghost" size="sm" onClick={() => setNewSecret(null)} className="text-muted-foreground">
            {t("dismiss")}
          </Button>
        </div>
      )}

      {/* Webhook list */}
      {webhookList.length === 0 ? (
        <p className="text-sm text-muted-foreground">{t("noWebhooks")}</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>{t("addedOn", { date: formatDate(w.createdAt) })}</span>
                      <span>·</span>
                      <Badge variant={w.active ? "default" : "secondary"} className="text-xs">
                        {w.active ? t("active") : t("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>
                    )}
                    {w.events.length === 0 && (
                      <p className="text-xs text-muted-foreground pt-1">{t("allEvents")}</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" />}
                      {t("deliveries")}
                    </Button>
                    <Button type="button" variant="outline" size="sm" onClick={() => { void handleToggleActive(w.id, w.active); }}>
                      {w.active ? t("disable") : t("enable")}
                    </Button>
                    <Button type="button" variant="destructive" size="sm" onClick={() => { void handleDelete(w.id); }}>
                      {tCommon("delete")}
                    </Button>
                  </div>
                </div>

                {/* Delivery history */}
                {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">{tCommon("loading")}</p>
                    ) : wDeliveries.length === 0 ? (
                      <p className="text-xs text-muted-foreground px-3 py-2">{t("noDeliveriesYet")}</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>
  );
}
