/**
 * 设备管理页
 *
 * 功能：
 * - 全局设备列表、筛选（用户、状态、信任状态）、分页
 * - 设备详情、信任/取消信任、删除
 */

import { useState, useEffect, useCallback } from 'react'
import {
  Table,
  Button,
  Space,
  Tag,
  Input,
  Select,
  Popconfirm,
  message,
  type TableColumnsType,
  type TablePaginationConfig,
} from 'antd'
import {
  SearchOutlined,
  ReloadOutlined,
  DeleteOutlined,
} from '@ant-design/icons'
import dayjs from 'dayjs'
import { PageHeader } from '@/components/common'
import { PageEmpty, PageError } from '@/components/feedback'
import { PageLayout, FilterCard, TableCard } from '@/components/layout'
import { getErrorMessage } from '@/lib/errors'
import {
  listAllDevices,
  adminDeleteDevice,
  adminTrustDevice,
  adminUntrustDevice,
} from '@/services/devices'
import type { Device, AdminDeviceListParams, DeviceStatus, DeviceType } from '@/types/device'
import { DeviceTypeText, DeviceStatusText, DeviceStatusColor, DeviceTrustText, DeviceTrustColor } from '@/types/device'
import type { CursorPaginatedData } from '@/types/http'

export function DevicesPage() {
  // 列表数据
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [devices, setDevices] = useState<Device[]>([])
  const [total, setTotal] = useState(0)
  // Cursor-based pagination state (preferred for large datasets)
  const [cursor, setCursor] = useState('')
  const [hasMore, setHasMore] = useState(true)
  // Legacy page state (for Ant Design Table compatibility)
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(20)

  // 筛选条件
  const [keyword, setKeyword] = useState('')
  const [userIdFilter, setUserIdFilter] = useState<number | undefined>()
  const [statusFilter, setStatusFilter] = useState<DeviceStatus | undefined>()
  const [trustFilter, setTrustFilter] = useState<boolean | undefined>()

  // 加载设备列表（使用游标分页）
  const fetchDevices = useCallback(async () => {
    setLoading(true)
    setError(null)
    try {
      const params: AdminDeviceListParams = {
        cursor: cursor || undefined,
        size: pageSize,
        keyword: keyword || undefined,
        user_id: userIdFilter,
        status: statusFilter,
        is_trusted: trustFilter,
      }
      const result = await listAllDevices(params) as unknown as CursorPaginatedData<Device>
      setDevices(result.items ?? [])
      // If the response has cursor fields, use them; otherwise fall back to legacy total
      if ('next_cursor' in result) {
        setCursor(result.next_cursor ?? '')
        setHasMore(result.has_more ?? false)
        // Estimate total from current data + whether there's more
        setTotal((page - 1) * pageSize + result.items?.length + (result.has_more ? 1 : 0))
      } else {
        // Legacy response format fallback
        setTotal((result as { total?: number }).total ?? 0)
      }
    } catch (err) {
      setError(getErrorMessage(err, '获取设备列表失败'))
    } finally {
      setLoading(false)
    }
  }, [cursor, page, pageSize, keyword, userIdFilter, statusFilter, trustFilter])

  useEffect(() => {
    void fetchDevices()
  }, [fetchDevices])

  // 筛选条件变化时重置到第一页（清空游标）
  useEffect(() => {
    setPage(1)
    setCursor('')
  }, [keyword, userIdFilter, statusFilter, trustFilter])

  // 重置筛选
  const handleReset = () => {
    setKeyword('')
    setUserIdFilter(undefined)
    setStatusFilter(undefined)
    setTrustFilter(undefined)
    setPage(1)
    setCursor('')
  }

  // 删除设备
  const handleDelete = async (device: Device) => {
    try {
      await adminDeleteDevice(device.id)
      message.success(`设备 ${device.device_name} 已删除`)
      void fetchDevices()
    } catch (err) {
      message.error(getErrorMessage(err, '删除失败'))
    }
  }

  // 信任设备
  const handleTrust = async (device: Device) => {
    try {
      await adminTrustDevice(device.id, '30d')
      message.success(`设备 ${device.device_name} 已设为信任`)
      void fetchDevices()
    } catch (err) {
      message.error(getErrorMessage(err, '操作失败'))
    }
  }

  // 取消信任
  const handleUntrust = async (device: Device) => {
    try {
      await adminUntrustDevice(device.id)
      message.success(`设备 ${device.device_name} 已取消信任`)
      void fetchDevices()
    } catch (err) {
      message.error(getErrorMessage(err, '操作失败'))
    }
  }

  // 表格列定义
  const columns: TableColumnsType<Device> = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '用户ID',
      dataIndex: 'user_id',
      key: 'user_id',
      width: 80,
    },
    {
      title: '设备名称',
      dataIndex: 'device_name',
      key: 'device_name',
      width: 120,
      render: (text) => text || '-',
    },
    {
      title: '设备类型',
      dataIndex: 'device_type',
      key: 'device_type',
      width: 80,
      render: (type: DeviceType) => DeviceTypeText[type] || '未知',
    },
    {
      title: '操作系统',
      dataIndex: 'device_os',
      key: 'device_os',
      width: 80,
      render: (text) => text || '-',
    },
    {
      title: '浏览器',
      dataIndex: 'device_browser',
      key: 'device_browser',
      width: 80,
      render: (text) => text || '-',
    },
    {
      title: 'IP地址',
      dataIndex: 'ip',
      key: 'ip',
      width: 120,
    },
    {
      title: '位置',
      dataIndex: 'location',
      key: 'location',
      width: 120,
      render: (text) => text || '-',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 80,
      render: (status: DeviceStatus) => (
        <Tag color={DeviceStatusColor[status]}>{DeviceStatusText[status]}</Tag>
      ),
    },
    {
      title: '信任状态',
      dataIndex: 'is_trusted',
      key: 'is_trusted',
      width: 80,
      render: (isTrusted: boolean) => (
        <Tag color={DeviceTrustColor[String(isTrusted)]}>{DeviceTrustText[String(isTrusted)]}</Tag>
      ),
    },
    {
      title: '最后活跃',
      dataIndex: 'last_active_time',
      key: 'last_active_time',
      width: 160,
      render: (text) => text ? dayjs(text).format('YYYY-MM-DD HH:mm') : '-',
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 160,
      render: (text) => dayjs(text).format('YYYY-MM-DD HH:mm'),
    },
    {
      title: '操作',
      key: 'action',
      width: 180,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          {record.is_trusted ? (
            <Button type="link" size="small" onClick={() => void handleUntrust(record)}>
              取消信任
            </Button>
          ) : (
            <Button type="link" size="small" onClick={() => void handleTrust(record)}>
              信任
            </Button>
          )}
          <Popconfirm
            title={`确定要删除设备「${record.device_name}」吗？此操作不可恢复。`}
            onConfirm={() => void handleDelete(record)}
          >
            <Button
              type="link"
              size="small"
              danger
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ]

  // 分页配置（兼容 Ant Design Table + 游标分页）
  const paginationConfig: TablePaginationConfig = {
    current: page,
    pageSize,
    total: hasMore ? total + 1 : total, // Show "more" indicator if hasMore
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (t) => `共 ${t > 0 && hasMore ? t - 1 : t} 条`,
    onChange: (p, ps) => {
      // When going forward, cursor is managed by fetchDevices
      // When changing page size or going backward, reset to offset mode
      if (ps !== pageSize) {
        setPageSize(ps)
        setPage(1)
        setCursor('')
      } else if (p === page + 1 && cursor) {
        // Next page via cursor
        setPage(p)
      } else {
        // Jump to specific page - fall back
        setPage(p)
        setCursor('')
      }
    },
  }

  if (error) {
    return <PageError description={error} onRetry={() => void fetchDevices()} />
  }

  return (
    <PageLayout>
      <PageHeader
        title="设备管理"
        description="管理系统所有设备，支持查看、信任状态管理和删除"
        actions={
          <Space>
            <Button icon={<ReloadOutlined />} onClick={() => void fetchDevices()}>
              刷新
            </Button>
          </Space>
        }
      />

      {/* 筛选区域 */}
      <FilterCard>
        <Space wrap size="middle">
          <Input
            placeholder="设备名/IP/位置"
            prefix={<SearchOutlined />}
            value={keyword}
            onChange={(e) => setKeyword(e.target.value)}
            onPressEnter={() => void fetchDevices()}
            style={{ width: 200 }}
            allowClear
          />
          <Input
            placeholder="用户ID"
            type="number"
            value={userIdFilter}
            onChange={(e) => setUserIdFilter(e.target.value ? Number(e.target.value) : undefined)}
            style={{ width: 100 }}
            allowClear
          />
          <Select
            placeholder="设备状态"
            value={statusFilter}
            onChange={setStatusFilter}
            allowClear
            style={{ width: 100 }}
            options={[
              { value: 0, label: '离线' },
              { value: 1, label: '活跃' },
            ]}
          />
          <Select
            placeholder="信任状态"
            value={trustFilter}
            onChange={setTrustFilter}
            allowClear
            style={{ width: 100 }}
            options={[
              { value: true, label: '已信任' },
              { value: false, label: '未信任' },
            ]}
          />
          <Button type="primary" icon={<SearchOutlined />} onClick={() => void fetchDevices()}>
            查询
          </Button>
          <Button onClick={handleReset}>重置</Button>
        </Space>
      </FilterCard>

      {/* 设备列表 */}
      <TableCard>
        <Table
          columns={columns}
          dataSource={devices}
          rowKey="id"
          loading={loading}
          pagination={paginationConfig}
          scroll={{ x: 1400 }}
          locale={{
            emptyText: (
              <PageEmpty
                description="暂无设备数据"
              />
            ),
          }}
        />
      </TableCard>
    </PageLayout>
  )
}
