import { useCallback, useEffect, useState } from 'react'
import {
  Button,
  DatePicker,
  Input,
  Select,
  Space,
  Table,
  Tag,
  type TableColumnsType,
  type TablePaginationConfig,
} from 'antd'
import { 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 { listOperationLogs } from '@/services/operation-logs'
import type { OperationLog, OperationLogListParams } from '@/types/operation-log'
import { OperationLogDetailDrawer } from './OperationLogDetailDrawer'

const { RangePicker } = DatePicker

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

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

    try {
      const params: OperationLogListParams = {
        page,
        page_size: pageSize,
        user_id: userId ? Number(userId) : undefined,
        method,
        keyword: keyword || undefined,
        start_at: startAt,
        end_at: endAt,
      }
      const result = await listOperationLogs(params)
      setLogs(result.items)
      setTotal(result.total)
    } catch (err) {
      setError(getErrorMessage(err, '获取操作日志失败'))
    } finally {
      setLoading(false)
    }
  }, [endAt, keyword, method, page, pageSize, startAt, userId])

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

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

  const handleReset = () => {
    setUserId('')
    setMethod(undefined)
    setKeyword('')
    setStartAt(undefined)
    setEndAt(undefined)
    setPage(1)
  }

  const columns: TableColumnsType<OperationLog> = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '用户 ID',
      dataIndex: 'user_id',
      key: 'user_id',
      width: 100,
      render: (value) => value ?? '-',
    },
    {
      title: '操作类型',
      dataIndex: 'operation_type',
      key: 'operation_type',
      width: 140,
    },
    {
      title: '操作名称',
      dataIndex: 'operation_name',
      key: 'operation_name',
      width: 180,
    },
    {
      title: '请求方法',
      dataIndex: 'request_method',
      key: 'request_method',
      width: 100,
      render: (value) => <Tag>{value}</Tag>,
    },
    {
      title: '请求路径',
      dataIndex: 'request_path',
      key: 'request_path',
      width: 260,
      ellipsis: true,
    },
    {
      title: '状态码',
      dataIndex: 'response_status',
      key: 'response_status',
      width: 100,
      render: (value) => (
        <Tag color={value >= 200 && value < 300 ? 'success' : 'error'}>{value}</Tag>
      ),
    },
    {
      title: 'IP',
      dataIndex: 'ip',
      key: 'ip',
      width: 140,
    },
    {
      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/operation` 的真实筛选参数和字段模型"
        actions={(
          <Button icon={<ReloadOutlined />} onClick={() => void fetchLogs()}>
            刷新
          </Button>
        )}
      />

      <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={method}
            onChange={setMethod}
            allowClear
            style={{ width: 120 }}
            options={[
              { value: 'GET', label: 'GET' },
              { value: 'POST', label: 'POST' },
              { value: 'PUT', label: 'PUT' },
              { value: 'DELETE', label: 'DELETE' },
              { value: 'PATCH', label: 'PATCH' },
            ]}
          />
          <Input
            placeholder="关键字"
            value={keyword}
            onChange={(event) => setKeyword(event.target.value)}
            onPressEnter={() => void fetchLogs()}
            style={{ width: 200 }}
            allowClear
          />
          <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: 1460 }}
          locale={{ emptyText: <PageEmpty description="暂无操作日志" /> }}
        />
      </TableCard>

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