'use client';

/**
 * DlqDepthPanel — admin view of dead-letter queue depth with acknowledge action.
 */

import { useState } from 'react';
import { useT, useLocale } from '@/lib/i18n/react';
import { RelativeTimeCell } from './RelativeTimeCell';
import { HydratedIsland } from '@/components/HydratedIsland';
import type { DehydratedState } from '@tanstack/react-query';
import type { Locale } from '@/lib/i18n';
import { PageHeader } from '@/components/ui/layout/PageHeader';
import { Button } from '@/components/ui/primitives/Button';
import { Badge } from '@/components/ui/primitives/Badge';
import { Spinner } from '@/components/ui/feedback/Spinner';
import { InlineNotice } from '@/components/ui/feedback/InlineNotice';
import { EmptyState } from '@/components/ui/feedback/EmptyState';
import { TableSkeleton } from '@/components/ui/feedback/Skeleton';
import { Row } from '@/components/ui/layout/Row';
import { Stack } from '@/components/ui/layout/Stack';
import {
  AlertDialog,
  AlertDialogContent,
  AlertDialogTitle,
  AlertDialogDescription,
  AlertDialogAction,
  AlertDialogCancel,
} from '@/components/ui/overlays/AlertDialog';
import { useToast } from '@/components/ui/overlays/Toast';
import { useDlq, useAcknowledgeDlq, type DlqQueueView } from './internals/useMonitorDlq';
import { QueryBoundary } from '@platform-modules/ui-primitives';

function depthBadgeTone(depth: number): 'neutral' | 'warning' | 'danger' {
  if (depth >= 50) return 'danger';
  if (depth > 0) return 'warning';
  return 'neutral';
}

function AcknowledgeButton({ queue }: { queue: DlqQueueView }) {
  const t = useT('adminMonitor');
  const tc = useT('common');
  const { toast } = useToast();
  const [confirmOpen, setConfirmOpen] = useState(false);
  const acknowledge = useAcknowledgeDlq(queue.queueKey);

  return (
    <>
      <Button
        variant="ghost"
        size="sm"
        disabled={acknowledge.isPending}
        onClick={() => setConfirmOpen(true)}
      >
        {acknowledge.isPending ? <Spinner variant="dots" size="sm" /> : t('dlqAcknowledge')}
      </Button>

      <AlertDialog open={confirmOpen} onOpenChange={setConfirmOpen}>
        <AlertDialogContent>
          <AlertDialogTitle>{t('dlqAcknowledge')}</AlertDialogTitle>
          <AlertDialogDescription>{t('dlqConfirmAck')}</AlertDialogDescription>
          <AlertDialogCancel>{tc('cancel')}</AlertDialogCancel>
          <AlertDialogAction
            onClick={() =>
              acknowledge.mutate(undefined, {
                onSuccess: () => {
                  setConfirmOpen(false);
                  toast({ title: t('dlqAcknowledged'), tone: 'success' });
                },
                onError: () => {
                  setConfirmOpen(false);
                  toast({ title: t('saveError'), tone: 'danger' });
                },
              })
            }
          >
            {t('dlqAcknowledge')}
          </AlertDialogAction>
        </AlertDialogContent>
      </AlertDialog>
    </>
  );
}

function DlqDepthPanelInner() {
  const t = useT('adminMonitor');
  const { locale } = useLocale();
  const dlqQuery = useDlq();

  return (
    <Stack gap="4">
      <PageHeader title={t('dlqTitle')} />

      <QueryBoundary
        query={dlqQuery}
        skeleton={<TableSkeleton rows={4} cols={5} />}
        errorFallback={() => <InlineNotice tone="danger" title={t('saveError')} />}
      >
        {(resolvedQueues) => {
          const resolvedHasDepth = resolvedQueues.some((queue) => queue.depth > 0);
          const resolvedShowEmpty = resolvedQueues.length === 0 || !resolvedHasDepth;

          return resolvedShowEmpty ? (
            <EmptyState title={t('dlqEmpty')} />
          ) : (
            <div className="border-border-default overflow-hidden rounded-lg border">
              <table className="w-full text-sm">
                <thead className="bg-surface-raised text-text-muted text-xs uppercase">
                  <tr>
                    <th className="px-4 py-2 text-start font-medium">{t('dlqQueue')}</th>
                    <th className="px-4 py-2 text-start font-medium">{t('dlqDepth')}</th>
                    <th className="px-4 py-2 text-start font-medium">{t('dlqLastDead')}</th>
                    <th className="px-4 py-2 text-start font-medium">{t('dlqLastReason')}</th>
                    <th className="px-4 py-2 text-end font-medium" />
                  </tr>
                </thead>
                <tbody className="divide-border-default divide-y">
                  {resolvedQueues.map((queue) => (
                    <tr key={queue.queueKey} className="bg-surface-default">
                      <td className="px-4 py-3 font-mono text-xs">{queue.queueKey}</td>
                      <td className="px-4 py-3">
                        <Badge tone={depthBadgeTone(queue.depth)} size="md">
                          {queue.depth}
                        </Badge>
                      </td>
                      <td className="text-text-muted px-4 py-3 text-xs">
                        <RelativeTimeCell date={queue.lastDeadAt} locale={locale} />
                      </td>
                      <td className="text-text-secondary max-w-xs truncate px-4 py-3">
                        {queue.lastReason ?? '—'}
                      </td>
                      <td className="px-4 py-3">
                        {queue.depth > 0 && (
                          <Row justify="end">
                            <AcknowledgeButton queue={queue} />
                          </Row>
                        )}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          );
        }}
      </QueryBoundary>
    </Stack>
  );
}

export function DlqDepthPanel({
  locale,
  dehydratedState,
}: {
  locale?: Locale;
  dehydratedState?: DehydratedState;
}) {
  return (
    <HydratedIsland locale={locale} dehydratedState={dehydratedState}>
      <DlqDepthPanelInner />
    </HydratedIsland>
  );
}
