import { useEffect, useRef, useState } from 'react'
import Taro from '@tarojs/taro'
import { Button, Image, Input, Picker, ScrollView, Text, Textarea, View } from '@tarojs/components'
import { useSystemLayout } from '@/hooks/useSystemLayout'
import Icon from '@/components/ui/Icon'
import Avatar from '@/components/ui/Avatar'
import { uploadAvatar } from '@/services/auth.service'
import { getProfile, updateProfile } from '@/services/profile.service'
import type { UserProfile } from '@/types/domain'
import './index.scss'

const YEAR_RANGE = Array.from({ length: 101 }, (_, i) => `${i}`)

interface ProfileEditSnapshot {
  avatarUrl: string
  avatarKey: string
  nickname: string
  bio: string
  location: string
  years: string
}

export default function ProfileEditPage() {
  const { statusBarHeight, safeBottom } = useSystemLayout()

  const [avatarUrl, setAvatarUrl] = useState('')
  const [avatarKey, setAvatarKey] = useState('gradient-avatar-2')
  const [avatarTemp, setAvatarTemp] = useState('')
  const [nickname, setNickname] = useState('')
  const [bio, setBio] = useState('')
  const [location, setLocation] = useState('')
  const [years, setYears] = useState('')
  const [saving, setSaving] = useState(false)
  const initialRef = useRef<ProfileEditSnapshot | null>(null)
  const avatarDisplayUrl = avatarUrl && !avatarUrl.startsWith('cloud://') ? avatarUrl : ''

  useEffect(() => {
    getProfile().then(({ user }) => {
      const snapshot = {
        avatarUrl: user.avatarUrl || '',
        avatarKey: user.avatarKey || 'gradient-avatar-2',
        nickname: user.nickname || '',
        bio: user.bio || '',
        location: user.location || '',
        years: String(user.yearsWithPets || 0)
      }
      initialRef.current = snapshot
      setAvatarUrl(snapshot.avatarUrl)
      setAvatarKey(snapshot.avatarKey)
      setNickname(snapshot.nickname)
      setBio(snapshot.bio)
      setLocation(snapshot.location)
      setYears(snapshot.years)
    })
  }, [])

  const isDirty = () => {
    const initial = initialRef.current
    if (!initial) return Boolean(avatarTemp || nickname || bio || location || years)
    return Boolean(
      avatarTemp ||
      initial.avatarUrl !== avatarUrl ||
      initial.avatarKey !== avatarKey ||
      initial.nickname !== nickname ||
      initial.bio !== bio ||
      initial.location !== location ||
      initial.years !== years
    )
  }

  const handleClose = async () => {
    if (saving) return
    if (!isDirty()) {
      Taro.navigateBack()
      return
    }

    const res = await Taro.showModal({
      title: '放弃修改？',
      content: '当前资料尚未保存，离开后修改会丢失。',
      cancelText: '继续编辑',
      confirmText: '放弃'
    })
    if (res.confirm) Taro.navigateBack()
  }

  const onChooseAvatar = (e: any) => {
    const url = e?.detail?.avatarUrl
    if (url) {
      setAvatarTemp(url)
      setAvatarUrl(url)
    }
  }

  const onRegionChange = (e: any) => {
    const parts: string[] = e.detail.value || []
    // Drop the duplicated entry for municipalities (province === city).
    const cleaned = parts.filter((p, i) => i === 0 || p !== parts[i - 1])
    setLocation(cleaned.join(' '))
  }

  const onYearChange = (e: any) => {
    setYears(YEAR_RANGE[Number(e.detail.value)] || '0')
  }

  const submit = async () => {
    if (saving) return
    if (!nickname.trim()) {
      Taro.showToast({ title: '请填写昵称', icon: 'none' })
      return
    }
    setSaving(true)
    try {
      const patch: Partial<UserProfile> = {
        nickname: nickname.trim(),
        bio: bio.trim(),
        location: location.trim(),
        yearsWithPets: Math.max(0, Number(years) || 0)
      }
      if (avatarTemp) {
        const fileId = await uploadAvatar(avatarTemp)
        if (fileId) patch.avatarUrl = fileId
      }
      await updateProfile(patch)
      Taro.showToast({ title: '已保存', icon: 'success' })
      setTimeout(() => Taro.navigateBack(), 600)
    } catch {
      Taro.showToast({ title: '保存失败，请重试', icon: 'none' })
    } finally {
      setSaving(false)
    }
  }

  return (
    <View className='profile-edit'>
      <View className='profile-edit__nav' style={{ paddingTop: `${statusBarHeight}px` }}>
        <View className='profile-edit__nav-row'>
          <View className='profile-edit__close' onClick={handleClose}>
            <Icon name='close' size={22} />
          </View>
          <Text className='profile-edit__nav-title'>编辑资料</Text>
          <View className='profile-edit__nav-spacer' />
        </View>
      </View>

      <ScrollView scrollY className='profile-edit__scroll' enhanced showScrollbar={false}>
        <View className='profile-edit__avatar-row'>
          <Button className='profile-edit__avatar-btn' openType='chooseAvatar' onChooseAvatar={onChooseAvatar}>
            {avatarDisplayUrl ? (
              <Image className='profile-edit__avatar-img' src={avatarDisplayUrl} mode='aspectFill' />
            ) : (
              <Avatar avatarKey={avatarKey} size='xl' label={nickname} />
            )}
            <View className='profile-edit__avatar-edit'>
              <Icon name='image' size={12} />
            </View>
          </Button>
          <Text className='profile-edit__avatar-hint'>点击更换头像</Text>
        </View>

        <View className='profile-edit__field'>
          <Text className='profile-edit__label'>昵称</Text>
          <Input
            className='profile-edit__input'
            type='nickname'
            placeholder='填写昵称'
            placeholderClass='profile-edit__placeholder'
            value={nickname}
            maxlength={16}
            onInput={e => setNickname(e.detail.value)}
            onBlur={e => setNickname(e.detail.value)}
          />
        </View>

        <View className='profile-edit__field'>
          <Text className='profile-edit__label'>个人简介</Text>
          <Textarea
            className='profile-edit__textarea'
            placeholder='介绍一下你和毛孩子的故事'
            placeholderClass='profile-edit__placeholder'
            value={bio}
            maxlength={80}
            onInput={e => setBio(e.detail.value)}
          />
        </View>

        <View className='profile-edit__field'>
          <Text className='profile-edit__label'>所在地区</Text>
          <Picker mode='region' onChange={onRegionChange}>
            <View className='profile-edit__picker'>
              <Text className={location ? 'profile-edit__picker-value' : 'profile-edit__picker-ph'}>
                {location || '请选择省 / 市 / 区'}
              </Text>
              <Icon name='chev' size={16} className='profile-edit__picker-arrow' />
            </View>
          </Picker>
        </View>

        <View className='profile-edit__field'>
          <Text className='profile-edit__label'>养宠年数</Text>
          <Picker
            mode='selector'
            range={YEAR_RANGE}
            value={Math.min(100, Math.max(0, Number(years) || 0))}
            onChange={onYearChange}
          >
            <View className='profile-edit__picker'>
              <Text className='profile-edit__picker-value'>{years || '0'} 年</Text>
              <Icon name='chev' size={16} className='profile-edit__picker-arrow' />
            </View>
          </Picker>
        </View>
      </ScrollView>

      <View className='profile-edit__footer' style={{ paddingBottom: `${Math.max(16, safeBottom)}px` }}>
        <View className='profile-edit__submit' onClick={submit}>
          {saving ? '保存中…' : '保存'}
        </View>
      </View>
    </View>
  )
}
