import { useCallback, useEffect, useState } from 'react'
import {
  Button,
  DatePicker,
  Input,
  message,
  Select,
  Space,
  Table,
  Tag,
  type TableColumnsType,
  type TablePaginationConfig,
} from 'antd'
import { DownloadOutlined, EyeOutlined, ReloadOutlined, SearchOutlined } 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 { exportLoginLogs, listLoginLogs } from '@/services/login-logs'
import {
  LoginStatusColor,
  LoginStatusText,
  LoginTypeText,
  type LoginLog,
  type LoginLogListParams,
  type LoginStatus,
} from '@/types/login-log'
import { LoginLogDetailDrawer } from './LoginLogDetailDrawer'

const { RangePicker } = DatePicker

export function LoginLogsPage() {
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [logs, setLogs] = useState<LoginLog[]>([])
  const [total, setTotal] = useState(0)
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(20)
  const [userId, setUserId] = useState('')
  const [statusFilter, setStatusFilter] = useState<LoginStatus | undefined>()
  const [startAt, setStartAt] = useState<string | undefined>()
  const [endAt, setEndAt] = useState<string | undefined>()
  const [detailVisible, setDetailVisible] = useState(false)
  const [selectedLog, setSelectedLog] = useState<LoginLog | null>(null)

  const fetchLogs = useCallback(async () => {
    setLoading(true)
    setError(null)

    try {
      const params: LoginLogListParams = {
        page,
        page_size: pageSize,
        user_id: userId ? parseInt(userId, 10) : undefined,
        status: statusFilter,
        start_at: startAt,
        end_at: endAt,
      }
      const result = await listLoginLogs(params)
      setLogs(result.items)
      setTotal(result.total)
    } catch (err) {
      setError(getErrorMessage(err, '获取登录日志失败'))
    } finally {
      setLoading(false)
    }
  }, [endAt, page, pageSize, startAt, statusFilter, userId])

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

  // 筛选条件变化时重置到第一页
  useEffect(() => {
    setPage(1)
  }, [userId, statusFilter, startAt, endAt])

  const handleReset = () => {
    setUserId('')
    setStatusFilter(undefined)
    setStartAt(undefined)
    setEndAt(undefined)
    setPage(1)
    // Directly call listLoginLogs with explicit cleared values to avoid stale closure issues
    void listLoginLogs({
      page: 1,
      page_size: pageSize,
      user_id: undefined,
      status: undefined,
      start_at: undefined,
      end_at: undefined,
    }).then((result) => {
      setLogs(result.items)
      setTotal(result.total)
    })
  }

  const handleExport = async () => {
    try {
      await exportLoginLogs({
        user_id: userId ? parseInt(userId, 10) : undefined,
        status: statusFilter,
        format: 'csv',
        start_at: startAt,
        end_at: endAt,
      })
      message.success('导出成功')
    } catch (err) {
      message.error(getErrorMessage(err, '导出失败'))
    }
  }

  const columns: TableColumnsType<LoginLog> = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '用户 ID',
      dataIndex: 'user_id',
      key: 'user_id',
      width: 100,
      render: (value) => value ?? '-',
    },
    {
      title: '登录类型',
      dataIndex: 'login_type',
      key: 'login_type',
      width: 140,
      render: (value: LoginLog['login_type']) => LoginTypeText[value] || value,
    },
    {
      title: '设备 ID',
      dataIndex: 'device_id',
      key: 'device_id',
      width: 180,
      render: (value) => value || '-',
    },
    {
      title: 'IP',
      dataIndex: 'ip',
      key: 'ip',
      width: 140,
    },
    {
      title: '位置',
      dataIndex: 'location',
      key: 'location',
      width: 180,
      render: (value) => value || '-',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: LoginLog['status']) => (
        <Tag color={LoginStatusColor[status]}>{LoginStatusText[status]}</Tag>
      ),
    },
    {
      title: '失败原因',
      dataIndex: 'fail_reason',
      key: 'fail_reason',
      width: 220,
      render: (value) => value || '-',
    },
    {
      title: '登录时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 180,
      render: (value) => dayjs(value).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      fixed: 'right',
      render: (_, record) => (
        <Button type="link" size="small" icon={<EyeOutlined />} onClick={() => {
          setSelectedLog(record)
          setDetailVisible(true)
        }}>
          详情
        </Button>
      ),
    },
  ]

  const paginationConfig: TablePaginationConfig = {
    current: page,
    pageSize,
    total,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (value) => `共 ${value} 条`,
    onChange: (current, size) => {
      setPage(current)
      setPageSize(size)
    },
  }

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

  return (
    <PageLayout>
      <PageHeader
        title="登录日志"
        description="对齐后端 `/logs/login` 的真实查询模型，只保留稳定支持的筛选项"
        actions={(
          <Space>
            <Button icon={<DownloadOutlined />} onClick={() => void handleExport()}>
              导出
            </Button>
            <Button icon={<ReloadOutlined />} onClick={() => void fetchLogs()}>
              刷新
            </Button>
          </Space>
        )}
      />

      <FilterCard>
        <Space wrap size="middle">
          <Input
            placeholder="用户 ID"
            prefix={<SearchOutlined />}
            value={userId}
            onChange={(event) => setUserId(event.target.value.replace(/[^\d]/g, ''))}
            onPressEnter={() => void fetchLogs()}
            style={{ width: 160 }}
            allowClear
          />
          <Select
            placeholder="登录状态"
            value={statusFilter}
            onChange={setStatusFilter}
            allowClear
            style={{ width: 120 }}
            options={[
              { value: 1, label: '成功' },
              { value: 0, label: '失败' },
            ]}
          />
          <RangePicker
            placeholder={['开始时间', '结束时间']}
            showTime
            onChange={(_, dateStrings) => {
              setStartAt(dateStrings[0] || undefined)
              setEndAt(dateStrings[1] || undefined)
            }}
          />
          <Button type="primary" icon={<SearchOutlined />} onClick={() => void fetchLogs()}>
            查询
          </Button>
          <Button onClick={handleReset}>重置</Button>
        </Space>
      </FilterCard>

      <TableCard>
        <Table
          columns={columns}
          dataSource={logs}
          rowKey="id"
          loading={loading}
          pagination={paginationConfig}
          scroll={{ x: 1380 }}
          locale={{ emptyText: <PageEmpty description="暂无登录日志" /> }}
        />
      </TableCard>

      <LoginLogDetailDrawer
        open={detailVisible}
        log={selectedLog}
        onClose={() => setDetailVisible(false)}
      />
    </PageLayout>
  )
}
