'use client';
import { formatErrorBanner } from '@/lib/api/toast-error';

import { useState } from 'react';
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 { Sheet, SheetContent, SheetHeader, SheetTitle, SheetFooter } from '@/components/ui/sheet';
import { apiFetch } from '@/lib/api/client';
import { WebhookEventSelector } from './webhook-event-selector';
import { WebhookSecretDisplay } from './webhook-secret-display';
import type { WebhookEvent } from '@/lib/services/webhook-event-map';

interface WebhookFormProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  webhook?: {
    id: string;
    name: string;
    url: string;
    events: string[];
    isActive: boolean;
    secretMasked: string;
  } | null;
  onSuccess: () => void;
}

export function WebhookForm({ open, onOpenChange, webhook, onSuccess }: WebhookFormProps) {
  const isEdit = !!webhook;

  const [name, setName] = useState(webhook?.name ?? '');
  const [url, setUrl] = useState(webhook?.url ?? '');
  const [events, setEvents] = useState<WebhookEvent[]>((webhook?.events ?? []) as WebhookEvent[]);
  const [isActive, setIsActive] = useState(webhook?.isActive ?? true);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [createdSecret, setCreatedSecret] = useState<string | null>(null);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError(null);
    setLoading(true);

    try {
      if (isEdit) {
        await apiFetch(`/api/v1/admin/webhooks/${webhook.id}`, {
          method: 'PATCH',
          body: { name, url, events, isActive },
        });
        onSuccess();
        onOpenChange(false);
      } else {
        const result = await apiFetch<{ data: { secret: string } }>('/api/v1/admin/webhooks', {
          method: 'POST',
          body: { name, url, events, isActive },
        });
        setCreatedSecret(result.data.secret);
        onSuccess();
      }
    } catch (err: unknown) {
      const message = formatErrorBanner(err);
      setError(message);
    } finally {
      setLoading(false);
    }
  }

  function handleClose() {
    setName(webhook?.name ?? '');
    setUrl(webhook?.url ?? '');
    setEvents((webhook?.events ?? []) as WebhookEvent[]);
    setIsActive(webhook?.isActive ?? true);
    setError(null);
    setCreatedSecret(null);
    onOpenChange(false);
  }

  return (
    <Sheet
      open={open}
      onOpenChange={(o) => {
        if (!o) handleClose();
      }}
    >
      <SheetContent className="w-full sm:max-w-xl overflow-y-auto">
        <SheetHeader>
          <SheetTitle>{isEdit ? 'Edit Webhook' : 'New Webhook'}</SheetTitle>
        </SheetHeader>

        {createdSecret ? (
          <div className="mt-6 space-y-4">
            <p className="text-sm">Webhook created successfully.</p>
            <WebhookSecretDisplay plaintext={createdSecret} masked="" />
            <Button onClick={handleClose} className="w-full">
              Done
            </Button>
          </div>
        ) : (
          <form onSubmit={handleSubmit} className="mt-6 space-y-6">
            <div className="space-y-2">
              <Label htmlFor="webhook-name">Name</Label>
              <Input
                id="webhook-name"
                value={name}
                onChange={(e) => setName(e.target.value)}
                placeholder="e.g. Zapier Integration"
                maxLength={200}
                required
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="webhook-url">URL</Label>
              <Input
                id="webhook-url"
                value={url}
                onChange={(e) => setUrl(e.target.value)}
                placeholder="https://hooks.example.com/webhook"
                type="url"
                required
              />
            </div>

            <div className="space-y-2">
              <Label>Events</Label>
              <WebhookEventSelector selected={events} onChange={setEvents} />
            </div>

            <div className="flex items-center gap-3">
              <Switch id="webhook-active" checked={isActive} onCheckedChange={setIsActive} />
              <Label htmlFor="webhook-active">Active</Label>
            </div>

            {error && <p className="whitespace-pre-line text-sm text-destructive">{error}</p>}

            <SheetFooter>
              <Button type="button" variant="outline" onClick={handleClose} disabled={loading}>
                Cancel
              </Button>
              <Button
                type="submit"
                disabled={loading || !name.trim() || !url.trim() || events.length === 0}
              >
                {loading ? 'Saving…' : isEdit ? 'Save changes' : 'Create Webhook'}
              </Button>
            </SheetFooter>
          </form>
        )}
      </SheetContent>
    </Sheet>
  );
}
