'use client';

import { createProxyFetch } from '@/lib/proxy-fetch';

import { useState, useEffect, useCallback } from 'react';
import { Radio, Plus, MoreHorizontal, Trash2 } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';

interface EventSub {
  id: string;
  eventType: string;
  callbackUrl: string;
  status: string;
  failureCount: number;
  createdAt: string;
}

function formatDate(iso: string) {
  return new Date(iso).toLocaleDateString('en-US', {
    month: 'short',
    day: 'numeric',
    year: 'numeric',
  });
}

const apiFetch = createProxyFetch('/api/event-subscriptions');

export default function EventSubscriptionsPage() {
  const [subs, setSubs] = useState<EventSub[]>([]);
  const [loading, setLoading] = useState(true);
  const [showCreate, setShowCreate] = useState(false);
  const [creating, setCreating] = useState(false);
  const [newEvent, setNewEvent] = useState('');
  const [newUrl, setNewUrl] = useState('');

  const loadData = useCallback(async () => {
    setLoading(true);
    const data = await apiFetch('');
    setSubs(
      Array.isArray(data?.subscriptions) ? data.subscriptions : Array.isArray(data) ? data : []
    );
    setLoading(false);
  }, []);

  useEffect(() => {
    void loadData();
  }, [loadData]);

  async function handleCreate() {
    setCreating(true);
    await apiFetch('', {
      method: 'POST',
      body: JSON.stringify({ eventType: newEvent, callbackUrl: newUrl }),
    });
    setCreating(false);
    setShowCreate(false);
    setNewEvent('');
    setNewUrl('');
    loadData();
  }

  async function handleDelete(id: string) {
    if (!confirm('Delete this subscription?')) return;
    await apiFetch(`${id}`, { method: 'DELETE' });
    loadData();
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold">Event Subscriptions</h1>
          <p className="text-sm text-muted-foreground">
            Manage DLQ replay and event subscription routing
          </p>
        </div>
        <Button onClick={() => setShowCreate(true)}>
          <Plus className="mr-2 h-4 w-4" /> Add Subscription
        </Button>
      </div>

      <div className="grid gap-4 md:grid-cols-3">
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">Total</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{subs.length}</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">Active</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-emerald-600">
              {subs.filter(s => s.status === 'active').length}
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">Failed</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-red-600">
              {subs.filter(s => s.status === 'disabled').length}
            </div>
          </CardContent>
        </Card>
      </div>

      <Card>
        <CardContent className="p-0">
          {loading ? (
            <div className="p-8 text-center text-muted-foreground">Loading...</div>
          ) : subs.length === 0 ? (
            <div className="p-8 text-center text-muted-foreground">
              <Radio className="mx-auto mb-2 h-8 w-8 opacity-40" />
              No event subscriptions.
            </div>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Event Type</TableHead>
                  <TableHead>Callback URL</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead>Failures</TableHead>
                  <TableHead>Created</TableHead>
                  <TableHead className="w-[50px]" />
                </TableRow>
              </TableHeader>
              <TableBody>
                {subs.map(s => (
                  <TableRow key={s.id}>
                    <TableCell>
                      <Badge variant="outline" className="font-mono text-xs">
                        {s.eventType}
                      </Badge>
                    </TableCell>
                    <TableCell className="font-mono text-xs max-w-[250px] truncate">
                      {s.callbackUrl}
                    </TableCell>
                    <TableCell>
                      <Badge
                        className={
                          s.status === 'active'
                            ? 'bg-emerald-50 text-emerald-700 border-0'
                            : 'bg-red-50 text-red-700 border-0'
                        }
                      >
                        {s.status}
                      </Badge>
                    </TableCell>
                    <TableCell>{s.failureCount}</TableCell>
                    <TableCell className="text-xs text-muted-foreground">
                      {formatDate(s.createdAt)}
                    </TableCell>
                    <TableCell>
                      <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                          <Button variant="ghost" size="icon" className="h-8 w-8">
                            <MoreHorizontal className="h-4 w-4" />
                          </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="end">
                          <DropdownMenuItem
                            onClick={() => handleDelete(s.id)}
                            className="text-destructive"
                          >
                            <Trash2 className="mr-2 h-4 w-4" />
                            Delete
                          </DropdownMenuItem>
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>

      <Dialog open={showCreate} onOpenChange={setShowCreate}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Add Event Subscription</DialogTitle>
            <DialogDescription>Subscribe to domain events with a callback URL.</DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div className="space-y-2">
              <Label>Event Type</Label>
              <Input
                placeholder="e.g. user.created"
                value={newEvent}
                onChange={e => setNewEvent(e.target.value)}
              />
            </div>
            <div className="space-y-2">
              <Label>Callback URL</Label>
              <Input
                placeholder="https://example.com/callback"
                value={newUrl}
                onChange={e => setNewUrl(e.target.value)}
              />
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowCreate(false)}>
              Cancel
            </Button>
            <Button
              onClick={handleCreate}
              disabled={creating || !newEvent.trim() || !newUrl.trim()}
            >
              {creating ? 'Creating...' : 'Create'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
