import { useEffect, useState } from 'react'
import Taro, { useRouter } from '@tarojs/taro'
import { Image, Input, Picker, ScrollView, Text, View } from '@tarojs/components'
import { useSystemLayout } from '@/hooks/useSystemLayout'
import Icon from '@/components/ui/Icon'
import SegmentedTabs from '@/components/ui/SegmentedTabs'
import { deletePet, getPet, savePet, uploadPetPhoto } from '@/services/pet.service'
import type { Pet } from '@/types/domain'
import './index.scss'

const speciesTabs = [
  { key: 'dog', label: '狗狗' },
  { key: 'cat', label: '猫咪' },
  { key: 'other', label: '其它' }
] as const

const CUSTOM = '自定义'

// Breed options linked to species; a 自定义 entry is appended at runtime.
const breedOptions: Record<Pet['species'], string[]> = {
  dog: ['金毛', '拉布拉多', '柯基', '柴犬', '萨摩耶', '哈士奇', '边境牧羊犬', '泰迪/贵宾', '比熊', '博美', '中华田园犬'],
  cat: ['布偶', '英国短毛', '美国短毛', '橘猫', '三花猫', '狸花猫', '暹罗', '加菲', '缅因', '中华田园猫'],
  other: ['仓鼠', '兔子', '龙猫', '鹦鹉', '乌龟', '蜥蜴']
}

const presetTags = ['亲人', '爱玩水', '可约遛', '安静', '精力旺盛', '慢热', '会接飞盘', '适合新手']

function nowYearMonth(): string {
  const d = new Date()
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`
}

function computeAge(ym: string): string {
  if (!ym) return ''
  const [y, m] = ym.split('-').map(Number)
  const d = new Date()
  let months = (d.getFullYear() - y) * 12 + (d.getMonth() + 1 - m)
  if (months < 0) months = 0
  if (months < 12) return `${months} 个月`
  return `${Math.floor(months / 12)} 岁`
}

export default function PetEditPage() {
  const { statusBarHeight, safeBottom } = useSystemLayout()
  const router = useRouter()
  const petId = router.params.petId || ''
  const isEdit = Boolean(petId)
  const today = nowYearMonth()

  const [name, setName] = useState('')
  const [species, setSpecies] = useState<Pet['species']>('dog')
  const [breed, setBreed] = useState('')
  const [breedCustom, setBreedCustom] = useState(false)
  const [birthDate, setBirthDate] = useState('')
  const [tags, setTags] = useState<string[]>([])
  const [photoUrl, setPhotoUrl] = useState('') // saved cloud fileID
  const [photoTemp, setPhotoTemp] = useState('') // newly chosen local temp path
  const [photoKey, setPhotoKey] = useState('photo-gold')
  const [avatarKey, setAvatarKey] = useState('gradient-avatar-4')
  const [saving, setSaving] = useState(false)

  useEffect(() => {
    if (!isEdit) return
    getPet(petId).then(pet => {
      if (!pet) return
      setName(pet.name || '')
      setSpecies(pet.species || 'dog')
      setBreed(pet.breed || '')
      setBreedCustom(Boolean(pet.breed) && !breedOptions[pet.species || 'dog'].includes(pet.breed))
      setBirthDate(pet.birthDate || '')
      setTags(pet.tags || [])
      setPhotoUrl(pet.photoUrl || '')
      setPhotoKey(pet.photoKey || 'photo-gold')
      setAvatarKey(pet.avatarKey || 'gradient-avatar-4')
    })
  }, [petId, isEdit])

  const breedList = [...breedOptions[species], CUSTOM]
  const breedIndex = breedCustom ? breedList.length - 1 : Math.max(0, breedList.indexOf(breed))
  const photoDisplay = photoTemp || photoUrl
  const photoDisplayUrl = photoDisplay && !photoDisplay.startsWith('cloud://') ? photoDisplay : ''

  const changeSpecies = (next: Pet['species']) => {
    setSpecies(next)
    setBreed('')
    setBreedCustom(false)
  }

  const onBreedChange = (e: any) => {
    const idx = Number(e.detail.value)
    if (idx === breedList.length - 1) {
      setBreedCustom(true)
      setBreed('')
    } else {
      setBreedCustom(false)
      setBreed(breedList[idx])
    }
  }

  const choosePhoto = async () => {
    try {
      const res = await Taro.chooseMedia({
        count: 1,
        mediaType: ['image'],
        sourceType: ['album', 'camera'],
        sizeType: ['compressed']
      })
      const path = res.tempFiles?.[0]?.tempFilePath
      if (path) setPhotoTemp(path)
    } catch {
      /* user cancelled */
    }
  }

  const toggleTag = (tag: string) => {
    setTags(current => (current.includes(tag) ? current.filter(t => t !== tag) : [...current, tag]))
  }

  const addCustomTag = () => {
    // editable/content are supported at runtime but missing from this Taro version's types.
    Taro.showModal({
      title: '自定义标签',
      editable: true,
      placeholderText: '如 会握手',
      success: (res: any) => {
        if (!res.confirm) return
        const t = (res.content || '').trim().slice(0, 8)
        if (t && !tags.includes(t)) setTags(cur => [...cur, t])
      }
    } as any)
  }

  const submit = async () => {
    if (saving) return
    if (!name.trim()) {
      Taro.showToast({ title: '请填写名字', icon: 'none' })
      return
    }
    if (!breed.trim()) {
      Taro.showToast({ title: '请选择或填写品种', icon: 'none' })
      return
    }
    setSaving(true)
    try {
      let finalPhotoUrl = photoUrl
      if (photoTemp) {
        finalPhotoUrl = (await uploadPetPhoto(photoTemp)) || photoUrl
      }
      const pet: Partial<Pet> = {
        name: name.trim(),
        species,
        breed: breed.trim(),
        birthDate,
        ageText: computeAge(birthDate),
        tags,
        photoUrl: finalPhotoUrl,
        photoKey,
        avatarKey
      }
      if (isEdit) pet._id = petId
      await savePet(pet)
      Taro.showToast({ title: isEdit ? '已保存' : '添加成功', icon: 'success' })
      setTimeout(() => Taro.navigateBack(), 600)
    } catch {
      Taro.showToast({ title: '保存失败，请重试', icon: 'none' })
    } finally {
      setSaving(false)
    }
  }

  const remove = () => {
    Taro.showModal({
      title: '删除毛孩子',
      content: `确定删除「${name || '该宠物'}」吗？此操作不可恢复。`,
      confirmText: '删除',
      confirmColor: '#ff8a9b',
      success: async res => {
        if (!res.confirm) return
        try {
          await deletePet(petId)
          Taro.showToast({ title: '已删除', icon: 'none' })
          setTimeout(() => Taro.navigateBack(), 500)
        } catch {
          Taro.showToast({ title: '删除失败', icon: 'none' })
        }
      }
    })
  }

  const customTags = tags.filter(t => !presetTags.includes(t))

  return (
    <View className='pet-edit'>
      <View className='pet-edit__nav' style={{ paddingTop: `${statusBarHeight}px` }}>
        <View className='pet-edit__nav-row'>
          <View className='pet-edit__close' onClick={() => Taro.navigateBack()}>
            <Icon name='close' size={22} />
          </View>
          <Text className='pet-edit__nav-title'>{isEdit ? '编辑毛孩子' : '添加毛孩子'}</Text>
          <View className='pet-edit__nav-spacer' />
        </View>
      </View>

      <ScrollView scrollY className='pet-edit__scroll' enhanced showScrollbar={false}>
        <View className='pet-edit__photo-row'>
          <View className={`pet-edit__photo ${photoDisplayUrl ? '' : photoKey}`} onClick={choosePhoto}>
            {photoDisplayUrl ? (
              <Image className='pet-edit__photo-img' src={photoDisplayUrl} mode='aspectFill' />
            ) : (
              <View className='pet-edit__photo-empty'>
                <Icon name='image' size={24} />
                <Text className='pet-edit__photo-hint'>添加照片</Text>
              </View>
            )}
          </View>
        </View>

        <View className='pet-edit__field'>
          <Text className='pet-edit__label'>名字</Text>
          <Input
            className='pet-edit__input'
            placeholder='给毛孩子起个名字'
            placeholderClass='pet-edit__placeholder'
            value={name}
            maxlength={12}
            onInput={e => setName(e.detail.value)}
          />
        </View>

        <View className='pet-edit__field'>
          <Text className='pet-edit__label'>物种</Text>
          <SegmentedTabs items={speciesTabs as any} value={species} onChange={changeSpecies} />
        </View>

        <View className='pet-edit__field'>
          <Text className='pet-edit__label'>品种</Text>
          <Picker mode='selector' range={breedList} value={breedIndex} onChange={onBreedChange}>
            <View className='pet-edit__picker'>
              <Text className={breed || breedCustom ? 'pet-edit__picker-value' : 'pet-edit__picker-ph'}>
                {breedCustom ? '自定义' : breed || '请选择品种'}
              </Text>
              <Icon name='chev' size={16} className='pet-edit__picker-arrow' />
            </View>
          </Picker>
          {breedCustom ? (
            <Input
              className='pet-edit__input pet-edit__input--mt'
              placeholder='填写品种'
              placeholderClass='pet-edit__placeholder'
              value={breed}
              maxlength={20}
              onInput={e => setBreed(e.detail.value)}
            />
          ) : null}
        </View>

        <View className='pet-edit__field'>
          <Text className='pet-edit__label'>出生年月</Text>
          <Picker
            mode='date'
            fields='month'
            start='2000-01'
            end={today}
            value={birthDate || today}
            onChange={e => setBirthDate(e.detail.value)}
          >
            <View className='pet-edit__picker'>
              <Text className={birthDate ? 'pet-edit__picker-value' : 'pet-edit__picker-ph'}>
                {birthDate ? `${birthDate} · ${computeAge(birthDate)}` : '请选择出生年月'}
              </Text>
              <Icon name='chev' size={16} className='pet-edit__picker-arrow' />
            </View>
          </Picker>
        </View>

        <View className='pet-edit__field'>
          <Text className='pet-edit__label'>性格标签</Text>
          <View className='pet-edit__tags'>
            {presetTags.map(tag => (
              <View
                key={tag}
                className={`pet-edit__tag ${tags.includes(tag) ? 'pet-edit__tag--active' : ''}`}
                onClick={() => toggleTag(tag)}
              >
                {tags.includes(tag) ? '× ' : '+ '}
                {tag}
              </View>
            ))}
            {customTags.map(tag => (
              <View key={tag} className='pet-edit__tag pet-edit__tag--active' onClick={() => toggleTag(tag)}>
                × {tag}
              </View>
            ))}
            <View className='pet-edit__tag pet-edit__tag--add' onClick={addCustomTag}>
              + 自定义
            </View>
          </View>
        </View>

        {isEdit ? (
          <View className='pet-edit__delete' onClick={remove}>
            删除这只毛孩子
          </View>
        ) : null}
      </ScrollView>

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