import React, { useEffect } from 'react'
import { View, ScrollView, Text } from '@tarojs/components'
import { useQuery } from '@tanstack/react-query'
import Taro from '@tarojs/taro'
import { RencaiTabBarLayout } from '@d8d/rencai-shared-ui/components/RencaiTabBarLayout'
import { Navbar } from '@d8d/mini-shared-ui-components/components/navbar'
import { talentPersonalInfoClient } from '../../api'
import { useRequireAuth } from '@d8d/rencai-auth-ui/hooks'
import UserInfoHeader from '../../components/UserInfoHeader'
import PersonalBasicInfo, { PersonalInfoResponse } from '../../components/PersonalBasicInfo'
import BankCardInfo from '../../components/BankCardInfo'
import { BankCardInfo as BankCardInfoType } from '../../components/BankCardItem'
import DocumentPhotos from '../../components/DocumentPhotos'
import { PhotoInfo } from '../../components/DocumentPhotoItem'

/**
 * 人才小程序个人信息页
 * TabBar页面 - 无返回按钮
 * 原型参考: docs/小程序原型/rencai.html (行483-628)
 */
const PersonalInfoPage: React.FC = () => {
  // 检查登录状态，未登录则重定向
  useRequireAuth()

  // 获取个人信息
  const { data: personalInfo, isLoading: personalInfoLoading, error: personalInfoError } = useQuery({
    queryKey: ['talentPersonalInfo'],
    queryFn: async () => {
      const response = await talentPersonalInfoClient.personal.info.$get()
      if (response.status !== 200) {
        throw new Error('获取个人信息失败')
      }
      return response.json() as Promise<PersonalInfoResponse>
    },
    refetchOnWindowFocus: false
  })

  // 获取银行卡信息
  const { data: bankCardsData, isLoading: bankCardsLoading, error: bankCardsError } = useQuery({
    queryKey: ['talentBankCards'],
    queryFn: async () => {
      const response = await talentPersonalInfoClient.personal['bank-cards'].$get()
      if (response.status !== 200) {
        throw new Error('获取银行卡信息失败')
      }
      const data = await response.json()
      return data.data as BankCardInfoType[]
    },
    refetchOnWindowFocus: false
  })

  // 获取证件照片
  const { data: photosData, isLoading: photosLoading, error: photosError } = useQuery({
    queryKey: ['talentPhotos'],
    queryFn: async () => {
      const response = await talentPersonalInfoClient.personal.photos.$get({
        query: { skip: 0, take: 100 }
      })
      if (response.status !== 200) {
        throw new Error('获取证件照片失败')
      }
      const data = await response.json()
      return data.data as PhotoInfo[]
    },
    refetchOnWindowFocus: false
  })

  // 页面加载时设置标题
  useEffect(() => {
    Taro.setNavigationBarTitle({
      title: '个人信息'
    })
  }, [])

  // 显示错误提示
  useEffect(() => {
    if (personalInfoError) {
      Taro.showToast({
        title: '获取个人信息失败',
        icon: 'none'
      })
    }
    if (bankCardsError) {
      Taro.showToast({
        title: '获取银行卡信息失败',
        icon: 'none'
      })
    }
    if (photosError) {
      Taro.showToast({
        title: '获取证件照片失败',
        icon: 'none'
      })
    }
  }, [personalInfoError, bankCardsError, photosError])

  return (
    <RencaiTabBarLayout activeKey="personal-info">
      <ScrollView
        className="h-[calc(100%-60px)] overflow-y-auto bg-gray-100"
        scrollY
      >
        {/* Navbar导航栏 - TabBar页面无返回按钮 */}
        <Navbar
          title="个人信息"
          leftIcon=""
          leftText=""
          onClickLeft={() => {}}
          backgroundColor="bg-white"
          border={true}
          fixed={true}
          placeholder={true}
        />

        {/* 顶部用户信息区域 - 直接在Navbar下方,无padding */}
        <UserInfoHeader
          personalInfo={personalInfo || null}
          loading={personalInfoLoading}
        />

        {/* 页面内容 */}
        <View className="px-4 py-3 pb-8">

          {/* 个人基本信息卡片 */}
          <PersonalBasicInfo
            personalInfo={personalInfo || null}
            loading={personalInfoLoading}
          />

          {/* 银行卡信息卡片 */}
          <BankCardInfo
            bankCards={bankCardsData || null}
            loading={bankCardsLoading}
          />

          {/* 证件照片卡片 */}
          <DocumentPhotos
            photos={photosData || null}
            loading={photosLoading}
          />
        </View>
      </ScrollView>
    </RencaiTabBarLayout>
  )
}

export default PersonalInfoPage
