import React, { useEffect } from 'react'
import { View, Text, ScrollView } from '@tarojs/components'
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 { useAuth, useRequireAuth } from '@d8d/rencai-auth-ui/hooks'
import { talentDashboardClient } from '../../api'
import type { InferResponseType } from 'hono'

/**
 * 人才小程序首页/个人主页
 * 原型参考: docs/小程序原型/rencai.html (行160-301)
 */

// 类型定义
type PersonalInfoResponse = InferResponseType<typeof talentDashboardClient.personal.info.$get, 200>

// 模拟打卡数据（P2延期功能）
interface ClockInData {
  status: '已打卡' | '未打卡'
  clockInTime?: string
  clockOutTime?: string
  displayTime?: string
  date?: string
}

// 格式化当前时间
const formatCurrentTime = (): string => {
  const now = new Date()
  return `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`
}

// 格式化当前日期
const formatCurrentDate = (): string => {
  const now = new Date()
  const weekdays = ['日', '一', '二', '三', '四', '五', '六']
  const year = now.getFullYear()
  const month = now.getMonth() + 1
  const date = now.getDate()
  const weekday = weekdays[now.getDay()]
  return `${year}年${month}月${date}日 星期${weekday}`
}

// 模拟通知数据
interface Notification {
  id: number
  iconClass: string
  iconColor: 'blue' | 'green' | 'yellow' | 'red'
  title: string
  subtitle: string
}

const Dashboard: React.FC = () => {
  const { user, refreshUser } = useAuth()
  const [personalInfo, setPersonalInfo] = React.useState<PersonalInfoResponse | null>(null)
  const [loading, setLoading] = React.useState(true)

  // 添加认证保护
  useRequireAuth()

  // 模拟打卡数据
  const clockInData: ClockInData = {
    status: '已打卡',
    clockInTime: '08:30',
    clockOutTime: '--:--',
    displayTime: formatCurrentTime(),
    date: formatCurrentDate()
  }

  // 模拟通知数据
  const notifications: Notification[] = [
    { id: 1, iconClass: 'i-heroicons-check-circle-20-solid', iconColor: 'green', title: '薪资发放通知', subtitle: '11月薪资已发放，请查收' },
    { id: 2, iconClass: 'i-heroicons-exclamation-circle-20-solid', iconColor: 'blue', title: '考勤异常提醒', subtitle: '11月20日考勤异常，请及时处理' },
    { id: 3, iconClass: 'i-heroicons-building-office-2-20-solid', iconColor: 'yellow', title: '企业通知', subtitle: '下周培训安排已更新' },
    { id: 4, iconClass: 'i-heroicons-wrench-screwdriver-20-solid', iconColor: 'red', title: '系统维护通知', subtitle: '系统将于12月1日维护' },
    { id: 5, iconClass: 'i-heroicons-document-text-20-solid', iconColor: 'blue', title: '福利政策更新', subtitle: '最新福利政策已发布' }
  ]

  // 加载个人信息
  useEffect(() => {
    loadPersonalInfo()
  }, [])

  const loadPersonalInfo = async () => {
    try {
      setLoading(true)
      const response = await talentDashboardClient.personal.info.$get()

      if (response.ok) {
        const data = await response.json()
        setPersonalInfo(data)
      } else {
        Taro.showToast({
          title: '加载个人信息失败',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('加载个人信息失败:', error)
      Taro.showToast({
        title: '加载个人信息失败',
        icon: 'none'
      })
    } finally {
      setLoading(false)
    }
  }

  // 下拉刷新
  const onRefresh = async () => {
    try {
      await Promise.all([
        refreshUser(),
        loadPersonalInfo()
      ])
      Taro.showToast({ title: '刷新成功', icon: 'success' })
    } catch (error) {
      Taro.showToast({ title: '刷新失败', icon: 'none' })
    }
  }

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

  // 快捷功能点击处理
  const handleQuickAction = (action: string) => {
    switch (action) {
      case 'personal-info':
        Taro.navigateTo({ url: '/pages/personal-info/index' })
        break
      case 'attendance':
        Taro.navigateTo({ url: '/pages/attendance/index' })
        break
      case 'employment':
        Taro.navigateTo({ url: '/pages/employment/index' })
        break
      case 'company':
        Taro.showToast({ title: '企业信息功能开发中', icon: 'none' })
        break
      default:
        break
    }
  }

  // 远程打卡处理（占位功能）
  const handleClockIn = () => {
    Taro.showToast({ title: '远程打卡功能开发中', icon: 'none' })
  }

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

        <View className="px-4 pb-20">
          {/* 个人概览卡片 - 蓝色渐变背景 */}
          <View
            className="rounded-2xl p-6 mb-4 shadow-md"
            style={{
              background: 'linear-gradient(135deg, #3b82f6 0%, #1e40af 100%)'
            }}
          >
            <View className="flex items-center mb-4">
              {/* 圆形头像显示(用户姓名首字) */}
              <View className="w-15 h-15 rounded-full bg-white/20 border-2 border-white flex items-center justify-center mr-3">
                <Text className="text-white text-xl font-semibold">
                  {(user?.personInfo?.name || user?.name || '人才用户').charAt(0)}
                </Text>
              </View>
              <View className="flex-1">
                <Text className="text-white text-xl font-semibold block mb-1">
                  {user?.personInfo?.name || user?.name || '人才用户'}
                </Text>
                <Text className="text-white/80 text-sm block">
                  {user?.personInfo?.disabilityType || '残疾类型未填写'}
                </Text>
              </View>
              {/* 右侧二维码按钮图标 */}
              <View
                className="w-10 h-10 rounded-full bg-white/20 flex items-center justify-center"
                onClick={() => Taro.showToast({ title: '二维码功能开发中', icon: 'none' })}
              >
                <View className="i-heroicons-qr-code-20-solid text-white text-lg" />
              </View>
            </View>

            {/* 3列统计数据 */}
            <View className="flex justify-between mt-4">
              <View className="flex flex-col items-center">
                <Text className="text-white text-2xl font-bold">28</Text>
                <Text className="text-white/80 text-xs">本月出勤</Text>
              </View>
              <View className="flex flex-col items-center">
                <Text className="text-white text-2xl font-bold">0</Text>
                <Text className="text-white/80 text-xs">异常记录</Text>
              </View>
              <View className="flex flex-col items-center">
                <Text className="text-white text-2xl font-bold">¥4,800</Text>
                <Text className="text-white/80 text-xs">本月薪资</Text>
              </View>
            </View>
          </View>

          {/* 打卡状态模块 */}
          <View className="bg-white rounded-2xl p-5 mb-4 shadow-sm text-center">
            {/* 打卡状态指示器 */}
            <View className="flex items-center justify-center mb-4">
              <View className="w-3 h-3 rounded-full bg-green-500 mr-2 animate-pulse" />
              <Text className="text-green-500 font-medium">已打卡</Text>
            </View>

            {/* 大号时间显示和日期 - 垂直布局 */}
            <View className="flex flex-col items-center mb-4">
              <Text className="text-2xl font-bold text-gray-800 mb-2">
                {clockInData.displayTime || '09:27'}
              </Text>
              <Text className="text-sm text-gray-600">
                {clockInData.date || '2023年11月25日 星期六'}
              </Text>
            </View>

            {/* 上班/下班卡片 */}
            <View className="flex justify-between mb-4">
              {/* 上班打卡 */}
              <View className="flex-1 flex flex-col items-center">
                <View className="w-12 h-12 rounded-full bg-blue-100 flex items-center justify-center mb-2">
                  <View className="i-heroicons-arrow-right-on-rectangle-20-solid text-blue-500 text-xl" />
                </View>
                <Text className="text-xs text-gray-600">上班打卡</Text>
                <Text className="text-sm font-semibold text-gray-800">{clockInData.clockInTime}</Text>
              </View>

              {/* 下班打卡 */}
              <View className="flex-1 flex flex-col items-center">
                <View className="w-12 h-12 rounded-full bg-gray-100 flex items-center justify-center mb-2">
                  <View className="i-heroicons-arrow-left-on-rectangle-20-solid text-gray-400 text-xl" />
                </View>
                <Text className="text-xs text-gray-600">下班打卡</Text>
                <Text className="text-sm font-semibold text-gray-400">{clockInData.clockOutTime}</Text>
              </View>
            </View>

            {/* 远程打卡按钮 */}
            <View
              className="bg-blue-500 text-white text-center py-3 rounded-lg font-medium flex items-center justify-center"
              onClick={handleClockIn}
            >
              <View className="i-heroicons-device-phone-mobile-20-solid text-lg mr-1" />
              <Text>小程序远程打卡</Text>
            </View>
          </View>

          {/* 快捷功能入口网格 */}
          <View className="grid grid-cols-4 gap-3 mb-4">
            <View
              className="bg-blue-50 rounded-xl p-3 flex flex-col items-center justify-center"
              onClick={() => handleQuickAction('personal-info')}
            >
              <View className="i-heroicons-user-20-solid text-blue-500 text-lg mb-1" />
              <Text className="text-xs text-gray-700">个人信息</Text>
            </View>

            <View
              className="bg-green-50 rounded-xl p-3 flex flex-col items-center justify-center"
              onClick={() => handleQuickAction('attendance')}
            >
              <View className="i-heroicons-document-text-20-solid text-green-500 text-lg mb-1" />
              <Text className="text-xs text-gray-700">考勤记录</Text>
            </View>

            <View
              className="bg-purple-50 rounded-xl p-3 flex flex-col items-center justify-center"
              onClick={() => handleQuickAction('employment')}
            >
              <View className="i-heroicons-chart-bar-20-solid text-purple-500 text-lg mb-1" />
              <Text className="text-xs text-gray-700">薪资查询</Text>
            </View>

            <View
              className="bg-yellow-50 rounded-xl p-3 flex flex-col items-center justify-center"
              onClick={() => handleQuickAction('company')}
            >
              <View className="i-heroicons-building-office-2-20-solid text-yellow-600 text-lg mb-1" />
              <Text className="text-xs text-gray-700">企业信息</Text>
            </View>
          </View>

          {/* 最新通知列表 */}
          <View className="bg-white rounded-2xl p-4 shadow-sm">
            <Text className="font-semibold text-gray-700 block mb-3">最新通知</Text>

            <View className="space-y-3">
              {notifications.map((notification) => {
                const iconBgClass = {
                  blue: 'bg-blue-100',
                  green: 'bg-green-100',
                  yellow: 'bg-yellow-100',
                  red: 'bg-red-100'
                }[notification.iconColor] || 'bg-gray-100'

                const iconColorClass = {
                  blue: 'text-blue-500',
                  green: 'text-green-500',
                  yellow: 'text-yellow-600',
                  red: 'text-red-500'
                }[notification.iconColor] || 'text-gray-500'

                return (
                  <View
                    key={notification.id}
                    className="flex items-start"
                  >
                    <View className={`w-8 h-8 rounded-full ${iconBgClass} flex items-center justify-center mr-3 mt-1 flex-shrink-0`}>
                      <View className={`${notification.iconClass} ${iconColorClass} text-sm`} />
                    </View>
                    <View className="flex-1">
                      <Text className="text-gray-800 text-sm font-medium block mb-1">{notification.title}</Text>
                      <Text className="text-gray-500 text-xs">{notification.subtitle}</Text>
                    </View>
                  </View>
                )
              })}
            </View>
          </View>
        </View>
      </ScrollView>
    </RencaiTabBarLayout>
  )
}

export default Dashboard
