'use client';

import { ChevronRight, RotateCcw, X } from 'lucide-react';
import { useState } from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { toast } from 'sonner';

import { AllClearIllustration } from '@/components/illustrations';
import { PageHeader } from '@/components/layout/page-header';
import { Button } from '@/components/ui/button';
import { Card } from '@/components/ui/card';
import { JsonBlock } from '@/components/ui/json-block';
import { Drawer } from '@/components/ui/overlay';
import { Segmented } from '@/components/ui/segmented';
import { EmptyState, ErrorState } from '@/components/ui/states';
import { Skeleton } from '@/components/ui/skeleton';
import { ApiError, api, apiEnvelope } from '@/lib/api-client';
import { formatRelative } from '@/lib/shipments';
import { cn } from '@/lib/utils';

interface WebhookRow {
  id: string;
  provider: string;
  type: string | null;
  status: string;
  error: string | null;
  payload: unknown;
  createdAt: string;
}

type StatusFilter = '' | 'RECEIVED' | 'PROCESSED' | 'FAILED';

const statusLook = (status: string) =>
  status === 'PROCESSED'
    ? { label: 'Processed', className: 'bg-success-soft text-success', dot: 'bg-success' }
    : status === 'FAILED'
      ? { label: 'Failed', className: 'bg-danger-soft text-danger', dot: 'bg-danger' }
      : status === 'RECEIVED'
        ? { label: 'Received', className: 'bg-info-soft text-info', dot: 'bg-info' }
        : { label: status.charAt(0) + status.slice(1).toLowerCase(), className: 'bg-surface-muted text-muted-foreground', dot: 'bg-subtle-foreground' };

function StatusBadge({ status }: { status: string }) {
  const look = statusLook(status);
  return (
    <span className={cn('inline-flex items-center gap-1.5 whitespace-nowrap rounded-pill px-2.5 py-0.5 text-caption font-semibold', look.className)}>
      <span className={cn('h-1.5 w-1.5 rounded-full', look.dot)} aria-hidden="true" />
      {look.label}
    </span>
  );
}

export default function AdminWebhooksPage() {
  const queryClient = useQueryClient();
  const [status, setStatus] = useState<StatusFilter>('');
  const [selected, setSelected] = useState<WebhookRow | null>(null);
  const [retrying, setRetrying] = useState<string | null>(null);
  const query = `?page=1&pageSize=50${status ? `&status=${status}` : ''}`;
  const list = useQuery({
    queryKey: ['admin', 'webhooks', query],
    queryFn: () => apiEnvelope<{ data: WebhookRow[] }>(`/admin/webhook-events${query}`),
  });
  const rows = list.data?.data ?? [];

  const retry = (row: WebhookRow) => {
    setRetrying(row.id);
    void api(`/admin/webhook-events/${row.id}/retry`, { method: 'POST' })
      .then(async () => {
        toast.success('Retry queued.');
        setSelected(null);
        await queryClient.invalidateQueries({ queryKey: ['admin', 'webhooks'] });
      })
      .catch((error: unknown) => toast.error(error instanceof ApiError ? error.message : 'Retry failed.'))
      .finally(() => setRetrying(null));
  };

  return (
    <div className="grid gap-5">
      <PageHeader
        title="Webhooks"
        description="Inbound webhook events and retries."
        actions={
          <Segmented<StatusFilter>
            label="Webhook status"
            value={status}
            onChange={setStatus}
            options={[
              { value: '', label: 'All' },
              { value: 'RECEIVED', label: 'Received' },
              { value: 'PROCESSED', label: 'Processed' },
              { value: 'FAILED', label: 'Failed' },
            ]}
            className="h-10 items-center"
          />
        }
      />
      {list.isLoading ? <Skeleton className="h-64 rounded-xl" /> : null}
      {list.error instanceof ApiError ? (
        <Card>
          <ErrorState message={list.error.message} requestId={list.error.requestId} onRetry={() => void list.refetch()} />
        </Card>
      ) : null}
      {list.data !== undefined && rows.length === 0 ? (
        <Card>
          <EmptyState
            illustration={<AllClearIllustration size={110} />}
            title={status === 'FAILED' ? 'No failed events' : 'No webhook events'}
            description={status === 'FAILED' ? 'Every inbound webhook processed cleanly.' : 'Events from Easyship and payment providers will appear here.'}
          />
        </Card>
      ) : null}
      {rows.length > 0 ? (
        <Card className="overflow-hidden p-0">
          <div className="overflow-x-auto">
            <table className="w-full min-w-[760px] text-left text-small">
              <thead>
                <tr className="h-11 border-b border-border bg-surface-muted/80 text-caption font-semibold uppercase tracking-[0.08em] text-muted-foreground">
                  <th scope="col" className="pl-5 pr-3 font-semibold">Received</th>
                  <th scope="col" className="px-3 font-semibold">Provider</th>
                  <th scope="col" className="px-3 font-semibold">Type</th>
                  <th scope="col" className="px-3 font-semibold">Status</th>
                  <th scope="col" className="px-3 font-semibold">Error</th>
                  <th scope="col" className="w-12 pr-4">
                    <span className="sr-only">Open</span>
                  </th>
                </tr>
              </thead>
              <tbody>
                {rows.map((row) => (
                  <tr
                    key={row.id}
                    tabIndex={0}
                    aria-label={`Open ${row.type ?? 'webhook'} event`}
                    className={cn(
                      'group h-14 cursor-pointer border-b border-border transition-colors last:border-b-0 hover:bg-surface-muted/60 focus-visible:bg-surface-muted/60 focus-visible:outline-none',
                      row.status === 'FAILED' && 'shadow-[inset_3px_0_0_rgb(var(--danger))]',
                    )}
                    onClick={() => setSelected(row)}
                    onKeyDown={(event) => {
                      if (event.key === 'Enter' || event.key === ' ') {
                        event.preventDefault();
                        setSelected(row);
                      }
                    }}
                  >
                    <td className="whitespace-nowrap pl-5 pr-3 text-muted-foreground" title={new Date(row.createdAt).toLocaleString()}>
                      {formatRelative(row.createdAt)}
                    </td>
                    <td className="px-3 font-semibold capitalize">{row.provider.toLowerCase()}</td>
                    <td className="px-3 font-mono text-caption">{row.type ?? <span className="font-sans text-subtle-foreground">—</span>}</td>
                    <td className="px-3">
                      <StatusBadge status={row.status} />
                    </td>
                    <td className="max-w-[280px] px-3">
                      {row.error === null ? <span className="text-subtle-foreground">—</span> : <span className="block truncate text-danger" title={row.error}>{row.error}</span>}
                    </td>
                    <td className="pr-4">
                      <ChevronRight className="h-4 w-4 text-subtle-foreground transition-transform group-hover:translate-x-0.5" aria-hidden="true" />
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </Card>
      ) : null}

      <Drawer open={selected !== null} title="Webhook event" side="right" onClose={() => setSelected(null)} className="flex flex-col p-0">
        {selected === null ? null : (
          <>
            <div className="flex items-start justify-between gap-3 border-b border-border px-6 py-4">
              <div className="min-w-0">
                <h2 className="truncate font-mono text-small font-semibold">{selected.type ?? 'Webhook event'}</h2>
                <p className="mt-1 flex flex-wrap items-center gap-2 text-caption text-muted-foreground">
                  <StatusBadge status={selected.status} />
                  <span className="capitalize">{selected.provider.toLowerCase()}</span>·<span>{new Date(selected.createdAt).toLocaleString()}</span>
                </p>
              </div>
              <button type="button" aria-label="Close" onClick={() => setSelected(null)} className="grid h-9 w-9 shrink-0 place-items-center rounded-md text-muted-foreground hover:bg-surface-muted hover:text-foreground">
                <X className="h-4 w-4" aria-hidden="true" />
              </button>
            </div>
            <div className="grid flex-1 content-start gap-4 overflow-y-auto px-6 py-5">
              {selected.error === null ? null : (
                <div className="rounded-lg border border-danger/30 bg-danger-soft px-4 py-3 text-small text-danger">
                  <p className="font-semibold">Processing error</p>
                  <p className="mt-1 break-words">{selected.error}</p>
                </div>
              )}
              <div className="grid gap-2">
                <h3 className="text-caption font-semibold uppercase tracking-[0.08em] text-muted-foreground">Payload</h3>
                <JsonBlock value={selected.payload} label="Copy payload" />
              </div>
            </div>
            {selected.status === 'FAILED' ? (
              <div className="flex justify-end gap-2 border-t border-border px-6 py-4">
                <Button type="button" loading={retrying === selected.id} onClick={() => retry(selected)}>
                  {retrying === selected.id ? null : <RotateCcw className="h-4 w-4" aria-hidden="true" />}
                  Retry event
                </Button>
              </div>
            ) : null}
          </>
        )}
      </Drawer>
    </div>
  );
}
