import { gitWebhookCreate, gitWebhookDelete, gitWebhookList, gitWebhookUpdate } from "@/client";
import type { WebhookEvent, WebhookResponse } from "@/client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
  Edit2,
  Loader2,
  Plus,
  Trash2,
  Webhook,
} from "lucide-react";
import { useState } from "react";
import { useParams } from "react-router-dom";
import { toast } from "sonner";
import {getApiErrorMessage} from '@/lib/api-error';

const WEBHOOK_EVENTS: Array<{ key: keyof WebhookEvent; label: string; desc: string }> = [
  { key: "push", label: "Push", desc: "Push to a repository branch or tag" },
  { key: "tag_push", label: "Tag", desc: "Create or delete a repository tag" },
  { key: "pull_request", label: "Pull Request", desc: "Open, close, or merge a pull request" },
  { key: "release", label: "Release", desc: "Publish or update a release" },
];

function WebhookForm({
  webhook,
  onSave,
  onCancel,
  isPending,
}: {
  webhook?: WebhookResponse;
  onSave: (data: { url: string; secret: string; events: WebhookEvent }) => void;
  onCancel: () => void;
  isPending: boolean;
}) {
  const [url, setUrl] = useState(webhook?.url ?? "");
  const [secret, setSecret] = useState(webhook?.secret ?? "");
  const [events, setEvents] = useState<WebhookEvent>(webhook?.events ?? {
    push: true,
    tag_push: false,
    pull_request: false,
    issue_comment: false,
    release: false,
  });

  const toggleEvent = (key: keyof WebhookEvent) => {
    setEvents((prev) => ({ ...prev, [key]: !prev[key] }));
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!url.trim()) return;
    onSave({ url: url.trim(), secret: secret.trim(), events });
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-4 border rounded-lg p-4 bg-card">
      <div className="space-y-2">
        <Label>Payload URL *</Label>
        <Input value={url} onChange={(e) => setUrl(e.target.value)} placeholder="https://example.com/webhook" required disabled={isPending} />
      </div>
      <div className="space-y-2">
        <Label>Secret</Label>
        <Input value={secret} onChange={(e) => setSecret(e.target.value)} placeholder="Optional secret for HMAC signature" disabled={isPending} />
        <p className="text-xs text-muted-foreground">Optional. If set, payloads will be signed with HMAC-SHA256.</p>
      </div>
      <div className="space-y-3">
        <Label>Events</Label>
        {WEBHOOK_EVENTS.map((e) => (
          <div key={e.key} className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium">{e.label}</p>
              <p className="text-xs text-muted-foreground">{e.desc}</p>
            </div>
            <Switch checked={!!events[e.key]} onCheckedChange={() => toggleEvent(e.key)} disabled={isPending} />
          </div>
        ))}
      </div>
      <div className="flex gap-2 pt-2">
        <Button type="submit" disabled={isPending || !url.trim()}>
          {isPending && <Loader2 className="h-3.5 w-3.5 mr-1.5 animate-spin" />}
          {webhook ? "Update Webhook" : "Add Webhook"}
        </Button>
        <Button type="button" variant="outline" onClick={onCancel} disabled={isPending}>Cancel</Button>
      </div>
    </form>
  );
}

function WebhookCard({ webhook, onEdit, onDelete, isDeleting }: { webhook: WebhookResponse; onEdit: () => void; onDelete: () => void; isDeleting: boolean }) {
  const activeEvents = WEBHOOK_EVENTS.filter((e) => webhook.events[e.key]);
  return (
    <div className="border rounded-lg px-4 py-3 bg-card hover:bg-muted/50 transition-colors">
      <div className="flex items-start justify-between gap-3">
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2">
            <Webhook className="h-4 w-4 text-muted-foreground flex-shrink-0" />
            <span className="text-sm font-mono truncate">{webhook.url}</span>
          </div>
          {activeEvents.length > 0 && (
            <div className="flex flex-wrap gap-1 mt-2">
              {activeEvents.map((e) => (
                <span key={e.key} className="text-xs px-1.5 py-0.5 rounded bg-blue-500/10 text-blue-600 border border-blue-500/20">{e.label}</span>
              ))}
            </div>
          )}
          <p className="text-xs text-muted-foreground mt-1.5">
            {webhook.touch_count} deliveries · created {new Date(webhook.created_at).toLocaleDateString()}
          </p>
        </div>
        <div className="flex gap-1 flex-shrink-0">
          <Button size="sm" variant="ghost" onClick={onEdit} disabled={isDeleting}><Edit2 className="h-3.5 w-3.5" /></Button>
          <Button size="sm" variant="ghost" className="text-destructive hover:text-destructive" onClick={onDelete} disabled={isDeleting}><Trash2 className="h-3.5 w-3.5" /></Button>
        </div>
      </div>
    </div>
  );
}

export function RepoSettingsWebhooks() {
  const queryClient = useQueryClient();
  const { namespace, repoName } = useParams<{ namespace: string; repoName: string }>();
  const ns = namespace!;
  const rn = repoName!;
  const [showForm, setShowForm] = useState(false);
  const [editingId, setEditingId] = useState<number | null>(null);
  const [deleteId, setDeleteId] = useState<number | null>(null);

  const { data, isLoading } = useQuery({
    queryKey: ["repo-webhooks", ns, rn],
    queryFn: async () => {
      const resp = await gitWebhookList({ path: { namespace: ns, repo: rn } });
      return resp.data?.data ?? null;
    },
    enabled: !!ns && !!rn,
    staleTime: 30 * 1000,
  });

  const webhooks: WebhookResponse[] = data?.webhooks ?? [];

  const createMutation = useMutation({
    mutationFn: async (params: { url: string; secret: string; events: WebhookEvent }) => {
      await gitWebhookCreate({
        path: { namespace: ns, repo: rn },
        body: { url: params.url, secret: params.secret || null, content_type: "json", events: params.events, active: true },
      });
    },
    onSuccess: () => { toast.success("Webhook created"); queryClient.invalidateQueries({ queryKey: ["repo-webhooks", ns, rn] }); resetForm(); },
    onError: (err: unknown) => { toast.error(getApiErrorMessage(err, "Failed to create webhook")); },
  });

  const updateMutation = useMutation({
    mutationFn: async (params: { url: string; secret: string; events: WebhookEvent }) => {
      if (!editingId) return;
      await gitWebhookUpdate({
        path: { namespace: ns, repo: rn, webhook_id: editingId },
        body: { url: params.url, secret: params.secret || null, events: params.events },
      });
    },
    onSuccess: () => { toast.success("Webhook updated"); queryClient.invalidateQueries({ queryKey: ["repo-webhooks", ns, rn] }); resetForm(); },
    onError: (err: unknown) => { toast.error(getApiErrorMessage(err, "Failed to update webhook")); },
  });

  const deleteMutation = useMutation({
    mutationFn: async (webhookId: number) => {
      await gitWebhookDelete({ path: { namespace: ns, repo: rn, webhook_id: webhookId } });
    },
    onSuccess: () => { toast.success("Webhook deleted"); queryClient.invalidateQueries({ queryKey: ["repo-webhooks", ns, rn] }); setDeleteId(null); },
    onError: (err: unknown) => { toast.error(getApiErrorMessage(err, "Failed to delete webhook")); },
  });

  const resetForm = () => { setShowForm(false); setEditingId(null); };
  const handleEdit = (wh: WebhookResponse) => { setEditingId(wh.id); setShowForm(true); };
  const pendingMutation = createMutation.isPending || updateMutation.isPending;
  const editingWebhook = editingId ? webhooks.find((w) => w.id === editingId) : undefined;

  return (
    <div className="space-y-4">
      <div className="border rounded-lg bg-card">
        <div className="p-4 border-b flex items-center justify-between">
          <div>
            <h2 className="text-sm font-semibold flex items-center gap-2"><Webhook className="h-4 w-4" />Webhooks</h2>
            <p className="text-xs text-muted-foreground mt-0.5">Configure webhooks to receive notifications about repository events.</p>
          </div>
          {!showForm && <Button size="sm" onClick={() => setShowForm(true)}><Plus className="h-3.5 w-3.5 mr-1" />Add webhook</Button>}
        </div>
        <div className="p-4 space-y-3">
          {showForm && <WebhookForm webhook={editingWebhook} onSave={(data) => { editingId ? updateMutation.mutate(data) : createMutation.mutate(data); }} onCancel={resetForm} isPending={pendingMutation} />}
          {isLoading ? (
            <div className="flex items-center justify-center h-32"><Loader2 className="h-5 w-5 animate-spin text-muted-foreground" /></div>
          ) : webhooks.length === 0 && !showForm ? (
            <div className="text-center py-8 text-muted-foreground"><Webhook className="h-8 w-8 mx-auto mb-2 opacity-40" /><p className="font-medium">No webhooks configured</p><p className="text-sm mt-1">Add a webhook to receive HTTP POST notifications.</p></div>
          ) : (
            webhooks.map((wh) => <WebhookCard key={wh.id} webhook={wh} onEdit={() => handleEdit(wh)} onDelete={() => setDeleteId(wh.id)} isDeleting={deleteMutation.isPending && deleteId === wh.id} />)
          )}
        </div>
      </div>
      {deleteId && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40">
          <div className="bg-background border rounded-lg shadow-lg p-6 max-w-sm w-full mx-4">
            <h3 className="text-base font-semibold mb-2">Delete webhook?</h3>
            <p className="text-sm text-muted-foreground mb-4">This will permanently delete the webhook and stop all future deliveries.</p>
            <div className="flex gap-2 justify-end">
              <Button variant="outline" size="sm" onClick={() => setDeleteId(null)}>Cancel</Button>
              <Button size="sm" variant="destructive" onClick={() => deleteMutation.mutate(deleteId)} disabled={deleteMutation.isPending}>
                {deleteMutation.isPending && <Loader2 className="h-3.5 w-3.5 mr-1.5 animate-spin" />}Delete
              </Button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
