import { DeleteOutlined, EditOutlined, LogoutOutlined, PlusOutlined, SettingOutlined } from '@ant-design/icons'
import { Button, Card, Col, Form, Modal, Popconfirm, Row, Space, Spin, Tag, Typography, message } from 'antd'
import { useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import { studentApi } from '../api/client'
import StudentAvatar from '../components/StudentAvatar'
import StudentFormFields, { type StudentFormValues } from '../components/StudentFormFields'
import { formatStudentSubtitle, SCHOOL_LEVEL_LABELS } from '../constants/school'
import { useAuth } from '../context/AuthContext'
import type { Student } from '../types'

export default function StudentsPage() {
  const { user, logout } = useAuth()
  const [students, setStudents] = useState<Student[]>([])
  const [loading, setLoading] = useState(true)
  const [modalOpen, setModalOpen] = useState(false)
  const [editing, setEditing] = useState<Student | null>(null)
  const [form] = Form.useForm<StudentFormValues>()

  const load = async () => {
    setLoading(true)
    try {
      const { data } = await studentApi.list()
      setStudents(data)
    } finally {
      setLoading(false)
    }
  }

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

  const openCreate = () => {
    setEditing(null)
    form.setFieldsValue({ school_level: 'junior_high', grade: undefined, school_name: undefined })
    setModalOpen(true)
  }

  const openEdit = (student: Student) => {
    setEditing(student)
    form.setFieldsValue({
      name: student.name,
      school_name: student.school_name || undefined,
      school_level: student.school_level,
      grade: student.grade || undefined,
      class_name: student.class_name || undefined,
    })
    setModalOpen(true)
  }

  const handleSubmit = async () => {
    const values = await form.validateFields()
    if (editing) {
      await studentApi.update(editing.id, values)
      message.success('学生资料已更新')
    } else {
      await studentApi.create(values)
      message.success('学生已添加')
    }
    setModalOpen(false)
    form.resetFields()
    load()
  }

  const handleDelete = async (student: Student) => {
    await studentApi.remove(student.id)
    message.success('学生已删除')
    load()
  }

  return (
    <div className="page-container">
      <div
        style={{
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          marginBottom: 24,
          flexWrap: 'wrap',
          gap: 12,
        }}
      >
        <div>
          <Typography.Title level={3} style={{ margin: 0 }}>
            学生档案
          </Typography.Title>
          <Typography.Text type="secondary">欢迎，{user?.username}</Typography.Text>
        </div>
        <Space wrap>
          {user?.is_superuser && (
            <Link to="/settings">
              <Button icon={<SettingOutlined />}>系统设置</Button>
            </Link>
          )}
          <Button type="primary" icon={<PlusOutlined />} onClick={openCreate}>
            添加学生
          </Button>
          <Button icon={<LogoutOutlined />} onClick={logout}>
            退出
          </Button>
        </Space>
      </div>

      <Spin spinning={loading}>
        <Row gutter={[16, 16]}>
          {students.map((s) => (
            <Col xs={24} sm={12} md={8} key={s.id}>
              <Card
                hoverable
                actions={[
                  <Button
                    type="link"
                    icon={<EditOutlined />}
                    onClick={() => openEdit(s)}
                    key="edit"
                  >
                    修改
                  </Button>,
                  <Popconfirm
                    key="delete"
                    title="确定删除该学生？"
                    description="将删除其全部成绩与错题数据"
                    onConfirm={() => handleDelete(s)}
                  >
                    <Button type="link" danger icon={<DeleteOutlined />}>
                      删除
                    </Button>
                  </Popconfirm>,
                ]}
              >
                <Link to={`/students/${s.id}`} style={{ textDecoration: 'none', color: 'inherit' }}>
                  <Space align="start">
                    <StudentAvatar student={s} size={48} />
                    <div>
                      <Space size={4} wrap>
                        <Typography.Text strong>{s.name}</Typography.Text>
                        <Tag color={s.school_level === 'senior_high' ? 'purple' : 'blue'}>
                          {SCHOOL_LEVEL_LABELS[s.school_level]}
                        </Tag>
                      </Space>
                      <br />
                      <Typography.Text type="secondary" style={{ fontSize: 12 }}>
                        {formatStudentSubtitle(s)}
                      </Typography.Text>
                    </div>
                  </Space>
                </Link>
              </Card>
            </Col>
          ))}
          {!loading && students.length === 0 && (
            <Col span={24}>
              <Card>
                <Typography.Text type="secondary">暂无学生，点击「添加学生」开始</Typography.Text>
              </Card>
            </Col>
          )}
        </Row>
      </Spin>

      <Modal
        title={editing ? '修改学生' : '添加学生'}
        open={modalOpen}
        onCancel={() => setModalOpen(false)}
        onOk={handleSubmit}
        destroyOnHidden
      >
        <Form form={form} layout="vertical" initialValues={{ school_level: 'junior_high' }}>
          <StudentFormFields form={form} />
        </Form>
      </Modal>
    </div>
  )
}
