/**
 * 人才小程序就业信息页
 * 非TabBar页面 - 带返回按钮
 * 原型参考: docs/小程序原型/rencai.html (行630-768)
 *
 * API集成:
 * - GET /api/v1/rencai/employment/status - 当前就业状态
 * - GET /api/v1/rencai/employment/salary-records - 薪资记录
 * - GET /api/v1/rencai/employment/history - 就业历史
 */
import React from 'react'
import Taro from '@tarojs/taro'
import { View, ScrollView } from '@tarojs/components'
import { useQuery } from '@tanstack/react-query'
import { Navbar } from '@d8d/mini-shared-ui-components/components/navbar'
import { useRequireAuth } from '@d8d/rencai-auth-ui/hooks'

// 组件导入
import { CurrentEmploymentStatus } from '../../components/CurrentEmploymentStatus'
import { SalaryRecords } from '../../components/SalaryRecords'
import { EmploymentHistory } from '../../components/EmploymentHistory'

// API客户端导入
import { talentEmploymentClient } from '../../api'

// 类型导入
import {
  CurrentEmploymentStatus as CurrentEmploymentStatusType,
  SalaryRecord,
  EmploymentHistoryItem,
  WorkStatus
} from '../../types/employment'

const EmploymentPage: React.FC = () => {
  // 检查登录状态，未登录则重定向
  useRequireAuth()

  // 获取当前就业状态
  // 注意: 无就业记录时API返回null (200状态码),不是404错误
  const { data: currentStatus, isLoading: statusLoading, error: statusError } = useQuery({
    queryKey: ['employment-status'],
    queryFn: async () => {
      const res = await talentEmploymentClient.employment.status.$get()
      if (!res.ok) {
        throw new Error('获取就业状态失败')
      }
      const data = await res.json()
      // API返回null表示无就业记录
      if (!data) {
        return null
      }
      return {
        ...data,
        workStatus: data.workStatus as WorkStatus
      } as CurrentEmploymentStatusType
    }
  })

  // 获取薪资记录
  const { data: salaryRecordsData, isLoading: salaryLoading, error: salaryError } = useQuery({
    queryKey: ['salary-records'],
    queryFn: async () => {
      const res = await talentEmploymentClient.employment['salary-records'].$get({
        query: { take: 3 }
      })
      if (!res.ok) {
        throw new Error('获取薪资记录失败')
      }
      const data = await res.json()
      return (data.data || []) as SalaryRecord[]
    }
  })

  // 获取就业历史
  const { data: employmentHistoryData, isLoading: historyLoading, error: historyError } = useQuery({
    queryKey: ['employment-history'],
    queryFn: async () => {
      const res = await talentEmploymentClient.employment.history.$get({
        query: { take: 20 }
      })
      if (!res.ok) {
        throw new Error('获取就业历史失败')
      }
      const data = await res.json()
      return (data.data || []).map((item: any) => ({
        ...item,
        workStatus: item.workStatus as WorkStatus
      })) as EmploymentHistoryItem[]
    }
  })

  // 错误处理
  React.useEffect(() => {
    if (statusError) {
      Taro.showToast({
        title: statusError.message,
        icon: 'none'
      })
    }
  }, [statusError])

  React.useEffect(() => {
    if (salaryError) {
      Taro.showToast({
        title: salaryError.message,
        icon: 'none'
      })
    }
  }, [salaryError])

  React.useEffect(() => {
    if (historyError) {
      Taro.showToast({
        title: historyError.message,
        icon: 'none'
      })
    }
  }, [historyError])

  // 处理查看全部薪资记录
  const handleViewAllSalaryRecords = () => {
    Taro.showToast({
      title: '全部薪资记录功能开发中',
      icon: 'none'
    })
  }

  return (
    <View className="h-screen bg-gray-100 flex flex-col">
      {/* Navbar导航栏 - 非TabBar页面带返回按钮 */}
      <Navbar
        title="就业信息"
        leftIcon="i-heroicons-chevron-left-20-solid"
        leftText="返回"
        onClickLeft={() => Taro.navigateBack()}
        backgroundColor="bg-white"
        border={true}
        fixed={true}
        placeholder={true}
      />

      {/* 页面内容 */}
      <ScrollView
        scrollY
        className="flex-1"
        refresherEnabled={true}
        refresherTriggered={false}
      >
        {/* 当前就业状态卡片 */}
        <View className="px-4 pt-4">
          <CurrentEmploymentStatus status={currentStatus || null} loading={statusLoading} />
        </View>

        {/* 薪资记录卡片 */}
        <View className="px-4">
          <SalaryRecords
            records={salaryRecordsData || []}
            loading={salaryLoading}
            onViewAll={handleViewAllSalaryRecords}
            showViewAll={true}
          />
        </View>

        {/* 就业历史时间线 */}
        <View className="px-4 pb-4">
          <EmploymentHistory history={employmentHistoryData || []} loading={historyLoading} />
        </View>
      </ScrollView>
    </View>
  )
}

export default EmploymentPage
