import React from 'react'
import { View, Text, ScrollView } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { useQuery } from '@tanstack/react-query'
import { YongrenTabBarLayout } from '@d8d/yongren-shared-ui/components/YongrenTabBarLayout'
import { Navbar } from '@d8d/mini-shared-ui-components/components/navbar'
import { useAuth } from '@d8d/mini-enterprise-auth-ui/hooks'
import type { User } from '@d8d/mini-enterprise-auth-ui/hooks'
import { enterpriseCompanyClient } from '../../api/companyClient'

// 延期功能列表（因史诗012系统设置API延期）
const DEFERRED_FEATURES = ['账号信息', '安全设置', '消息通知']

const Settings: React.FC = () => {
  const { user } = useAuth()

  // 获取企业概览信息
  const { data: companyOverview, isLoading } = useQuery({
    queryKey: ['company-overview'],
    queryFn: async () => {
      const res = await enterpriseCompanyClient.overview.$get({} as any)
      if (!res.ok) {
        throw new Error('获取企业信息失败')
      }
      return await res.json()
    }
  })

  // 处理功能项点击
  const handleFeatureClick = (featureName: string) => {
    if (DEFERRED_FEATURES.includes(featureName)) {
      Taro.showModal({
        title: '功能开发中',
        content: `${featureName}功能正在开发中，预计下一版本上线。如需使用此功能，请在管理后台执行。`,
        showCancel: false,
        confirmText: '我知道了'
      })
      return
    }

    // 处理其他功能
    switch (featureName) {
      case '帮助中心':
        Taro.showToast({ title: '即将开放', icon: 'none' })
        break
      case '用户协议':
        Taro.showToast({ title: '即将开放', icon: 'none' })
        break
      case '隐私政策':
        Taro.showToast({ title: '即将开放', icon: 'none' })
        break
      case '退出登录':
        handleLogout()
        break
      default:
        break
    }
  }

  // 退出登录
  const handleLogout = () => {
    Taro.showModal({
      title: '退出登录',
      content: '确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          // 清除本地存储的认证信息
          Taro.removeStorageSync('enterpriseToken')
          Taro.removeStorageSync('enterpriseUser')

          // 跳转到登录页
          Taro.reLaunch({
            url: '/pages/login/index'
          })
        }
      }
    })
  }

  if (isLoading) {
    return (
      <YongrenTabBarLayout activeKey="settings">
        <ScrollView
          className="h-[calc(100%-60px)] overflow-y-auto px-4 pb-4 pt-0"
          scrollY
        >
          <Navbar
            title="企业设置"
            leftIcon=""
            leftText=""
            onClickLeft={() => {}}
            backgroundColor="bg-white"
            border={true}
            fixed={true}
            placeholder={true}
          />
          <View className="p-4">
            <Text>加载中...</Text>
          </View>
        </ScrollView>
      </YongrenTabBarLayout>
    )
  }

  const companyData: any = companyOverview || {}

  return (
    <YongrenTabBarLayout activeKey="settings">
      <ScrollView
        className="h-[calc(100%-60px)] overflow-y-auto px-4 pb-4 pt-0"
        scrollY
      >
        {/* 导航栏 */}
        <Navbar
          title="企业设置"
          leftIcon=""
          leftText=""
          onClickLeft={() => {}}
          backgroundColor="bg-white"
          border={true}
          fixed={true}
          placeholder={true}
        />

        {/* 企业信息区域 */}
        <View className="p-4 border-b border-gray-200">
          <View className="flex items-center mb-4">
            <View className="w-16 h-16 rounded-full bg-blue-100 flex items-center justify-center mr-3">
              <View className="i-heroicons-building-office-20-solid text-blue-500 text-2xl" />
            </View>
            <View className="flex flex-col">
              <Text className="font-semibold text-gray-800">
                {user?.company?.companyName || user?.nickname || user?.username || '企业名称'}
              </Text>
              <Text className="text-sm text-gray-500">企业账号</Text>
            </View>
          </View>

          {/* 统计卡片 */}
          <View className="grid grid-cols-3 gap-3 text-center">
            <View className="flex flex-col">
              <Text className="text-xl font-bold text-gray-800">
                {companyData?.['在职人员数'] || 0}
              </Text>
              <Text className="text-xs text-gray-500">在职人员</Text>
            </View>
            <View className="flex flex-col">
              <Text className="text-xl font-bold text-gray-800">
                {companyData?.['进行中订单数'] || 0}
              </Text>
              <Text className="text-xs text-gray-500">进行中订单</Text>
            </View>
            <View className="flex flex-col">
              <Text className="text-xl font-bold text-gray-800">
                {companyData?.['累计订单数'] || 0}
              </Text>
              <Text className="text-xs text-gray-500">累计订单</Text>
            </View>
          </View>
        </View>

        {/* 功能列表区域 */}
        <View className="p-4">
          {/* 第一组功能列表 */}
          <View className="mb-6">
            <View
              className="flex items-center justify-between p-3 rounded-lg hover:bg-gray-50"
              onClick={() => handleFeatureClick('账号信息')}
            >
              <View className="flex items-center">
                <View className="w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center mr-3">
                  <View className="i-heroicons-user-20-solid text-blue-500 text-lg" />
                </View>
                <View className="flex flex-col">
                  <Text className="text-gray-700">账号信息</Text>
                  <Text className="text-xs text-gray-400">（后期优化）</Text>
                </View>
              </View>
              <Text className="text-gray-400">›</Text>
            </View>

            <View
              className="flex items-center justify-between p-3 rounded-lg hover:bg-gray-50"
              onClick={() => handleFeatureClick('安全设置')}
            >
              <View className="flex items-center">
                <View className="w-10 h-10 rounded-full bg-green-100 flex items-center justify-center mr-3">
                  <View className="i-heroicons-shield-check-20-solid text-green-500 text-lg" />
                </View>
                <View className="flex flex-col">
                  <Text className="text-gray-700">安全设置</Text>
                  <Text className="text-xs text-gray-400">（后期优化）</Text>
                </View>
              </View>
              <Text className="text-gray-400">›</Text>
            </View>

            <View
              className="flex items-center justify-between p-3 rounded-lg hover:bg-gray-50"
              onClick={() => handleFeatureClick('消息通知')}
            >
              <View className="flex items-center">
                <View className="w-10 h-10 rounded-full bg-purple-100 flex items-center justify-center mr-3">
                  <View className="i-heroicons-bell-20-solid text-purple-500 text-lg" />
                </View>
                <View className="flex flex-col">
                  <Text className="text-gray-700">消息通知</Text>
                  <Text className="text-xs text-gray-400">（后期优化）</Text>
                </View>
              </View>
              <Text className="text-gray-400">›</Text>
            </View>
          </View>

          {/* 第二组功能列表 */}
          <View className="mb-6">
            <View
              className="flex items-center justify-between p-3 rounded-lg hover:bg-gray-50"
              onClick={() => handleFeatureClick('帮助中心')}
            >
              <View className="flex items-center">
                <View className="w-10 h-10 rounded-full bg-yellow-100 flex items-center justify-center mr-3">
                  <View className="i-heroicons-question-mark-circle-20-solid text-yellow-500 text-lg" />
                </View>
                <Text className="text-gray-700">帮助中心</Text>
              </View>
              <Text className="text-gray-400">›</Text>
            </View>

            <View
              className="flex items-center justify-between p-3 rounded-lg hover:bg-gray-50"
              onClick={() => handleFeatureClick('用户协议')}
            >
              <View className="flex items-center">
                <View className="w-10 h-10 rounded-full bg-indigo-100 flex items-center justify-center mr-3">
                  <View className="i-heroicons-document-text-20-solid text-indigo-500 text-lg" />
                </View>
                <Text className="text-gray-700">用户协议</Text>
              </View>
              <Text className="text-gray-400">›</Text>
            </View>

            <View
              className="flex items-center justify-between p-3 rounded-lg hover:bg-gray-50"
              onClick={() => handleFeatureClick('隐私政策')}
            >
              <View className="flex items-center">
                <View className="w-10 h-10 rounded-full bg-pink-100 flex items-center justify-center mr-3">
                  <View className="i-heroicons-lock-closed-20-solid text-pink-500 text-lg" />
                </View>
                <Text className="text-gray-700">隐私政策</Text>
              </View>
              <Text className="text-gray-400">›</Text>
            </View>
          </View>

          {/* 退出登录 */}
          <View>
            <View
              className="flex items-center justify-between p-3 rounded-lg hover:bg-gray-50"
              onClick={() => handleFeatureClick('退出登录')}
            >
              <View className="flex items-center">
                <View className="w-10 h-10 rounded-full bg-red-100 flex items-center justify-center mr-3">
                  <View className="i-heroicons-arrow-left-on-rectangle-20-solid text-red-500 text-lg" />
                </View>
                <Text className="text-gray-700">退出登录</Text>
              </View>
            </View>
          </View>
        </View>
      </ScrollView>
    </YongrenTabBarLayout>
  )
}

export default Settings
