"use client";

import { useState } from "react";
import { Field, Input } from "@/components/ui/kit";

export interface Endpoint {
  id: number;
  url: string;
  description: string | null;
  events: string[];
  is_active: boolean;
  disabled_reason: string | null;
  consecutive_failures: number;
  last_success_at: string | null;
  last_failure_at: string | null;
  secret_rotating_until: string | null;
  created_at: string;
  stats?: { failed_24h: number; succeeded_24h: number; pending: number };
}
export type EventType = { type: string; description: string };

export function EndpointForm({ id, initial, types, errors, busy, onSubmit }: { id: string; initial?: Endpoint; types: EventType[]; errors: Record<string, string>; busy: boolean; onSubmit: (body: Record<string, unknown>) => void }) {
  const subscribable = types.filter((t) => t.type !== "test.ping");
  const [all, setAll] = useState(initial ? initial.events.includes("*") : true);
  const [chosen, setChosen] = useState<string[]>(initial && !initial.events.includes("*") ? initial.events : ["message.received", "message.status"]);
  return (
    <form
      id={id}
      noValidate
      className="space-y-4"
      onSubmit={(e) => {
        e.preventDefault();
        const f = new FormData(e.currentTarget);
        onSubmit({ url: String(f.get("url") ?? "").trim(), description: String(f.get("description") ?? "").trim() || null, events: all ? ["*"] : chosen });
      }}
    >
      <Field label="Endpoint URL" htmlFor={`${id}-url`} error={errors.url} hint="An https:// URL on your server that answers 2xx within 10 seconds.">
        <Input id={`${id}-url`} name="url" type="url" placeholder="https://example.com/devwebs/webhooks" defaultValue={initial?.url} invalid={!!errors.url} disabled={busy} />
      </Field>
      <Field label="Description (optional)" htmlFor={`${id}-desc`}>
        <Input id={`${id}-desc`} name="description" defaultValue={initial?.description ?? ""} disabled={busy} />
      </Field>
      <fieldset>
        <legend className="mb-1.5 text-sm font-medium">Events</legend>
        {errors.events && <p className="mb-1 text-[13px] text-brick">{errors.events}</p>}
        <label className="mb-1 flex items-center gap-2.5 text-sm">
          <input type="checkbox" className="size-4 accent-teal" checked={all} onChange={(e) => setAll(e.target.checked)} />
          All events, including ones added later
        </label>
        {!all && (
          <div className="mt-2 max-h-64 space-y-1 overflow-y-auto rounded-lg border border-line p-2">
            {subscribable.map((t) => (
              <label key={t.type} className="flex items-start gap-2.5 rounded-md px-2 py-1.5 text-sm hover:bg-paper">
                <input type="checkbox" className="mt-0.5 size-4 accent-teal" checked={chosen.includes(t.type)} onChange={(e) => setChosen((c) => (e.target.checked ? [...c, t.type] : c.filter((x) => x !== t.type)))} />
                <span>
                  <code className="font-mono text-[13px]">{t.type}</code>
                  <span className="block text-[13px] text-muted">{t.description}</span>
                </span>
              </label>
            ))}
          </div>
        )}
      </fieldset>
    </form>
  );
}
