import { useEffect, useState } from 'react'
import Taro from '@tarojs/taro'
import { View } from '@tarojs/components'
import CustomNavBar from '@/components/layout/CustomNavBar'
import PageShell from '@/components/layout/PageShell'
import ProfileHero from '@/features/profile/components/ProfileHero'
import StatsRow from '@/features/profile/components/StatsRow'
import PetShelf from '@/features/profile/components/PetShelf'
import PreferenceList from '@/features/profile/components/PreferenceList'
import LoginCard from '@/features/profile/components/LoginCard'
import { completeLogin, isLoggedOut, logout } from '@/services/auth.service'
import { getProfile, updateProfile } from '@/services/profile.service'
import { hasChatMessageTemplate, requestChatMessageSubscription } from '@/services/notification.service'
import { mockPets } from '@/services/mock'
import { useSession, ensureLogin, clearSession } from '@/store/session.store'
import { useTabRefresh } from '@/hooks/useTabRefresh'
import { markFresh } from '@/store/dataBus'
import type { TabViewProps } from '@/components/navigation/BottomTabBar/tabConfig'
import type { Pet, UserProfile } from '@/types/domain'
import './index.scss'

export default function ProfilePage({ active = false, showTick = 0 }: TabViewProps) {
  // Shared session — no per-page login roundtrip; the cached user paints instantly.
  const { user, setUser } = useSession()
  const [pets, setPets] = useState<Pet[]>(mockPets)
  const [needsLogin, setNeedsLogin] = useState(false)
  const [loading, setLoading] = useState(true)

  // Fetch the authoritative profile + pets. The current view stays visible while
  // refreshing (no flash) — `loading` only gates the very first paint.
  const loadProfile = () => {
    if (isLoggedOut()) return
    getProfile().then(({ user: u, pets: p }) => {
      setUser(u)
      setPets(p)
      setNeedsLogin(isLoggedOut() || !u.profileCompleted)
      markFresh('profile')
    })
  }

  useEffect(() => {
    ensureLogin().then(current => {
      setNeedsLogin(isLoggedOut() || !current.profileCompleted)
      setLoading(false)
      loadProfile()
    })
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  // Refresh when returning from the edit pages — only when marked stale by a save
  // or the TTL elapsed.
  useTabRefresh('profile', active, showTick, loadProfile)

  const handleLogin = async (avatarPath: string, nickname: string) => {
    try {
      const updated = await completeLogin(avatarPath, nickname)
      setUser(updated)
      setNeedsLogin(false)
      Taro.showToast({ title: '登录成功', icon: 'success' })
    } catch {
      Taro.showToast({ title: '登录失败，请重试', icon: 'none' })
    }
  }

  const handleLogout = () => {
    Taro.showModal({
      title: '退出登录',
      content: '确定要退出当前账号吗？',
      confirmText: '退出',
      confirmColor: '#ff8a9b',
      success: async res => {
        if (!res.confirm) return
        await logout()
        clearSession()
        setPets([])
        setNeedsLogin(true)
        Taro.showToast({ title: '已退出登录', icon: 'none' })
      }
    })
  }

  const handleAction = (key: 'help' | 'about') => {
    if (key === 'help') {
      Taro.showModal({
        title: '帮助与反馈',
        content: '遇到问题或有建议？\n请发送邮件至 chenwuzhu975@gmail.com\n我们会尽快回复你 ✨',
        confirmText: '复制邮箱',
        cancelText: '关闭',
        success: res => {
          if (!res.confirm) return
          Taro.setClipboardData({ data: 'chenwuzhu975@gmail.com' })
        }
      })
    } else {
      Taro.showToast({ title: '敬请期待新功能', icon: 'none' })
    }
  }

  const changePreference = async (key: keyof UserProfile['preferences'], value: boolean) => {
    const previous = user
    if (key === 'notifications' && value && hasChatMessageTemplate()) {
      const accepted = await requestChatMessageSubscription()
      if (!accepted) {
        Taro.showToast({ title: '未开启微信订阅通知', icon: 'none' })
      }
    }
    const next = {
      ...user,
      preferences: {
        ...user.preferences,
        [key]: value
      }
    }
    setUser(next)
    try {
      const saved = await updateProfile({ preferences: next.preferences } as Partial<UserProfile>)
      setUser(saved)
    } catch {
      setUser(previous)
      Taro.showToast({ title: '设置保存失败，请重试', icon: 'none' })
    }
  }

  if (needsLogin && !loading) {
    return (
      <PageShell className='profile-page'>
        <CustomNavBar title='我的' />
        <LoginCard onSubmit={handleLogin} />
      </PageShell>
    )
  }

  return (
    <PageShell className='profile-page'>
      <CustomNavBar title='我的' />
      <ProfileHero user={user} />
      <StatsRow
        stats={user.stats}
        onSelect={key => {
          if (key === 'posts') Taro.navigateTo({ url: '/pages/my-posts/index' })
          else if (key === 'following') Taro.navigateTo({ url: '/pages/contacts/index?tab=following' })
          else if (key === 'followers') Taro.navigateTo({ url: '/pages/contacts/index?tab=followers' })
        }}
      />
      <View className='profile-page__actions'>
        <View
          className='profile-page__primary'
          onClick={() => Taro.navigateTo({ url: '/pages/profile-edit/index' })}
        >
          编辑资料
        </View>
      </View>
      <PetShelf pets={pets} />
      <PreferenceList
        preferences={user.preferences}
        onChange={changePreference}
        onAction={handleAction}
        onLogout={handleLogout}
      />
    </PageShell>
  )
}
