import { useCallback, useEffect, useState } from 'react'
import {
  Alert,
  Button,
  Col,
  DatePicker,
  Form,
  Input,
  Row,
  Select,
  Space,
  Spin,
  Tag,
  Typography,
  message,
} from 'antd'
import { SaveOutlined } from '@ant-design/icons'
import dayjs from 'dayjs'
import type { Dayjs } from 'dayjs'
import { Link } from 'react-router-dom'
import { useAuth } from '@/app/providers/auth-context'
import { getErrorMessage } from '@/lib/errors'
import { getCurrentProfile, updateProfile } from '@/services/profile'
import type { CurrentUserProfile } from '@/services/profile'
import type { UpdateUserRequest } from '@/types/user'
import { PageLayout, ContentCard } from '@/components/layout'
import { PageHeader } from '@/components/common'

const { Text } = Typography

const genderOptions = [
  { value: 0, label: '保密' },
  { value: 1, label: '男' },
  { value: 2, label: '女' },
]

interface ProfileFormValues {
  nickname?: string
  gender?: 0 | 1 | 2
  birthday?: Dayjs | null
  region?: string
  bio?: string
}

export function ProfilePage() {
  const { user, refreshUser } = useAuth()
  const [form] = Form.useForm<ProfileFormValues>()
  const [loading, setLoading] = useState(false)
  const [fetching, setFetching] = useState(true)
  const [profileData, setProfileData] = useState<CurrentUserProfile | null>(null)

  const fetchProfile = useCallback(async () => {
    if (!user) {
      return
    }

    try {
      setFetching(true)
      const data = await getCurrentProfile(user.id)
      setProfileData(data)
      form.setFieldsValue({
        nickname: data.user.nickname || undefined,
        gender: data.user.gender,
        birthday: data.user.birthday ? dayjs(data.user.birthday) : null,
        region: data.user.region || undefined,
        bio: data.user.bio || undefined,
      })
    } catch (error) {
      message.error(getErrorMessage(error, '获取个人资料失败'))
    } finally {
      setFetching(false)
    }
  }, [form, user])

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

  const handleSubmit = async (values: ProfileFormValues) => {
    if (!user) {
      return
    }

    const payload: UpdateUserRequest = {
      nickname: values.nickname,
      gender: values.gender,
      birthday: values.birthday?.format('YYYY-MM-DD'),
      region: values.region,
      bio: values.bio,
    }

    try {
      setLoading(true)
      await updateProfile(user.id, payload)
      await Promise.all([fetchProfile(), refreshUser()])
      message.success('资料更新成功')
    } catch (error) {
      message.error(getErrorMessage(error, '资料更新失败'))
    } finally {
      setLoading(false)
    }
  }

  if (fetching) {
    return (
      <div style={{ display: 'flex', justifyContent: 'center', padding: 100 }}>
        <Spin size="large" />
      </div>
    )
  }

  return (
    <PageLayout>
      <PageHeader
        title="个人资料"
        description="维护当前账号的基础资料信息"
      />

      <Alert
        type="info"
        showIcon
        message="头像上传已迁移到安全设置"
        description="当前后端仅提供头像上传接口，头像相关操作统一放到「安全设置」页处理。"
        style={{ marginBottom: 24 }}
      />

      <Row gutter={24}>
        <Col xs={24} lg={16}>
          <ContentCard title="基本信息">
            <Form form={form} layout="vertical" onFinish={handleSubmit}>
              <Alert
                type="info"
                showIcon
                message="邮箱和手机号已迁移到安全设置管理"
                description={<Link to="/profile/security">前往安全设置完成绑定、换绑或解绑</Link>}
                style={{ marginBottom: 16 }}
              />

              <Row gutter={16}>
                <Col xs={24} md={12}>
                  <Form.Item
                    name="nickname"
                    label="昵称"
                    rules={[{ max: 50, message: '昵称不能超过 50 个字符' }]}
                  >
                    <Input placeholder="请输入昵称" />
                  </Form.Item>
                </Col>
                <Col xs={24} md={12}>
                  <Form.Item name="gender" label="性别">
                    <Select options={genderOptions} placeholder="请选择性别" />
                  </Form.Item>
                </Col>
              </Row>

              <Row gutter={16}>
                <Col xs={24} md={12}>
                  <Form.Item name="birthday" label="生日">
                    <DatePicker
                      style={{ width: '100%' }}
                      placeholder="请选择生日"
                      disabledDate={(current) => current && current > dayjs().endOf('day')}
                    />
                  </Form.Item>
                </Col>
                <Col xs={24} md={12}>
                  <Form.Item
                    name="region"
                    label="地区"
                    rules={[{ max: 100, message: '地区不能超过 100 个字符' }]}
                  >
                    <Input placeholder="请输入地区" />
                  </Form.Item>
                </Col>
              </Row>

              <Form.Item
                name="bio"
                label="个人简介"
                rules={[{ max: 500, message: '简介不能超过 500 个字符' }]}
              >
                <Input.TextArea rows={4} maxLength={500} showCount placeholder="介绍一下自己..." />
              </Form.Item>

              <Form.Item style={{ marginBottom: 0 }}>
                <Button
                  type="primary"
                  htmlType="submit"
                  icon={<SaveOutlined />}
                  loading={loading}
                >
                  保存修改
                </Button>
              </Form.Item>
            </Form>
          </ContentCard>
        </Col>

        <Col xs={24} lg={8}>
          <ContentCard title="账号信息">
            <Space direction="vertical" size={12} style={{ width: '100%' }}>
              <div>
                <Text type="secondary">用户 ID</Text>
                <div>
                  <Text copyable>{profileData?.user.id}</Text>
                </div>
              </div>
              <div>
                <Text type="secondary">用户名</Text>
                <div>
                  <Text strong>{profileData?.user.username || '-'}</Text>
                </div>
              </div>
              <div>
                <Text type="secondary">注册时间</Text>
                <div>
                  <Text>
                    {profileData?.user.created_at
                      ? dayjs(profileData.user.created_at).format('YYYY-MM-DD HH:mm')
                      : '-'}
                  </Text>
                </div>
              </div>
              <div>
                <Text type="secondary">最后登录</Text>
                <div>
                  <Text>
                    {profileData?.user.last_login_at
                      ? dayjs(profileData.user.last_login_at).format('YYYY-MM-DD HH:mm')
                      : '-'}
                  </Text>
                </div>
              </div>
              <div>
                <Text type="secondary">邮箱</Text>
                <div>
                  <Text>{profileData?.user.email || '未绑定'}</Text>
                </div>
              </div>
              <div>
                <Text type="secondary">手机号</Text>
                <div>
                  <Text>{profileData?.user.phone || '未绑定'}</Text>
                </div>
              </div>
            </Space>
          </ContentCard>

          <ContentCard title="当前角色" style={{ marginTop: 16 }}>
            <Space wrap>
              {profileData?.roles.map((role) => (
                <Tag key={role.id} color={role.code === 'admin' ? 'processing' : 'default'}>
                  {role.name}
                </Tag>
              ))}
            </Space>
            {(!profileData?.roles || profileData.roles.length === 0) && (
              <Text type="secondary">暂无角色</Text>
            )}
          </ContentCard>
        </Col>
      </Row>
    </PageLayout>
  )
}
