import { useState } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { Ban } from 'lucide-react'
import { toast } from 'sonner'
import { 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 { ReasonDialog } from './reason-dialog'
import {
  FilterBar,
  formatBytes,
  formatDate,
  GovernanceShell,
  GovernanceTable,
  type PageData,
  Pagination,
  useUrlFilters,
} from './shared'

interface MailboxItem {
  id: number
  address: string
  user_id: string
  user_email: string
  note?: string
  status: string
  max_quota_bytes: number
  used_bytes: number
  email_count: number
  expires_at: string
  created_at: string
}

export function MailboxesPage() {
  const queryClient = useQueryClient()
  const { filters, update } = useUrlFilters({
    page: '1',
    page_size: '20',
    q: '',
    status: 'all',
  })
  const [selected, setSelected] = useState<Array<string | number>>([])
  const [confirmOpen, setConfirmOpen] = useState(false)
  const params = {
    ...filters,
    status: filters.status === 'all' ? undefined : filters.status,
  }
  const query = useQuery({
    queryKey: ['admin', 'mailboxes', params],
    queryFn: async () => {
      const response = await api.get<ApiResponse<PageData<MailboxItem>>>(
        '/admin/mailboxes',
        { params }
      )
      return response.data.data
    },
  })
  const revoke = useMutation({
    mutationFn: async (reason: string) => {
      await api.post('/admin/mailboxes/bulk-actions', {
        ids: selected.map(Number),
        action: 'revoke',
        reason,
      })
    },
    onSuccess: async () => {
      setConfirmOpen(false)
      setSelected([])
      await queryClient.invalidateQueries({ queryKey: ['admin', 'mailboxes'] })
      toast.success('邮箱处置已完成')
    },
    onError: () => toast.error('邮箱处置失败'),
  })
  const data = query.data

  return (
    <GovernanceShell
      title='邮箱管理'
      description='检查邮箱归属、容量、状态与生命周期，支持批量吊销。'
    >
      <FilterBar
        value={filters.q}
        placeholder='搜索地址、用户或备注'
        onChange={(value) => update('q', value)}
        onRefresh={() => query.refetch()}
        refreshing={query.isFetching}
      >
        <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='active'>有效</SelectItem>
            <SelectItem value='expired'>已过期</SelectItem>
            <SelectItem value='revoked'>已吊销</SelectItem>
          </SelectContent>
        </Select>
        {selected.length > 0 && (
          <Button variant='destructive' onClick={() => setConfirmOpen(true)}>
            <Ban />
            吊销 {selected.length} 项
          </Button>
        )}
      </FilterBar>
      <GovernanceTable
        data={data?.items ?? []}
        selected={selected}
        onSelectedChange={setSelected}
        loading={query.isPending}
        columns={[
          {
            key: 'address',
            label: '邮箱',
            mobile: true,
            render: (item) => (
              <div className='max-w-72'>
                <div className='truncate font-medium'>{item.address}</div>
                <div className='truncate text-xs text-muted-foreground md:hidden'>
                  {item.user_email}
                </div>
              </div>
            ),
          },
          {
            key: 'owner',
            label: '所有者',
            render: (item) => (
              <div>
                <div>{item.user_email}</div>
                <div className='text-xs text-muted-foreground'>
                  {item.user_id}
                </div>
              </div>
            ),
          },
          {
            key: 'status',
            label: '状态',
            mobile: true,
            render: (item) => (
              <Badge
                variant={item.status === 'active' ? 'outline' : 'secondary'}
              >
                {formatStatusLabel(item.status)}
              </Badge>
            ),
          },
          {
            key: 'storage',
            label: '容量',
            render: (item) => (
              <div>
                {formatBytes(item.used_bytes)} /{' '}
                {formatBytes(item.max_quota_bytes)}
                <div className='text-xs text-muted-foreground'>
                  {item.email_count} 封邮件
                </div>
              </div>
            ),
          },
          {
            key: 'expires',
            label: '到期时间',
            render: (item) => formatDate(item.expires_at),
          },
          {
            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))}
      />
      <ReasonDialog
        open={confirmOpen}
        title='吊销所选邮箱'
        description={`将吊销 ${selected.length} 个邮箱。该操作不退还积分或每日次数。`}
        confirmLabel='确认吊销'
        pending={revoke.isPending}
        onOpenChange={setConfirmOpen}
        onConfirm={(reason) => revoke.mutate(reason)}
      />
    </GovernanceShell>
  )
}
