import { Ionicons } from '@expo/vector-icons'
import { Block, ConfirmModal, Img, Input, Text, Toast } from '@share/components'
import { router, Stack } from 'expo-router'
import { observer } from 'mobx-react-lite'
import React, { useEffect, useState } from 'react'
import { ScrollView } from 'react-native'

import { authClient } from '@/lib/auth'
import { userStore } from '@/stores'

type InfoItem = {
  id: string
  label: string
  value: string
  valueGray?: boolean
  onPress: () => void
}

type EditNicknameModalProps = {
  initialName: string
  onConfirm: (name: string) => void | Promise<void>
  onCancel: () => void
}

function EditNicknameModal({ initialName, onConfirm, onCancel }: EditNicknameModalProps) {
  const [name, setName] = useState(initialName)

  useEffect(() => {
    setName(initialName)
  }, [initialName])

  return (
    <ConfirmModal
      badge="用户名"
      cancelText="取消"
      confirmText="确定"
      content={
        <Block className="w-full">
          <Input
            className="w-full rounded-lg border-2 border-black px-[12px] py-[10px] text-[14px]"
            placeholder="请输入6-12个字符"
            placeholderTextColor="#9CA3AF"
            value={name}
            onChangeText={setName}
          />
        </Block>
      }
      title="修改昵称"
      onCancel={onCancel}
      onConfirm={() => onConfirm(name)}
    />
  )
}

export default observer(function ProfilePage() {
  const { user } = userStore

  const handleEditAvatar = () => {
    // TODO: 打开相册/拍照更换头像
    Toast.show({ title: '更换头像功能开发中' })
  }

  const handleEditNickname = () => {
    Toast.showModal(
      <EditNicknameModal
        initialName={user?.name || ''}
        onConfirm={async (name) => {
          const trimmed = name.trim()
          if (trimmed.length < 6 || trimmed.length > 12) {
            Toast.show({ title: '请输入6-12个字符' })
            return
          }
          try {
            const res = await authClient.updateUser({ name: trimmed })
            const err = (res as { error?: { message?: string } }).error
            if (err) {
              Toast.show({ title: err.message || '修改失败，请重试' })
              return
            }
            if (userStore.user) {
              userStore.setUser({ ...userStore.user, name: trimmed })
            }
            Toast.hideModal()
            Toast.show({ title: '昵称已更新' })
          } catch (e) {
            Toast.show({ title: '修改失败，请重试' })
          }
        }}
        onCancel={() => Toast.hideModal()}
      />,
    )
  }

  const infoItems: InfoItem[] = [
    {
      id: 'nickname',
      label: '昵称',
      value: user?.name || '未设置',
      onPress: handleEditNickname,
    },
    {
      id: 'phone',
      label: '手机号',
      value: user?.phoneNumber || '',
      onPress: () => {
        Toast.show({ title: '手机号不可修改' })
      },
    }
  ]

  const renderHeader = () => (
    <Block className="flex-row items-center justify-between px-[16px] py-[10px]">
      <Block
        className="ml-[-8px] size-[40px] items-center justify-center"
        opacity={0.7}
        onClick={() => router.back()}
      >
        <Ionicons color="black" name="chevron-back" size={24} />
      </Block>
      <Text className="text-[16px] font-[700] text-black">个人信息</Text>
      <Block className="w-[32px]" />
    </Block>
  )

  const renderAvatarSection = () => (
    <Block className="mt-[24px] items-center">
      <Block className="relative size-[100px] overflow-hidden rounded-full">
        <Block className="size-[100px] items-center justify-center overflow-hidden rounded-full bg-gray-200">
          {user?.image ? (
            <Img
              src={user.image}
              style={{ width: 100, height: 100, borderRadius: 50 }}
              width={100}
            />
          ) : (
            <Ionicons color="#9CA3AF" name="person" size={48} />
          )}
        </Block>
        <Block
          className="absolute bottom-0 left-0 right-0 items-center justify-center bg-[#00000080] py-[2px]"
          style={{ borderBottomLeftRadius: 50, borderBottomRightRadius: 50 }}
          onClick={handleEditAvatar}
        >
          <Text className="text-[12px] font-[600] text-white">编辑</Text>
        </Block>
      </Block>
    </Block>
  )

  const renderInfoList = () => (
    <Block className="mt-[32px] px-[16px]">
      {infoItems.map((item) => (
        <Block
          key={item.id}
          className="flex-row items-center gap-[12px] py-[16px]"
          onClick={item.onPress}
        >
          <Text className="w-[56px] text-[14px] text-black">{item.label}</Text>
          <Text
            className="flex-1 text-[14px] text-right"
            style={{ color: item.valueGray ? '#9CA3AF' : '#000' }}
            numberOfLines={1}
            ellipsizeMode="tail"
          >
            {item.value}
          </Text>
          {/*手机号 显示隐藏按钮 */}
          {item.id !== 'phone' && (
            <Ionicons color="#9CA3AF" name="chevron-forward" size={18} />
          )}
        </Block>
      ))}
    </Block>
  )

  return (
    <Block className="h-full flex-1 bg-white">
      <Stack.Screen options={{ headerShown: false }} />
      {renderHeader()}
      <ScrollView contentContainerStyle={{ flexGrow: 1 }} showsVerticalScrollIndicator={false}>
        {renderAvatarSection()}
        {renderInfoList()}
      </ScrollView>
    </Block>
  )
})
