import React, { useState, useEffect } from 'react'
import { View, Text, ScrollView } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { useUser } from '@/hooks/useUser'
import { useScrollHeight } from '@/hooks/useScrollHeight'
import { listShopUserReferee } from '@/api/shop/shopUserReferee'
import type { ShopUserReferee } from '@/api/shop/shopUserReferee/model'
import EmptyState from '@/components/common/EmptyState'

definePageConfig({
  navigationBarTitleText: '邀请记录',
})

const InviteRecordPage: React.FC = () => {
  const { isLoggedIn } = useUser()
  const [records, setRecords] = useState<ShopUserReferee[]>([])
  const [loading, setLoading] = useState(true)
  const scrollHeight = useScrollHeight(44)


  useEffect(() => {
    if (!isLoggedIn) {
      Taro.navigateTo({ url: '/passport/login' })
      return
    }
    fetchRecords()
  }, [isLoggedIn])

  const fetchRecords = async () => {
    try {
      const data = await listShopUserReferee({})
      setRecords(data || [])
    } catch (e) {
      console.error('获取邀请记录失败:', e)
    } finally {
      setLoading(false)
    }
  }

  if (!isLoggedIn) {
    return null
  }

  return (
    <View className='min-h-screen bg-gray-50'>
      <ScrollView scrollY style={{ height: scrollHeight }}>
        {loading ? (
          <View className='flex items-center justify-center py-10'>
            <Text className='text-gray-400'>加载中...</Text>
          </View>
        ) : records.length === 0 ? (
          <EmptyState text='暂无邀请记录' />
        ) : (
          <View className='p-3'>
            {records.map((item) => (
              <View
                key={item.id}
                className='bg-white rounded-lg p-3 mb-2'
              >
                <View className='flex justify-between items-center mb-1'>
                  <Text className='text-sm font-medium text-gray-800'>
                    {item.nickname || '用户'}
                  </Text>
                  <View
                    className={`px-2 py-1 rounded-full text-xs ${
                      item.status === 1 ? 'bg-green-50 text-green-500' : 'bg-orange-50 text-orange-500'
                    }`}
                  >
                    <Text>{item.status === 1 ? '已注册' : '待注册'}</Text>
                  </View>
                </View>
                <View className='flex justify-between items-center'>
                  <Text className='text-xs text-gray-400'>
                    邀请时间：{item.createTime}
                  </Text>
                  {item.isMember && (
                    <Text className='text-xs text-orange-500'>会员</Text>
                  )}
                </View>
              </View>
            ))}
          </View>
        )}
      </ScrollView>
    </View>
  )
}

export default InviteRecordPage
