import { useState } from 'react'
import { createFileRoute } from '@tanstack/react-router'
import { useTranslation } from 'react-i18next'
import {
  Alert,
  Badge,
  Button,
  EmptyState,
  LoadingBlock,
  PageHeader,
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeaderCell,
  TableRow,
} from '@/ui'
import { ArrowsClockwiseIcon } from '@phosphor-icons/react'
import { useDlq, useOutboxStats } from '@/api/queries'

export const Route = createFileRoute('/outbox')({
  component: OutboxPage,
})

function OutboxPage() {
  const { t } = useTranslation()
  const [page, setPage] = useState(0)
  const size = 50

  const stats = useOutboxStats()
  const dlq = useDlq(page, size)

  return (
    <div className="space-y-6">
      <PageHeader
        title={t('outbox.title')}
        description={t('outbox.subtitle')}
        actions={
          <Button
            type="button"
            variant="secondary"
            leftIcon={<ArrowsClockwiseIcon size={16} />}
            onClick={() => {
              stats.refetch()
              dlq.refetch()
            }}
          >
            {t('audit.filter.apply')}
          </Button>
        }
      />

      <div className="grid grid-cols-2 gap-4">
        <StatCard
          label={t('outbox.stats.pending')}
          value={stats.data?.pending ?? '—'}
          tone="info"
        />
        <StatCard
          label={t('outbox.stats.dlq')}
          value={stats.data?.dlq ?? '—'}
          tone={(stats.data?.dlq ?? 0) > 0 ? 'error' : 'success'}
        />
      </div>

      {dlq.error ? (
        <Alert variant="error" title={t('error.failed')}>
          {String(dlq.error)}
        </Alert>
      ) : dlq.isLoading ? (
        <LoadingBlock size="md" label={t('loading')} />
      ) : !dlq.data || dlq.data.content.length === 0 ? (
        <EmptyState title={t('outbox.dlq.empty')} />
      ) : (
        <>
          <Table>
            <TableHead>
              <TableRow>
                <TableHeaderCell>{t('outbox.dlq.col.id')}</TableHeaderCell>
                <TableHeaderCell>{t('outbox.dlq.col.eventType')}</TableHeaderCell>
                <TableHeaderCell>{t('outbox.dlq.col.dictionary')}</TableHeaderCell>
                <TableHeaderCell>{t('outbox.dlq.col.aggregateId')}</TableHeaderCell>
                <TableHeaderCell>{t('outbox.dlq.col.topic')}</TableHeaderCell>
                <TableHeaderCell>{t('outbox.dlq.col.attempts')}</TableHeaderCell>
                <TableHeaderCell>{t('outbox.dlq.col.lastError')}</TableHeaderCell>
                <TableHeaderCell>{t('outbox.dlq.col.dlqAt')}</TableHeaderCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {dlq.data.content.map((row) => (
                <TableRow key={row.id}>
                  <TableCell>
                    <span className="text-mono">{row.id}</span>
                  </TableCell>
                  <TableCell>
                    <Badge variant="warning">{row.eventType}</Badge>
                  </TableCell>
                  <TableCell>{row.dictionaryName ?? '—'}</TableCell>
                  <TableCell>
                    <span className="text-mono">{row.aggregateId}</span>
                  </TableCell>
                  <TableCell>
                    <span className="text-mono">{row.kafkaTopic}</span>
                  </TableCell>
                  <TableCell>{row.attemptCount}</TableCell>
                  <TableCell>
                    <span
                      className="text-cell text-ink-2 truncate max-w-md inline-block align-middle"
                      title={row.lastError ?? ''}
                    >
                      {row.lastError ?? '—'}
                    </span>
                  </TableCell>
                  <TableCell>
                    <span className="text-cell tabular-nums">
                      {new Date(row.dlqAt).toLocaleString()}
                    </span>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
          <div className="flex items-center justify-end gap-3 text-body">
            <Button
              type="button"
              variant="secondary"
              onClick={() => setPage((p) => Math.max(0, p - 1))}
              disabled={page <= 0}
            >
              {t('audit.page.prev')}
            </Button>
            <span className="tabular-nums">
              {t('audit.page.of', {
                cur: (dlq.data.number ?? 0) + 1,
                total: Math.max(dlq.data.totalPages ?? 1, 1),
              })}
            </span>
            <Button
              type="button"
              variant="secondary"
              onClick={() => setPage((p) => p + 1)}
              disabled={(dlq.data.number ?? 0) + 1 >= (dlq.data.totalPages ?? 1)}
            >
              {t('audit.page.next')}
            </Button>
          </div>
        </>
      )}
    </div>
  )
}

type StatCardProps = {
  label: string
  value: number | string
  tone: 'info' | 'success' | 'error'
}

function StatCard({ label, value, tone }: StatCardProps) {
  const colour =
    tone === 'error'
      ? 'text-mars'
      : tone === 'success'
        ? 'text-grass'
        : 'text-accent'
  return (
    <div className="bg-white border border-line rounded-lg p-4">
      <div className="text-cap text-ink-2 mb-1">
        {label}
      </div>
      <div className={`text-2xl font-sans tabular-nums ${colour}`}>{value}</div>
    </div>
  )
}
