'use client';

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

import { useState, useEffect, useCallback } from 'react';
import { Webhook, Plus, MoreHorizontal, RotateCcw, 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 WebhookSub {
  id: string;
  url: string;
  events: string[];
  status: string;
  failureCount: number;
  createdAt: string;
}

interface Delivery {
  id: string;
  subscriptionId: string;
  event: string;
  status: string;
  statusCode?: number;
  attempt: number;
  createdAt: string;
}

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

const apiFetch = createProxyFetch('/api/webhooks');

export default function WebhooksPage() {
  const [subs, setSubs] = useState<WebhookSub[]>([]);
  const [deliveries, setDeliveries] = useState<Delivery[]>([]);
  const [loading, setLoading] = useState(true);
  const [tab, setTab] = useState<'subscriptions' | 'deliveries'>('subscriptions');
  const [showCreate, setShowCreate] = useState(false);
  const [creating, setCreating] = useState(false);
  const [newUrl, setNewUrl] = useState('');
  const [newEvents, setNewEvents] = useState('');

  const loadData = useCallback(async () => {
    setLoading(true);
    const sData = await apiFetch('subscriptions');
    const subsList: WebhookSub[] = Array.isArray(sData?.subscriptions)
      ? sData.subscriptions
      : Array.isArray(sData)
        ? sData
        : [];
    setSubs(subsList);

    // Load deliveries per-subscription in parallel (backend only has per-sub endpoint)
    const results = await Promise.allSettled(
      subsList.slice(0, 10).map(sub =>
        apiFetch(`subscriptions/${sub.id}/deliveries`).then((dData: Record<string, unknown>) => {
          const items: Delivery[] = Array.isArray(dData?.deliveries)
            ? (dData.deliveries as Delivery[])
            : Array.isArray(dData)
              ? (dData as unknown as Delivery[])
              : [];
          return items;
        })
      )
    );
    const allDeliveries = results
      .filter((r): r is PromiseFulfilledResult<Delivery[]> => r.status === 'fulfilled')
      .flatMap(r => r.value);
    setDeliveries(allDeliveries.sort((a, b) => b.createdAt.localeCompare(a.createdAt)));
    setLoading(false);
  }, []);

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

  async function handleCreate() {
    setCreating(true);
    await apiFetch('subscriptions', {
      method: 'POST',
      body: JSON.stringify({
        url: newUrl,
        events: newEvents
          .split(',')
          .map(e => e.trim())
          .filter(Boolean),
      }),
    });
    setCreating(false);
    setShowCreate(false);
    setNewUrl('');
    setNewEvents('');
    loadData();
  }

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

  async function handleTest(id: string) {
    await apiFetch(`subscriptions/${id}/test`, { method: 'POST' });
    loadData();
  }

  const activeCount = subs.filter(s => s.status === 'active').length;

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold">Webhooks</h1>
          <p className="text-sm text-muted-foreground">
            Manage webhook subscriptions and view delivery logs
          </p>
        </div>
        <Button onClick={() => setShowCreate(true)}>
          <Plus className="mr-2 h-4 w-4" /> Add Webhook
        </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 Subscriptions
            </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">{activeCount}</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">
              Recent Deliveries
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{deliveries.length}</div>
          </CardContent>
        </Card>
      </div>

      <div className="flex gap-2">
        <Button
          variant={tab === 'subscriptions' ? 'default' : 'outline'}
          size="sm"
          onClick={() => setTab('subscriptions')}
        >
          Subscriptions
        </Button>
        <Button
          variant={tab === 'deliveries' ? 'default' : 'outline'}
          size="sm"
          onClick={() => setTab('deliveries')}
        >
          Delivery Log
        </Button>
      </div>

      {tab === 'subscriptions' && (
        <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">
                <Webhook className="mx-auto mb-2 h-8 w-8 opacity-40" />
                No webhook subscriptions.
              </div>
            ) : (
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>URL</TableHead>
                    <TableHead>Events</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 className="font-mono text-xs max-w-[300px] truncate">
                        {s.url}
                      </TableCell>
                      <TableCell>
                        <div className="flex flex-wrap gap-1">
                          {s.events.map(e => (
                            <Badge key={e} variant="outline" className="text-xs">
                              {e}
                            </Badge>
                          ))}
                        </div>
                      </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={() => handleTest(s.id)}>
                              <RotateCcw className="mr-2 h-4 w-4" />
                              Test
                            </DropdownMenuItem>
                            <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>
      )}

      {tab === 'deliveries' && (
        <Card>
          <CardContent className="p-0">
            {deliveries.length === 0 ? (
              <div className="p-8 text-center text-muted-foreground">No deliveries yet.</div>
            ) : (
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Event</TableHead>
                    <TableHead>Status</TableHead>
                    <TableHead>HTTP</TableHead>
                    <TableHead>Attempt</TableHead>
                    <TableHead>Date</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {deliveries.map(d => (
                    <TableRow key={d.id}>
                      <TableCell>
                        <Badge variant="outline" className="text-xs">
                          {d.event}
                        </Badge>
                      </TableCell>
                      <TableCell>
                        <Badge
                          className={
                            d.status === 'delivered'
                              ? 'bg-emerald-50 text-emerald-700 border-0'
                              : 'bg-red-50 text-red-700 border-0'
                          }
                        >
                          {d.status}
                        </Badge>
                      </TableCell>
                      <TableCell className="font-mono text-xs">{d.statusCode || '—'}</TableCell>
                      <TableCell>{d.attempt}</TableCell>
                      <TableCell className="text-xs text-muted-foreground">
                        {formatDate(d.createdAt)}
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            )}
          </CardContent>
        </Card>
      )}

      <Dialog open={showCreate} onOpenChange={setShowCreate}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Add Webhook Subscription</DialogTitle>
            <DialogDescription>Subscribe to platform events via HTTP callback.</DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div className="space-y-2">
              <Label>Endpoint URL</Label>
              <Input
                placeholder="https://example.com/webhook"
                value={newUrl}
                onChange={e => setNewUrl(e.target.value)}
              />
            </div>
            <div className="space-y-2">
              <Label>Events (comma-separated)</Label>
              <Input
                placeholder="user.created, subscription.changed"
                value={newEvents}
                onChange={e => setNewEvents(e.target.value)}
              />
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowCreate(false)}>
              Cancel
            </Button>
            <Button onClick={handleCreate} disabled={creating || !newUrl.trim()}>
              {creating ? 'Creating...' : 'Create'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
