import { useMutation, useQueryClient } from '@tanstack/react-query';
import { Plus, Trash2, Webhook } from 'lucide-react';
import { useState } from 'react';
import { useParams } from 'react-router-dom';
import type { EventType } from '@/client/models/EventType';
import { ReposService } from '@/client/services/ReposService';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Spinner } from '@/components/ui/spinner';
import { useRepoWebhooks } from '@/hooks/repo/useRepoWebhooks';
import { cn } from '@/lib/utils';

export function RepoWebhooksPage() {
  const { workspaceName = '', repoName = '' } = useParams();
  const qc = useQueryClient();
  const { data: webhooks, isLoading } = useRepoWebhooks(workspaceName, repoName);

  const [showCreate, setShowCreate] = useState(false);
  const [newUrl, setNewUrl] = useState('');
  const [newEvents, setNewEvents] = useState('');

  const createWebhook = useMutation({
    mutationFn: () => {
      const events = newEvents
        .split(',')
        .map((e) => e.trim())
        .filter(Boolean) as EventType[];
      return ReposService.repoCreateWebhook({
        workspaceName,
        repoName,
        requestBody: { url: newUrl, events: events.length > 0 ? events : ['Pushed'] },
      });
    },
    onSuccess: () => {
      setNewUrl('');
      setNewEvents('');
      setShowCreate(false);
      qc.invalidateQueries({ queryKey: ['repo', workspaceName, repoName, 'webhooks'] });
    },
  });

  const deleteWebhook = useMutation({
    mutationFn: (webhookId: string) =>
      ReposService.repoDeleteWebhook({ workspaceName, repoName, webhookId }),
    onSuccess: () =>
      qc.invalidateQueries({ queryKey: ['repo', workspaceName, repoName, 'webhooks'] }),
  });

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <p className="text-[12px] text-muted-foreground">
          {(webhooks ?? []).length} webhook{(webhooks ?? []).length !== 1 ? 's' : ''}
        </p>
        <Button size="sm" onClick={() => setShowCreate(!showCreate)}>
          <Plus className="size-3.5" />
          New webhook
        </Button>
      </div>

      {showCreate && (
        <div className="space-y-2 rounded-lg border border-border p-3">
          <Input
            className="h-8 text-[13px]"
            placeholder="Payload URL (https://...)"
            value={newUrl}
            onChange={(e) => setNewUrl(e.target.value)}
          />
          <Input
            className="h-8 text-[13px]"
            placeholder="Events (comma-separated, e.g. Pushed, Merged, Commented)"
            value={newEvents}
            onChange={(e) => setNewEvents(e.target.value)}
          />
          <div className="flex gap-2">
            <Button
              size="sm"
              disabled={!newUrl.trim() || createWebhook.isPending}
              onClick={() => createWebhook.mutate()}
            >
              {createWebhook.isPending ? 'Creating...' : 'Create webhook'}
            </Button>
            <Button size="sm" variant="outline" onClick={() => setShowCreate(false)}>
              Cancel
            </Button>
          </div>
        </div>
      )}

      <div className="overflow-hidden rounded-lg border border-border">
        {isLoading ? (
          <div className="flex items-center gap-2 p-6 text-[13px] text-muted-foreground">
            <Spinner />
          </div>
        ) : (webhooks ?? []).length > 0 ? (
          <div>
            {(webhooks ?? []).map((hook) => (
              <div
                key={hook.id}
                className="flex items-center gap-3 border-b border-border px-4 py-2.5 last:border-b-0 transition-colors hover:bg-muted/40"
              >
                <Webhook className="size-4 text-muted-foreground shrink-0" />
                <div className="min-w-0 flex-1">
                  <span className="block truncate text-[13px] font-medium text-foreground">
                    {hook.url}
                  </span>
                  <div className="mt-0.5 flex items-center gap-2 text-[11px] text-muted-foreground">
                    <span
                      className={cn(hook.active ? 'text-green-500' : 'text-muted-foreground/50')}
                    >
                      {hook.active ? 'Active' : 'Inactive'}
                    </span>
                    {hook.last_delivery_status && (
                      <span
                        className={cn(
                          hook.last_delivery_status === 'Success'
                            ? 'text-green-500'
                            : 'text-red-500',
                        )}
                      >
                        Last: {hook.last_delivery_status}
                      </span>
                    )}
                    <span className="flex flex-wrap gap-1">
                      {hook.events.slice(0, 3).map((evt) => (
                        <span key={evt} className="rounded bg-muted px-1 py-0.5 text-[10px]">
                          {evt}
                        </span>
                      ))}
                      {hook.events.length > 3 && (
                        <span className="text-[10px] text-muted-foreground/50">
                          +{hook.events.length - 3}
                        </span>
                      )}
                    </span>
                  </div>
                </div>
                <Button
                  size="icon-sm"
                  variant="ghost"
                  className="text-muted-foreground hover:text-destructive"
                  onClick={() => {
                    if (confirm(`Delete webhook?`)) deleteWebhook.mutate(hook.id);
                  }}
                >
                  <Trash2 className="size-3.5" />
                </Button>
              </div>
            ))}
          </div>
        ) : (
          <div className="flex flex-col items-center justify-center py-16 text-center">
            <Webhook className="size-6 text-muted-foreground/30" />
            <p className="mt-3 text-[13px] text-muted-foreground">No webhooks configured</p>
            <Button size="sm" className="mt-3" onClick={() => setShowCreate(true)}>
              <Plus className="size-3.5" />
              Add webhook
            </Button>
          </div>
        )}
      </div>
    </div>
  );
}
