import { useCallback, useEffect, useState } from 'react'
import {
  Button,
  Card,
  Form,
  Input,
  Modal,
  Select,
  Space,
  Table,
  Tag,
  Typography,
  message,
} from 'antd'
import type { ColumnsType } from 'antd/es/table'
import { sysErrorApi } from '@/lib/api'
import { formatDate } from '@/lib/date'
import type { SysErrorRecord } from '@/types/system'

export function ErrorLogPage() {
  const [editForm] = Form.useForm()
  const [rows, setRows] = useState<SysErrorRecord[]>([])
  const [loading, setLoading] = useState(false)
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(10)
  const [total, setTotal] = useState(0)
  const [editingRow, setEditingRow] = useState<SysErrorRecord | null>(null)

  const reloadRows = useCallback(async () => {
    setLoading(true)
    try {
      const response = await sysErrorApi.getErrorList({
        page,
        pageSize,
      })
      setRows(response.data.list)
      setTotal(response.data.total)
    } finally {
      setLoading(false)
    }
  }, [page, pageSize])

  useEffect(() => {
    reloadRows()
  }, [reloadRows])

  const saveRow = async () => {
    const values = await editForm.validateFields()
    if (!editingRow) {
      return
    }
    await sysErrorApi.updateError({
      ...editingRow,
      ...values,
    })
    message.success('错误日志已更新')
    setEditingRow(null)
    reloadRows()
  }

  const columns: ColumnsType<SysErrorRecord> = [
    {
      title: '时间',
      width: 180,
      render: (_, record) => formatDate(record.CreatedAt),
    },
    {
      title: '来源',
      dataIndex: 'form',
      width: 180,
    },
    {
      title: '等级',
      dataIndex: 'level',
      width: 100,
    },
    {
      title: '状态',
      width: 120,
      render: (_, record) => <Tag>{record.status || '未处理'}</Tag>,
    },
    {
      title: '错误内容',
      dataIndex: 'info',
    },
    {
      title: '解决方案',
      dataIndex: 'solution',
    },
    {
      title: '操作',
      width: 220,
      render: (_, record) => (
        <Space>
          <Button
            type="link"
            onClick={() => {
              setEditingRow(record)
              editForm.setFieldsValue({
                status: record.status,
                solution: record.solution,
              })
            }}
          >
            编辑
          </Button>
          <Button
            type="link"
            onClick={async () => {
              await sysErrorApi.handleError(record.ID)
              message.success('AI 处理任务已触发')
              reloadRows()
            }}
          >
            AI 处理
          </Button>
          <Button
            danger
            type="link"
            onClick={async () => {
              await sysErrorApi.deleteError(record.ID)
              message.success('错误日志已删除')
              reloadRows()
            }}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ]

  return (
    <div className="page-stack">
      <Card className="glass-panel page-panel">
        <div className="section-heading">
          <div>
            <Typography.Title level={2} style={{ marginBottom: 8 }}>
              错误日志
            </Typography.Title>
            <Typography.Paragraph className="text-muted" style={{ marginBottom: 0 }}>
              当前页提供错误列表、状态更新和 AI 处理触发入口。
            </Typography.Paragraph>
          </div>
        </div>
      </Card>
      <Card className="glass-panel page-panel">
        <Table
          rowKey="ID"
          loading={loading}
          columns={columns}
          dataSource={rows}
          pagination={{
            current: page,
            pageSize,
            total,
            showSizeChanger: true,
            onChange: (nextPage, nextPageSize) => {
              setPage(nextPage)
              setPageSize(nextPageSize)
            },
          }}
        />
      </Card>

      <Modal open={Boolean(editingRow)} title="编辑错误日志" onCancel={() => setEditingRow(null)} onOk={saveRow}>
        <Form form={editForm} layout="vertical">
          <Form.Item name="status" label="处理状态">
            <Select
              options={[
                { label: '未处理', value: '未处理' },
                { label: '处理中', value: '处理中' },
                { label: '处理完成', value: '处理完成' },
              ]}
            />
          </Form.Item>
          <Form.Item name="solution" label="解决方案">
            <Input.TextArea rows={4} />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}
