/**
 * 用户编辑抽屉
 */

import { useState, useEffect } from 'react'
import {
  Drawer,
  Form,
  Input,
  Select,
  Button,
  message,
  Space,
  DatePicker,
} from 'antd'
import dayjs from 'dayjs'
import { getErrorMessage, isFormValidationError } from '@/lib/errors'
import type { User } from '@/types/user'
import { updateUser } from '@/services/users'

interface UserEditDrawerProps {
  open: boolean
  user: User | null
  onSuccess: () => void
  onClose: () => void
}

export function UserEditDrawer({ open, user, onSuccess, onClose }: UserEditDrawerProps) {
  const [form] = Form.useForm()
  const [loading, setLoading] = useState(false)

  // 初始化表单
  useEffect(() => {
    if (open && user) {
      form.setFieldsValue({
        email: user.email,
        phone: user.phone,
        nickname: user.nickname,
        gender: user.gender,
        birthday: user.birthday ? dayjs(user.birthday) : null,
        region: user.region,
        bio: user.bio,
      })
    }
  }, [open, user, form])

  // 提交表单
  const handleSubmit = async () => {
    if (!user) return
    
    try {
      const values = await form.validateFields()
      setLoading(true)
      await updateUser(user.id, {
        ...values,
        // DatePicker 返回 dayjs 对象，转换为 YYYY-MM-DD 字符串
        birthday: values.birthday ? (values.birthday as ReturnType<typeof dayjs>).format('YYYY-MM-DD') : undefined,
      })
      message.success('用户信息已更新')
      onSuccess()
    } catch (err) {
      if (isFormValidationError(err)) {
        return
      }
      message.error(getErrorMessage(err, '更新失败'))
    } finally {
      setLoading(false)
    }
  }

  // 关闭时重置
  const handleClose = () => {
    form.resetFields()
    onClose()
  }

  return (
    <Drawer
      title="编辑用户"
      placement="right"
      width={480}
      open={open}
      onClose={handleClose}
      footer={
        <Space>
          <Button onClick={handleClose}>取消</Button>
          <Button type="primary" loading={loading} onClick={handleSubmit}>
            保存
          </Button>
        </Space>
      }
    >
      <Form form={form} layout="vertical">
        <Form.Item label="用户名">
          <Input value={user?.username} disabled />
        </Form.Item>
        
        <Form.Item
          name="email"
          label="邮箱"
          rules={[
            { type: 'email', message: '请输入有效的邮箱地址' },
          ]}
        >
          <Input placeholder="邮箱地址" />
        </Form.Item>
        
        <Form.Item
          name="phone"
          label="手机号"
          rules={[
            { pattern: /^1\d{10}$/, message: '请输入有效的手机号' },
          ]}
        >
          <Input placeholder="手机号" />
        </Form.Item>
        
        <Form.Item name="nickname" label="昵称">
          <Input placeholder="昵称" />
        </Form.Item>
        
        <Form.Item name="gender" label="性别">
          <Select
            placeholder="选择性别"
            allowClear
            options={[
              { value: 0, label: '未知' },
              { value: 1, label: '男' },
              { value: 2, label: '女' },
            ]}
          />
        </Form.Item>
        
        <Form.Item name="birthday" label="生日">
          <DatePicker
            style={{ width: '100%' }}
            placeholder="请选择生日"
            disabledDate={(current) => current && current > dayjs().endOf('day')}
          />
        </Form.Item>
        
        <Form.Item name="region" label="地区">
          <Input placeholder="地区" />
        </Form.Item>
        
        <Form.Item name="bio" label="简介">
          <Input.TextArea rows={3} placeholder="个人简介" />
        </Form.Item>
      </Form>
    </Drawer>
  )
}
