import { useMemo, useState } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import DOMPurify from 'dompurify'
import { Ban, CheckCircle2, Download, Network, Trash2 } from 'lucide-react'
import { toast } from 'sonner'
import {
  formatSecurityResultLabel,
  formatStatusLabel,
} from '@/lib/admin-labels'
import { api, type ApiResponse } from '@/lib/api'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { EntityDetailSheet } from '@/components/admin/entity-detail-sheet'
import { ReasonDialog } from './reason-dialog'
import {
  FilterBar,
  formatBytes,
  formatDate,
  GovernanceShell,
  GovernanceTable,
  type PageData,
  Pagination,
  useUrlFilters,
} from './shared'

interface EmailItem {
  id: number
  mailbox_id: number
  user_id: string
  recipient: string
  mail_from: string
  sender_name?: string
  subject?: string
  source_ip: string
  spf_result?: string
  dkim_result?: string
  dmarc_result?: string
  abuse_score: number
  status: string
  size_bytes: number
  received_at: string
  expires_at: string
}

interface EmailDetail extends EmailItem {
  rcpt_to: string
  text_body?: string
  html_body?: string
  helo?: string
  ptr_result?: string
  message_id?: string
  attachments: Array<{
    id: number
    filename?: string
    content_type: string
    size_bytes: number
  }>
}

type EmailAction =
  | 'delete'
  | 'release'
  | 'block_sender'
  | 'block_domain'
  | 'block_ip'

const actionLabels: Record<EmailAction, string> = {
  delete: '物理删除',
  release: '放行',
  block_sender: '封禁发件地址',
  block_domain: '封禁发件域',
  block_ip: '封禁来源 IP',
}

function securityBadge(label: string, value?: string) {
  return (
    <Badge variant={value === 'pass' ? 'outline' : 'secondary'}>
      {label} {formatSecurityResultLabel(value)}
    </Badge>
  )
}

export function EmailsPage({ quarantined = false }: { quarantined?: boolean }) {
  const queryClient = useQueryClient()
  const { filters, update } = useUrlFilters({
    page: '1',
    page_size: '20',
    q: '',
    status: quarantined ? 'quarantined' : 'all',
  })
  const [selected, setSelected] = useState<Array<string | number>>([])
  const [selectedEmail, setSelectedEmail] = useState<EmailItem | null>(null)
  const [action, setAction] = useState<EmailAction | null>(null)
  const params = {
    ...filters,
    status:
      quarantined || filters.status === 'quarantined'
        ? 'quarantined'
        : filters.status === 'all'
          ? undefined
          : filters.status,
  }
  const query = useQuery({
    queryKey: ['admin', 'emails', params],
    queryFn: async () => {
      const response = await api.get<ApiResponse<PageData<EmailItem>>>(
        '/admin/emails',
        { params }
      )
      return response.data.data
    },
  })
  const detail = useQuery({
    queryKey: ['admin', 'email-detail', selectedEmail?.id],
    enabled: selectedEmail !== null,
    queryFn: async () => {
      const response = await api.get<ApiResponse<EmailDetail>>(
        `/admin/emails/${selectedEmail?.id}`
      )
      return response.data.data
    },
  })
  const mutate = useMutation({
    mutationFn: async (reason: string) => {
      await api.post('/admin/emails/bulk-actions', {
        ids:
          selected.length > 0
            ? selected.map(Number)
            : selectedEmail
              ? [selectedEmail.id]
              : [],
        action,
        reason,
      })
    },
    onSuccess: async () => {
      setAction(null)
      setSelected([])
      setSelectedEmail(null)
      await Promise.all([
        queryClient.invalidateQueries({ queryKey: ['admin', 'emails'] }),
        queryClient.invalidateQueries({ queryKey: ['admin', 'overview'] }),
      ])
      toast.success('邮件处置已完成')
    },
    onError: () => toast.error('邮件处置失败，请查看返回原因'),
  })
  const safeHtml = useMemo(
    () =>
      DOMPurify.sanitize(detail.data?.html_body ?? '', {
        FORBID_TAGS: [
          'script',
          'style',
          'form',
          'input',
          'button',
          'iframe',
          'object',
          'embed',
          'link',
          'meta',
        ],
        FORBID_ATTR: ['src', 'srcset', 'href', 'style'],
      }),
    [detail.data?.html_body]
  )
  const data = query.data
  const affected = selected.length || (selectedEmail ? 1 : 0)

  const downloadAttachment = async (
    emailId: number,
    attachmentId: number,
    filename: string
  ) => {
    const response = await api.get(
      `/admin/emails/${emailId}/attachments/${attachmentId}`,
      { responseType: 'blob' }
    )
    const url = URL.createObjectURL(response.data)
    const anchor = document.createElement('a')
    anchor.href = url
    anchor.download = filename
    anchor.click()
    URL.revokeObjectURL(url)
  }

  return (
    <GovernanceShell
      title={quarantined ? '隔离队列' : '全部邮件'}
      description={
        quarantined
          ? '审查风险邮件；放行成功后才原子扣分并占用当日收信次数。'
          : '检索全量邮件元数据，受控查看正文、附件并执行治理操作。'
      }
    >
      <FilterBar
        value={filters.q}
        placeholder='搜索发件人、收件人、主题或 Message-ID'
        onChange={(value) => update('q', value)}
        onRefresh={() => query.refetch()}
        refreshing={query.isFetching}
      >
        {!quarantined && (
          <Select
            value={filters.status}
            onValueChange={(value) => update('status', value)}
          >
            <SelectTrigger className='w-full md:w-36'>
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value='all'>全部状态</SelectItem>
              <SelectItem value='received'>正常接收</SelectItem>
              <SelectItem value='quarantined'>已隔离</SelectItem>
              <SelectItem value='rejected'>已拒绝</SelectItem>
            </SelectContent>
          </Select>
        )}
        {selected.length > 0 && (
          <div className='flex flex-wrap gap-2'>
            {quarantined && (
              <Button variant='outline' onClick={() => setAction('release')}>
                <CheckCircle2 />
                放行
              </Button>
            )}
            <Button variant='outline' onClick={() => setAction('block_sender')}>
              <Ban />
              封禁来源
            </Button>
            <Button variant='destructive' onClick={() => setAction('delete')}>
              <Trash2 />
              删除
            </Button>
          </div>
        )}
      </FilterBar>
      <GovernanceTable
        data={data?.items ?? []}
        selected={selected}
        onSelectedChange={setSelected}
        onRowClick={setSelectedEmail}
        loading={query.isPending}
        columns={[
          {
            key: 'subject',
            label: '主题与发件人',
            mobile: true,
            render: (item) => (
              <div className='max-w-80'>
                <div className='truncate font-medium'>
                  {item.subject || '（无主题）'}
                </div>
                <div className='truncate text-xs text-muted-foreground'>
                  {item.mail_from}
                </div>
              </div>
            ),
          },
          {
            key: 'recipient',
            label: '收件人',
            render: (item) => item.recipient,
          },
          {
            key: 'status',
            label: '状态',
            mobile: true,
            render: (item) => (
              <div className='flex items-center gap-2'>
                <Badge
                  variant={
                    item.status === 'quarantined' ? 'destructive' : 'outline'
                  }
                >
                  {formatStatusLabel(item.status)}
                </Badge>
                <span className='text-xs'>风险 {item.abuse_score}</span>
              </div>
            ),
          },
          {
            key: 'security',
            label: '安全结果',
            render: (item) => (
              <div className='flex flex-wrap gap-1'>
                {securityBadge('S', item.spf_result)}
                {securityBadge('D', item.dkim_result)}
                {securityBadge('M', item.dmarc_result)}
              </div>
            ),
          },
          {
            key: 'source',
            label: '来源 IP',
            render: (item) => item.source_ip,
          },
          {
            key: 'size',
            label: '大小',
            render: (item) => formatBytes(item.size_bytes),
          },
          {
            key: 'received',
            label: '接收时间',
            render: (item) => formatDate(item.received_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))}
      />

      <EntityDetailSheet
        open={selectedEmail !== null}
        onOpenChange={(open) => !open && setSelectedEmail(null)}
        title={detail.data?.subject || selectedEmail?.subject || '（无主题）'}
        description={`${detail.data?.mail_from ?? selectedEmail?.mail_from ?? ''} → ${detail.data?.recipient ?? selectedEmail?.recipient ?? ''}`}
        status={{
          label: formatStatusLabel(
            detail.data?.status ?? selectedEmail?.status
          ),
          tone:
            (detail.data?.status ?? selectedEmail?.status) === 'quarantined'
              ? 'danger'
              : 'success',
        }}
        meta={`查看正文会记录审计 · ${formatDate(detail.data?.received_at)}`}
        isLoading={detail.isPending}
        sections={[
          {
            title: '投递与安全',
            fields: [
              { label: '来源 IP', value: detail.data?.source_ip },
              { label: 'HELO', value: detail.data?.helo },
              {
                label: 'SPF',
                value: formatSecurityResultLabel(detail.data?.spf_result),
              },
              {
                label: 'DKIM',
                value: formatSecurityResultLabel(detail.data?.dkim_result),
              },
              {
                label: 'DMARC',
                value: formatSecurityResultLabel(detail.data?.dmarc_result),
              },
              { label: '风险分', value: detail.data?.abuse_score },
            ],
          },
          {
            title: '纯文本正文',
            content: (
              <pre className='max-h-80 overflow-auto text-sm leading-6 whitespace-pre-wrap'>
                {detail.data?.text_body || '无纯文本正文'}
              </pre>
            ),
          },
          {
            title: 'HTML 正文',
            description: '脚本、表单、远程资源和可点击链接已移除。',
            content: safeHtml ? (
              <iframe
                title='已清洗邮件正文'
                sandbox=''
                srcDoc={safeHtml}
                className='h-80 w-full bg-white'
              />
            ) : (
              <p className='text-sm text-muted-foreground'>无 HTML 正文</p>
            ),
          },
          {
            title: '附件',
            description: '附件仅允许下载，下载行为会写入审计日志。',
            content: (
              <div className='divide-y'>
                {detail.data?.attachments.map((attachment) => (
                  <div
                    key={attachment.id}
                    className='flex items-center justify-between gap-3 py-2'
                  >
                    <div className='min-w-0'>
                      <div className='truncate text-sm font-medium'>
                        {attachment.filename || `attachment-${attachment.id}`}
                      </div>
                      <div className='text-xs text-muted-foreground'>
                        {attachment.content_type} ·{' '}
                        {formatBytes(attachment.size_bytes)}
                      </div>
                    </div>
                    <Button
                      size='icon'
                      variant='outline'
                      title='下载附件'
                      onClick={() =>
                        downloadAttachment(
                          detail.data!.id,
                          attachment.id,
                          attachment.filename || `attachment-${attachment.id}`
                        )
                      }
                    >
                      <Download />
                    </Button>
                  </div>
                ))}
                {detail.data?.attachments.length === 0 && (
                  <p className='py-2 text-sm text-muted-foreground'>无附件</p>
                )}
              </div>
            ),
          },
        ]}
        actions={[
          ...(selectedEmail?.status === 'quarantined'
            ? [
                {
                  label: '放行',
                  icon: CheckCircle2,
                  onClick: () => setAction('release'),
                },
              ]
            : []),
          {
            label: '封禁发件人',
            icon: Ban,
            onClick: () => setAction('block_sender'),
          },
          {
            label: '封禁 IP',
            icon: Network,
            onClick: () => setAction('block_ip'),
          },
          {
            label: '删除',
            icon: Trash2,
            variant: 'destructive',
            onClick: () => setAction('delete'),
          },
        ]}
      />
      <ReasonDialog
        open={action !== null}
        title={action ? actionLabels[action] : '邮件处置'}
        description={`将对 ${affected} 封邮件执行“${action ? actionLabels[action] : ''}”。批量操作逐项执行并保留部分成功结果。`}
        confirmLabel='确认执行'
        pending={mutate.isPending}
        onOpenChange={(open) => !open && setAction(null)}
        onConfirm={(reason) => mutate.mutate(reason)}
      />
    </GovernanceShell>
  )
}
