import React, { useState, useEffect } from 'react'
import { View, Text, ScrollView } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { Button, Empty } from '@nutui/nutui-react-taro'
import { useThemeStyles } from '@/hooks/useTheme'
import { pageEnterpriseApp } from '@/api/developer/enterprise'
import type { App } from '@/types/developer'
import { STATUS_NAME, STATUS_COLOR } from '@/types/developer'
import './index.scss'

const EnterpriseIndex: React.FC = () => {
  const themeStyles = useThemeStyles()
  const [apps, setApps] = useState<App[]>([])
  const [loading, setLoading] = useState(true)
  const [stats, setStats] = useState({
    totalApps: 0,
    runningApps: 0,
    totalMembers: 0,
    pendingBills: 0,
  })

  // 加载数据
  const loadData = async () => {
    try {
      setLoading(true)
      const result = await pageEnterpriseApp({ current: 1, size: 10 })
      if (result) {
        setApps(result.list || [])
        setStats({
          totalApps: result.count || 0,
          runningApps: result.list?.filter((a) => a.status === 1).length || 0,
          totalMembers: 0,
          pendingBills: 0,
        })
      }
    } catch (error) {
      console.error('加载数据失败', error)
      Taro.showToast({ title: '加载失败', icon: 'none' })
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    loadData()
  }, [])

  // 跳转页面
  const navigateTo = (url: string) => {
    Taro.navigateTo({ url })
  }

  // 获取状态颜色
  const getStatusColor = (status?: number) => {
    return STATUS_COLOR[status || 0] || '#6b7280'
  }

  // 获取状态文本
  const getStatusText = (status?: number) => {
    return STATUS_NAME[status || 0] || '未知'
  }

  return (
    <View className="enterprise-page">
      <ScrollView scrollY className="enterprise-page__scroll">
        {/* 头部区域 */}
        <View className="enterprise-header">
          <View className="enterprise-header__glow" />
          <View className="enterprise-header__content">
            <View className="enterprise-header__title">
              <Text className="enterprise-header__titleText">🏢 企业控制台</Text>
            </View>
            <Text className="enterprise-header__subtitle">管理企业的应用、成员和资源</Text>
          </View>
        </View>

        {/* 统计卡片 */}
        <View className="stats-card">
          <View className="stats-card__row">
            <View className="stats-card__item">
              <Text className="stats-card__value">{stats.totalApps}</Text>
              <Text className="stats-card__label">企业应用</Text>
            </View>
            <View className="stats-card__divider" />
            <View className="stats-card__item">
              <Text className="stats-card__value">{stats.runningApps}</Text>
              <Text className="stats-card__label">运行中</Text>
            </View>
            <View className="stats-card__divider" />
            <View className="stats-card__item">
              <Text className="stats-card__value">{stats.totalMembers}</Text>
              <Text className="stats-card__label">成员</Text>
            </View>
            <View className="stats-card__divider" />
            <View className="stats-card__item">
              <Text className="stats-card__value">{stats.pendingBills}</Text>
              <Text className="stats-card__label">待支付</Text>
            </View>
          </View>
        </View>

        {/* 快捷操作 */}
        <View className="quick-actions">
          <View className="quick-actions__title">
            <Text className="quick-actions__titleText">快捷操作</Text>
          </View>
          <View className="quick-actions__grid">
            <View className="quick-actions__item" onClick={() => navigateTo('/enterprise/apps/index')}>
              <View className="quick-actions__icon quick-actions__icon--blue">
                <Text>📱</Text>
              </View>
              <Text className="quick-actions__text">企业应用</Text>
            </View>
            <View className="quick-actions__item" onClick={() => navigateTo('/enterprise/members/index')}>
              <View className="quick-actions__icon quick-actions__icon--green">
                <Text>👥</Text>
              </View>
              <Text className="quick-actions__text">成员管理</Text>
            </View>
            <View className="quick-actions__item" onClick={() => navigateTo('/enterprise/orders/index')}>
              <View className="quick-actions__icon quick-actions__icon--purple">
                <Text>📋</Text>
              </View>
              <Text className="quick-actions__text">订单账单</Text>
            </View>
            <View className="quick-actions__item" onClick={() => navigateTo('/enterprise/settings/index')}>
              <View className="quick-actions__icon quick-actions__icon--orange">
                <Text>⚙️</Text>
              </View>
              <Text className="quick-actions__text">企业设置</Text>
            </View>
          </View>
        </View>

        {/* 应用列表 */}
        <View className="app-list">
          <View className="app-list__header">
            <Text className="app-list__title">企业应用</Text>
            <View className="app-list__more" onClick={() => navigateTo('/enterprise/apps/index')}>
              <Text className="app-list__moreText">查看全部 ›</Text>
            </View>
          </View>

          {loading ? (
            <View className="app-list__loading">
              <Text>加载中...</Text>
            </View>
          ) : apps.length === 0 ? (
            <Empty description="暂无企业应用" />
          ) : (
            <View className="app-list__content">
              {apps.map((app) => (
                <View key={app.productId} className="app-item" onClick={() => navigateTo(`/enterprise/apps/${app.productId}`)}>
                  <View className="app-item__icon">
                    {app.icon ? (
                      <img src={app.icon} alt={app.productName} />
                    ) : (
                      <Text>📱</Text>
                    )}
                  </View>
                  <View className="app-item__info">
                    <Text className="app-item__name">{app.productName}</Text>
                    <Text className="app-item__type">{app.appType}</Text>
                  </View>
                  <View className="app-item__status" style={{ color: getStatusColor(app.status) }}>
                    <View className="app-item__statusDot" style={{ backgroundColor: getStatusColor(app.status) }} />
                    <Text className="app-item__statusText">{getStatusText(app.status)}</Text>
                  </View>
                </View>
              ))}
            </View>
          )}

          <View className="app-list__footer">
            <Button type="primary" block onClick={() => navigateTo('/enterprise/apps/purchase')}>
              购买新应用
            </Button>
          </View>
        </View>

        {/* 底部安全区域 */}
        <View className="safe-area-bottom" />
      </ScrollView>
    </View>
  )
}

export default EnterpriseIndex
