import { useQuery } from '@tanstack/react-query'
import {
  formatAdminText,
  formatAuditActionLabel,
  formatAuditEventLabel,
  formatCreditReasonLabel,
  formatEmailKindLabel,
  formatStatusLabel,
  formatTargetTypeLabel,
} from '@/lib/admin-labels'
import { api, type ApiResponse } from '@/lib/api'
import { Badge } from '@/components/ui/badge'
import {
  FilterBar,
  formatDate,
  GovernanceShell,
  GovernanceTable,
  type PageData,
  Pagination,
  useUrlFilters,
} from './shared'

interface AuditItem {
  id: number
  event_type: string
  source_ip?: string
  helo?: string
  mail_from?: string
  rcpt_to?: string
  action: string
  reason?: string
  operator_id?: string
  target_type?: string
  target_id?: string
  created_at: string
}

interface CreditItem {
  id: number
  user_id: string
  user_email?: string
  delta: number
  balance_after: number
  reason: string
  description?: string
  operator_id?: string
  created_at: string
}

interface OutboundItem {
  id: number
  user_id?: string
  recipient: string
  kind: string
  status: string
  error?: string
  created_at: string
}

function AuditLogs({ scope }: { scope: 'admin' | 'smtp' }) {
  const { filters, update } = useUrlFilters({
    page: '1',
    page_size: '20',
    q: '',
  })
  const query = useQuery({
    queryKey: ['admin', 'audit-logs', scope, filters],
    queryFn: async () => {
      const response = await api.get<ApiResponse<PageData<AuditItem>>>(
        '/admin/audit-logs',
        { params: { ...filters, scope } }
      )
      return response.data.data
    },
  })
  const data = query.data
  return (
    <GovernanceShell
      title={scope === 'smtp' ? 'SMTP 审计' : '管理员操作'}
      description={
        scope === 'smtp'
          ? '只读检索连接、接收、拒绝、延迟与隔离事件。'
          : '永久保留管理员查看、下载与治理动作。'
      }
    >
      <FilterBar
        value={filters.q}
        placeholder={
          scope === 'smtp'
            ? '搜索发件人、收件人、原因或目标'
            : '搜索原因或目标 ID'
        }
        onChange={(value) => update('q', value)}
        onRefresh={() => query.refetch()}
        refreshing={query.isFetching}
      />
      <GovernanceTable
        data={data?.items ?? []}
        loading={query.isPending}
        columns={[
          {
            key: 'event',
            label: '事件',
            mobile: true,
            render: (item) => (
              <div>
                <div className='font-medium'>
                  {formatAuditEventLabel(item.event_type)}
                </div>
                <Badge variant='outline'>
                  {formatAuditActionLabel(item.action)}
                </Badge>
              </div>
            ),
          },
          {
            key: scope === 'smtp' ? 'route' : 'operator',
            label: scope === 'smtp' ? '投递路径' : '管理员',
            mobile: true,
            render: (item) =>
              scope === 'smtp' ? (
                <div className='max-w-80'>
                  <div className='truncate'>{item.mail_from || '-'}</div>
                  <div className='truncate text-xs text-muted-foreground'>
                    → {item.rcpt_to || '-'}
                  </div>
                </div>
              ) : (
                item.operator_id || '-'
              ),
          },
          {
            key: 'source',
            label: scope === 'smtp' ? '来源 IP / HELO' : '操作目标',
            render: (item) =>
              scope === 'smtp'
                ? `${item.source_ip || '-'} / ${item.helo || '-'}`
                : `${formatTargetTypeLabel(item.target_type)} / ${item.target_id || '-'}`,
          },
          {
            key: 'reason',
            label: '原因',
            render: (item) => (
              <div className='max-w-96 whitespace-normal'>
                {formatAdminText(item.reason)}
              </div>
            ),
          },
          {
            key: 'created',
            label: '时间',
            render: (item) => formatDate(item.created_at),
          },
        ]}
      />
      <Pagination
        page={data?.page ?? Number(filters.page)}
        pageSize={data?.page_size ?? 20}
        total={data?.total ?? 0}
        totalPages={data?.total_pages ?? 0}
        onPage={(page) => update('page', String(page))}
      />
    </GovernanceShell>
  )
}

export function SmtpAuditPage() {
  return <AuditLogs scope='smtp' />
}

export function AdminAuditPage() {
  return <AuditLogs scope='admin' />
}

export function CreditTransactionsPage() {
  const { filters, update } = useUrlFilters({
    page: '1',
    page_size: '20',
    user_id: '',
  })
  const query = useQuery({
    queryKey: ['admin', 'credit-transactions', filters],
    queryFn: async () => {
      const response = await api.get<ApiResponse<PageData<CreditItem>>>(
        '/admin/credit-transactions',
        { params: filters }
      )
      return response.data.data
    },
  })
  const data = query.data
  return (
    <GovernanceShell
      title='积分流水'
      description='按用户、原因与管理员追踪每次赠送、消费和人工调整。'
    >
      <FilterBar
        value={filters.user_id}
        placeholder='按用户 ID 精确筛选'
        onChange={(value) => update('user_id', value)}
        onRefresh={() => query.refetch()}
        refreshing={query.isFetching}
      />
      <GovernanceTable
        data={data?.items ?? []}
        loading={query.isPending}
        columns={[
          {
            key: 'user',
            label: '用户',
            mobile: true,
            render: (item) => (
              <div>
                <div className='font-medium'>
                  {item.user_email || item.user_id}
                </div>
                <div className='text-xs text-muted-foreground'>
                  {item.user_id}
                </div>
              </div>
            ),
          },
          {
            key: 'delta',
            label: '变化',
            mobile: true,
            render: (item) => (
              <span
                className={
                  item.delta >= 0 ? 'text-emerald-600' : 'text-red-600'
                }
              >
                {item.delta > 0 ? '+' : ''}
                {item.delta}
              </span>
            ),
          },
          {
            key: 'balance',
            label: '变更后余额',
            render: (item) => item.balance_after,
          },
          {
            key: 'reason',
            label: '原因',
            render: (item) => (
              <div>
                <div>{formatCreditReasonLabel(item.reason)}</div>
                <div className='text-xs text-muted-foreground'>
                  {formatAdminText(item.description)}
                </div>
              </div>
            ),
          },
          {
            key: 'operator',
            label: '操作管理员',
            render: (item) => item.operator_id || '-',
          },
          {
            key: 'created',
            label: '时间',
            render: (item) => formatDate(item.created_at),
          },
        ]}
      />
      <Pagination
        page={data?.page ?? Number(filters.page)}
        pageSize={data?.page_size ?? 20}
        total={data?.total ?? 0}
        totalPages={data?.total_pages ?? 0}
        onPage={(page) => update('page', String(page))}
      />
    </GovernanceShell>
  )
}

export function EmailLogsPage() {
  const { filters, update } = useUrlFilters({
    page: '1',
    page_size: '20',
    q: '',
  })
  const query = useQuery({
    queryKey: ['admin', 'email-logs', filters],
    queryFn: async () => {
      const response = await api.get<ApiResponse<PageData<OutboundItem>>>(
        '/admin/email-logs',
        { params: filters }
      )
      return response.data.data
    },
  })
  const data = query.data
  return (
    <GovernanceShell
      title='外发邮件日志'
      description='查看验证码与系统邮件的发送状态、收件人与失败原因。'
    >
      <FilterBar
        value={filters.q}
        placeholder='搜索收件人或错误信息'
        onChange={(value) => update('q', value)}
        onRefresh={() => query.refetch()}
        refreshing={query.isFetching}
      />
      <GovernanceTable
        data={data?.items ?? []}
        loading={query.isPending}
        columns={[
          {
            key: 'recipient',
            label: '收件人',
            mobile: true,
            render: (item) => (
              <span className='font-medium'>{item.recipient}</span>
            ),
          },
          {
            key: 'kind',
            label: '类型',
            render: (item) => formatEmailKindLabel(item.kind),
          },
          {
            key: 'status',
            label: '状态',
            mobile: true,
            render: (item) => (
              <Badge
                variant={item.status === 'sent' ? 'outline' : 'destructive'}
              >
                {formatStatusLabel(item.status)}
              </Badge>
            ),
          },
          {
            key: 'error',
            label: '错误',
            render: (item) => (
              <div className='max-w-96 whitespace-normal'>
                {formatAdminText(item.error)}
              </div>
            ),
          },
          {
            key: 'created',
            label: '时间',
            render: (item) => formatDate(item.created_at),
          },
        ]}
      />
      <Pagination
        page={data?.page ?? Number(filters.page)}
        pageSize={data?.page_size ?? 20}
        total={data?.total ?? 0}
        totalPages={data?.total_pages ?? 0}
        onPage={(page) => update('page', String(page))}
      />
    </GovernanceShell>
  )
}
