import { DeleteOutlined, UploadOutlined } from '@ant-design/icons'
import { Button, Form, Popconfirm, Space, Typography, Upload, message } from 'antd'
import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { studentApi } from '../api/client'
import type { Student } from '../types'
import StudentAvatar from './StudentAvatar'
import StudentFormFields, { type StudentFormValues } from './StudentFormFields'

interface Props {
  student: Student
  onUpdated: (student: Student) => void
}

export default function StudentSettingsPanel({ student, onUpdated }: Props) {
  const navigate = useNavigate()
  const [form] = Form.useForm<StudentFormValues>()
  const [saving, setSaving] = useState(false)
  const [avatarLoading, setAvatarLoading] = useState(false)
  const [current, setCurrent] = useState(student)

  useEffect(() => {
    setCurrent(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,
    })
  }, [student, form])

  const handleSave = async () => {
    const values = await form.validateFields()
    setSaving(true)
    try {
      const { data } = await studentApi.update(student.id, values)
      setCurrent(data)
      onUpdated(data)
      message.success('学生资料已保存')
    } finally {
      setSaving(false)
    }
  }

  const handleAvatar = async (file: File) => {
    setAvatarLoading(true)
    try {
      const { data } = await studentApi.uploadAvatar(student.id, file)
      setCurrent(data)
      onUpdated(data)
      message.success('头像已更新')
    } catch {
      message.error('头像上传失败')
    } finally {
      setAvatarLoading(false)
    }
    return false
  }

  const handleRemoveAvatar = async () => {
    const { data } = await studentApi.removeAvatar(student.id)
    setCurrent(data)
    onUpdated(data)
    message.success('头像已移除')
  }

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

  return (
    <Space direction="vertical" size="large" style={{ width: '100%', maxWidth: 520 }}>
      <Typography.Paragraph type="secondary" style={{ marginBottom: 0 }}>
        在此修改学生基本信息。年级按学段选择（初一至初三 / 高一至高三），供 AI 与统计按课内要求使用。
      </Typography.Paragraph>

      <Space align="center" size="middle">
        <StudentAvatar student={current} size={72} />
        <Space direction="vertical" size={8}>
          <Upload beforeUpload={handleAvatar} showUploadList={false} accept="image/*">
            <Button icon={<UploadOutlined />} loading={avatarLoading}>
              上传头像
            </Button>
          </Upload>
          {current.has_avatar && (
            <Button size="small" danger onClick={handleRemoveAvatar}>
              移除头像
            </Button>
          )}
        </Space>
      </Space>

      <Form form={form} layout="vertical">
        <StudentFormFields form={form} />
        <Space wrap>
          <Button type="primary" loading={saving} onClick={handleSave}>
            保存资料
          </Button>
          <Popconfirm
            title="确定删除该学生？"
            description="将同时删除其成绩、错题、作文等全部数据，且不可恢复。"
            onConfirm={handleDelete}
          >
            <Button danger icon={<DeleteOutlined />}>
              删除学生
            </Button>
          </Popconfirm>
        </Space>
      </Form>
    </Space>
  )
}
