import { Copy } from 'lucide-react';
import { toast } from 'sonner';

import { useState } from 'react';

import { Button } from '@/Components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/Components/ui/card';
import { Input } from '@/Components/ui/input';
import { Label } from '@/Components/ui/label';
import { LoadingButton } from '@/Components/ui/loading-button';
import { copied, couldnt } from '@/lib/messages';
import { getCsrfToken } from '@/lib/utils';

interface CreateEndpointDialogProps {
  availableEvents: string[];
  onClose: () => void;
  onCreated: () => void;
}

export function CreateEndpointDialog({
  availableEvents,
  onClose,
  onCreated,
}: CreateEndpointDialogProps) {
  const [url, setUrl] = useState('');
  const [events, setEvents] = useState<string[]>([]);
  const [description, setDescription] = useState('');
  const [creating, setCreating] = useState(false);
  const [errors, setErrors] = useState<Record<string, string[]>>({});
  const [createdSecret, setCreatedSecret] = useState<string | null>(null);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setCreating(true);
    setErrors({});

    const res = await fetch('/api/webhooks', {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
        'X-XSRF-TOKEN': getCsrfToken(),
      },
      body: JSON.stringify({ url, events, description: description || null }),
    });

    const data = await res.json();
    setCreating(false);

    if (!res.ok) {
      if (res.status === 422 && data.errors) {
        setErrors(data.errors);
      } else {
        toast.error(data.message || couldnt('create', 'endpoint'));
      }
      return;
    }

    setCreatedSecret(data.secret);
    toast.success('Webhook endpoint created.');
  };

  if (createdSecret) {
    return (
      <div className="fixed inset-0 z-50 flex items-center justify-center bg-background/80 backdrop-blur-sm">
        <Card className="w-full max-w-md mx-4 max-h-[90vh] overflow-y-auto">
          <CardHeader>
            <CardTitle>Endpoint Created</CardTitle>
            <CardDescription>Save this secret now. It will only be shown once.</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="flex items-center gap-2">
              <code className="flex-1 rounded-md bg-muted px-3 py-2 text-sm font-mono break-all">
                {createdSecret}
              </code>
              <Button
                variant="outline"
                size="icon"
                onClick={() => {
                  navigator.clipboard.writeText(createdSecret);
                  toast.success(copied('Secret'));
                }}
                aria-label="Copy webhook secret"
              >
                <Copy className="h-4 w-4" />
              </Button>
            </div>
            <Button className="w-full" onClick={onCreated}>
              Done
            </Button>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-background/80 backdrop-blur-sm">
      <Card className="w-full max-w-md mx-4 max-h-[90vh] overflow-y-auto">
        <CardHeader>
          <CardTitle>Add Webhook Endpoint</CardTitle>
          <CardDescription>
            We'll send HTTP POST requests to this URL when events occur.
          </CardDescription>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleSubmit} className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="webhook-url">Endpoint URL</Label>
              <Input
                id="webhook-url"
                type="url"
                placeholder="https://example.com/webhook"
                value={url}
                onChange={(e) => setUrl(e.target.value)}
                required
                aria-describedby={errors.url ? 'webhook-url-error' : undefined}
                aria-invalid={!!errors.url}
              />
              {errors.url && (
                <p id="webhook-url-error" className="text-xs text-destructive">
                  {errors.url[0]}
                </p>
              )}
            </div>

            <div className="space-y-2">
              <Label>Events</Label>
              <div className="space-y-2">
                {availableEvents.map((event) => (
                  <label key={event} className="flex items-center gap-2 text-sm">
                    <input
                      type="checkbox"
                      checked={events.includes(event)}
                      onChange={(e) =>
                        setEvents(
                          e.target.checked
                            ? [...events, event]
                            : events.filter((ev) => ev !== event),
                        )
                      }
                      className="rounded"
                    />
                    {event}
                  </label>
                ))}
              </div>
              {errors.events && (
                <p id="webhook-events-error" className="text-xs text-destructive" role="alert">
                  {errors.events[0]}
                </p>
              )}
            </div>

            <div className="space-y-2">
              <Label htmlFor="webhook-description">Description (optional)</Label>
              <Input
                id="webhook-description"
                placeholder="Production server"
                value={description}
                onChange={(e) => setDescription(e.target.value)}
              />
            </div>

            <div className="flex gap-2">
              <Button type="button" variant="outline" className="flex-1" onClick={onClose}>
                Cancel
              </Button>
              <LoadingButton
                type="submit"
                className="flex-1"
                loading={creating}
                loadingText="Creating..."
                disabled={events.length === 0}
              >
                Create endpoint
              </LoadingButton>
            </div>
          </form>
        </CardContent>
      </Card>
    </div>
  );
}
