import { useEffect, useState } from 'react'
import Taro, { useRouter } from '@tarojs/taro'
import { Input, ScrollView, Text, View } from '@tarojs/components'
import { useSystemLayout } from '@/hooks/useSystemLayout'
import Icon from '@/components/ui/Icon'
import Avatar from '@/components/ui/Avatar'
import SegmentedTabs from '@/components/ui/SegmentedTabs'
import { discoverUsers, getFollowList, toggleFollow, type FollowListType } from '@/services/social.service'
import { ensureProfileReady } from '@/store/session.store'
import type { SocialUser } from '@/types/domain'
import './index.scss'

type TabKey = FollowListType | 'discover'

const tabs = [
  { key: 'friends', label: '汪友' },
  { key: 'following', label: '关注' },
  { key: 'followers', label: '粉丝' },
  { key: 'discover', label: '发现' }
] as const

const validTabs: TabKey[] = ['friends', 'following', 'followers', 'discover']

export default function ContactsPage() {
  const { statusBarHeight } = useSystemLayout()
  const router = useRouter()
  const initialTab = validTabs.includes(router.params.tab as TabKey) ? (router.params.tab as TabKey) : 'friends'
  const [tab, setTab] = useState<TabKey>(initialTab)
  const [keyword, setKeyword] = useState('')
  const [users, setUsers] = useState<SocialUser[]>([])
  const [loading, setLoading] = useState(false)

  const load = async (t: TabKey, kw = '') => {
    setLoading(true)
    try {
      if (t === 'discover') {
        setUsers(await discoverUsers(kw))
      } else {
        const res = await getFollowList(t)
        setUsers(res.list)
      }
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    load(tab, keyword)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [tab])

  useEffect(() => {
    if (tab !== 'discover') return undefined
    const timer = setTimeout(() => load('discover', keyword), 300)
    return () => clearTimeout(timer)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [keyword, tab])

  const onFollow = async (user: SocialUser) => {
    if (!(await ensureProfileReady())) return
    const next = !user.isFollowing
    const previous = user
    setUsers(cur => cur.map(u => (u.id === user.id ? { ...u, isFollowing: next, isFriend: next ? u.isFriend : false } : u)))
    try {
      const result = await toggleFollow(user.id, next)
      setUsers(cur => cur.map(u => (
        u.id === user.id
          ? { ...u, isFollowing: result.following, isFriend: result.mutual }
          : u
      )))
    } catch {
      // revert on failure
      setUsers(cur => cur.map(u => (u.id === user.id ? previous : u)))
      Taro.showToast({ title: '操作失败', icon: 'none' })
    }
  }

  const openProfile = (user: SocialUser) => {
    Taro.navigateTo({ url: `/pages/user-profile/index?userId=${user.id}` })
  }

  const openChat = (user: SocialUser) => {
    ensureProfileReady().then(ready => {
      if (!ready) return
      Taro.navigateTo({
        url: `/pages/chat/index?targetUserId=${user.id}&title=${encodeURIComponent(user.name)}`
      })
    })
  }

  const emptyText =
    tab === 'friends'
      ? '还没有汪友。互相关注即成为汪友'
      : tab === 'following'
        ? '还没有关注任何人，去「发现」看看吧'
        : tab === 'followers'
          ? '还没有粉丝'
          : '没有找到用户'

  return (
    <View className='contacts'>
      <View className='contacts__nav' style={{ paddingTop: `${statusBarHeight}px` }}>
        <View className='contacts__nav-row'>
          <View className='contacts__back' onClick={() => Taro.navigateBack()}>
            <Icon name='chev' size={22} className='contacts__back-icon' />
          </View>
          <Text className='contacts__title'>汪友</Text>
          <View className='contacts__nav-spacer' />
        </View>
      </View>

      <SegmentedTabs items={tabs as any} value={tab} onChange={(v: TabKey) => setTab(v)} />

      {tab === 'discover' ? (
        <View className='contacts__search'>
          <Icon name='search' size={16} className='contacts__search-icon' />
          <Input
            className='contacts__search-input'
            value={keyword}
            placeholder='搜索昵称'
            placeholderClass='contacts__search-ph'
            confirmType='search'
            onInput={e => setKeyword(e.detail.value)}
            onConfirm={() => load('discover', keyword)}
          />
        </View>
      ) : null}

      <ScrollView scrollY className='contacts__scroll' enhanced showScrollbar={false}>
        <View className='contacts__list'>
          {users.map(user => (
            <View key={user.id} className='contacts__item'>
              <View className='contacts__left' onClick={() => openProfile(user)}>
                <Avatar avatarKey={user.avatarKey} avatarUrl={user.avatarUrl} size='lg' label={user.name} />
                <View className='contacts__meta'>
                  <Text className='contacts__name'>{user.name}</Text>
                  <Text className='contacts__bio'>{user.bio || user.handle || '这位汪友很神秘'}</Text>
                </View>
              </View>
              <View className='contacts__actions'>
                {user.isFriend ? <Text className='contacts__friend-tag'>汪友</Text> : null}
                <View
                  className={`contacts__follow ${user.isFollowing ? 'contacts__follow--on' : ''}`}
                  onClick={() => onFollow(user)}
                >
                  {user.isFollowing ? '已关注' : '关注'}
                </View>
                {user.isFriend ? (
                  <View className='contacts__follow' onClick={() => openChat(user)}>
                    聊天
                  </View>
                ) : null}
              </View>
            </View>
          ))}
          {!loading && users.length === 0 ? <Text className='contacts__empty'>{emptyText}</Text> : null}
        </View>
      </ScrollView>
    </View>
  )
}
