"use client";

import { useCallback, useEffect, useState } from "react";
import { toast } from "sonner";
import { Loader2 as Loader, Webhook, Trash2, Activity, Play, Copy } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardBody, CardHeader, CardTitle } from "@/components/ui/card";
import { Input, Label } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";

type WebhookEndpoint = {
  id: string;
  url: string;
  active: boolean;
  events: string[];
  createdAt: string;
  _count: {
    logs: number;
  };
};

type WebhookLog = {
  id: string;
  event: string;
  payload: any;
  status: number;
  response: string | null;
  createdAt: string;
};

export default function WebhooksPage() {
  const [endpoints, setEndpoints] = useState<WebhookEndpoint[]>([]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  
  const [selectedEndpointId, setSelectedEndpointId] = useState<string | null>(null);
  const [logs, setLogs] = useState<WebhookLog[]>([]);
  const [loadingLogs, setLoadingLogs] = useState(false);

  const load = useCallback(async () => {
    setLoading(true);
    const res = await fetch("/api/settings/webhooks");
    const j = await res.json().catch(() => ({}));
    if (res.ok) setEndpoints(j.endpoints ?? []);
    else toast.error(j.error ?? "Failed to load webhooks.");
    setLoading(false);
  }, []);

  useEffect(() => {
    load();
  }, [load]);

  async function create(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    const form = e.currentTarget;
    setSaving(true);
    const data: Record<string, string> = {};
    for (const [k, v] of new FormData(form).entries()) data[k] = String(v);
    
    const res = await fetch("/api/settings/webhooks", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ url: data.url, secret: data.secret || undefined, events: ["all"] }),
    });
    
    const j = await res.json().catch(() => ({}));
    setSaving(false);
    if (!res.ok) return toast.error(j.error ?? "Create failed.");
    toast.success("Webhook endpoint created.");
    form.reset();
    load();
  }

  async function remove(id: string) {
    if (!confirm("Delete this webhook endpoint? This cannot be undone.")) return;
    const res = await fetch("/api/settings/webhooks", {
      method: "DELETE",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ id }),
    });
    if (!res.ok) return toast.error("Delete failed.");
    toast.success("Webhook endpoint deleted.");
    if (selectedEndpointId === id) setSelectedEndpointId(null);
    load();
  }

  async function toggleActive(id: string, active: boolean) {
    const res = await fetch("/api/settings/webhooks", {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ id, active }),
    });
    if (!res.ok) return toast.error("Update failed.");
    load();
  }

  async function loadLogs(id: string) {
    setSelectedEndpointId(id);
    setLoadingLogs(true);
    const res = await fetch(`/api/settings/webhooks/${id}/logs`);
    const j = await res.json().catch(() => ({}));
    if (res.ok) setLogs(j.logs ?? []);
    else toast.error(j.error ?? "Failed to load logs.");
    setLoadingLogs(false);
  }

  return (
    <div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
      <div className="space-y-4">
        <Card>
          <CardHeader>
            <CardTitle>Create Incoming Webhook</CardTitle>
          </CardHeader>
          <CardBody>
            <form onSubmit={create} className="space-y-4">
              <div>
                <Label>Webhook Name</Label>
                <Input name="url" placeholder="e.g. Shopify Orders, WooCommerce..." required />
              </div>
              <div className="flex justify-end">
                <Button type="submit" loading={saving}>
                  <Webhook className="h-4 w-4" /> Generate URL
                </Button>
              </div>
            </form>
            <p className="mt-4 text-xs text-muted-foreground">
              Generate a unique URL to provide to external services (like Shopify). You can view the JSON logs of any data they send here.
            </p>
          </CardBody>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Your Webhook URLs</CardTitle>
          </CardHeader>
          <CardBody>
            {loading ? (
              <div className="flex items-center gap-2 text-sm text-muted-foreground">
                <Loader className="h-4 w-4 animate-spin" /> Loading…
              </div>
            ) : endpoints.length === 0 ? (
              <p className="text-sm text-muted-foreground">No webhook URLs generated yet.</p>
            ) : (
              <div className="space-y-3">
                {endpoints.map((ep) => {
                  const baseUrl = typeof window !== "undefined" ? window.location.origin : "";
                  const url = `${baseUrl}/api/webhooks/in/${ep.id}`;
                  return (
                    <div key={ep.id} className="flex flex-col gap-3 rounded-lg border border-border px-4 py-3">
                      <div className="flex items-start justify-between min-w-0">
                        <div className="min-w-0 pr-4">
                          <p className="font-semibold text-foreground text-sm">{ep.url}</p>
                          <div className="mt-1 flex items-center gap-2">
                            <code className="text-xs bg-muted px-1.5 py-0.5 rounded break-all">{url}</code>
                            <Button variant="ghost" size="icon" className="h-6 w-6" onClick={() => { navigator.clipboard.writeText(url); toast.success("Copied!"); }}>
                              <Copy className="h-3 w-3" />
                            </Button>
                          </div>
                          <div className="mt-2 flex items-center gap-2">
                            <Badge tone={ep.active ? "green" : "gray"}>{ep.active ? "Active" : "Inactive"}</Badge>
                            <span className="text-xs text-muted-foreground">{ep._count?.logs || 0} requests</span>
                          </div>
                        </div>
                        <div className="flex shrink-0 items-center gap-1">
                          <Button variant="ghost" size="icon" onClick={() => loadLogs(ep.id)} className={selectedEndpointId === ep.id ? "bg-muted" : ""}>
                            <Activity className="h-4 w-4" />
                          </Button>
                          <Button variant="ghost" size="icon" className="text-muted-foreground hover:text-red-600" onClick={() => remove(ep.id)}>
                            <Trash2 className="h-4 w-4" />
                          </Button>
                        </div>
                      </div>
                    </div>
                  );
                })}
              </div>
            )}
          </CardBody>
        </Card>
      </div>

      <div className="space-y-4">
        {selectedEndpointId ? (
          <Card className="h-[600px] flex flex-col">
            <CardHeader>
              <CardTitle>JSON Logs</CardTitle>
            </CardHeader>
            <CardBody className="flex-1 overflow-auto">
              {loadingLogs ? (
                <div className="flex items-center gap-2 text-sm text-muted-foreground">
                  <Loader className="h-4 w-4 animate-spin" /> Loading logs…
                </div>
              ) : logs.length === 0 ? (
                <p className="text-sm text-muted-foreground">No logs found for this webhook yet.</p>
              ) : (
                <div className="space-y-4">
                  {logs.map((log) => (
                    <div key={log.id} className="rounded-lg border border-border bg-muted/30 p-3 text-sm">
                      <div className="mb-2 flex items-center justify-between">
                        <Badge tone={log.status >= 200 && log.status < 300 ? "green" : "red"}>
                          {log.status || "Received"}
                        </Badge>
                        <span className="text-xs text-muted-foreground">
                          {new Date(log.createdAt).toLocaleString()}
                        </span>
                      </div>
                      <div className="font-mono text-xs">
                        <div className="mb-2 rounded bg-card p-2 border border-border overflow-auto max-h-60">
                          <pre>{JSON.stringify(log.payload, null, 2)}</pre>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </CardBody>
          </Card>
        ) : (
          <Card className="h-full min-h-[400px] flex items-center justify-center border-dashed">
            <div className="text-center text-muted-foreground">
              <Activity className="mx-auto h-8 w-8 opacity-20 mb-2" />
              <p className="text-sm">Select a webhook to view its JSON logs</p>
            </div>
          </Card>
        )}
      </div>
    </div>
  );
}
