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

const EnterpriseApps: React.FC = () => {
  const [activeTab, setActiveTab] = useState('all')
  const [apps, setApps] = useState<App[]>([])
  const [loading, setLoading] = useState(true)
  const [refreshing, setRefreshing] = useState(false)

  // 加载数据
  const loadData = async () => {
    try {
      setLoading(true)
      const result = await pageEnterpriseApp({ current: 1, size: 20 })
      if (result) {
        setApps(result.list || [])
      }
    } catch (error) {
      console.error('加载失败', error)
    } finally {
      setLoading(false)
    }
  }

  // 下拉刷新
  const onRefresh = async () => {
    setRefreshing(true)
    await loadData()
    setRefreshing(false)
  }

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

  // 筛选应用
  const filteredApps = activeTab === 'all'
    ? apps
    : apps.filter((app) => {
        if (activeTab === 'running') return app.status === 1
        if (activeTab === 'stopped') return app.status !== 1
        return true
      })

  // 跳转应用详情
  const handleAppClick = (id: number) => {
    Taro.navigateTo({ url: `/enterprise/apps/${id}` })
  }

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

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

  return (
    <View className="enterprise-apps-page">
      <PullToRefresh refreshing={refreshing} onRefresh={onRefresh}>
        {/* 标签页 */}
        <View className="tabs-wrapper">
          <Tabs value={activeTab} onChange={(v) => setActiveTab(v as string)}>
            <Tabs.TabPane title="全部" value="all" />
            <Tabs.TabPane title="运行中" value="running" />
            <Tabs.TabPane title="已停止" value="stopped" />
          </Tabs>
        </View>

        <ScrollView scrollY className="enterprise-apps-page__scroll">
          {/* 应用列表 */}
          <View className="app-list">
            {loading ? (
              <View className="app-list__loading">
                <Text>加载中...</Text>
              </View>
            ) : filteredApps.length === 0 ? (
              <Empty description="暂无应用" />
            ) : (
              <View className="app-list__content">
                {filteredApps.map((app) => (
                  <View key={app.productId} className="app-card" onClick={() => handleAppClick(app.productId!)}>
                    <View className="app-card__icon">
                      {app.icon ? (
                        <Image src={app.icon} mode="aspectFill" className="app-card__iconImg" />
                      ) : (
                        <Text className="app-card__iconDefault">📱</Text>
                      )}
                    </View>

                    <View className="app-card__info">
                      <View className="app-card__header">
                        <Text className="app-card__name">{app.productName}</Text>
                        <View className="app-card__status" style={{ color: getStatusColor(app.status) }}>
                          <View className="app-card__statusDot" style={{ backgroundColor: getStatusColor(app.status) }} />
                          <Text className="app-card__statusText">{getStatusText(app.status)}</Text>
                        </View>
                      </View>

                      <Text className="app-card__desc" numberOfLines={2}>
                        {app.description || '暂无描述'}
                      </Text>

                      <View className="app-card__meta">
                        <Text className="app-card__version">v{app.version || '1.0.0'}</Text>
                        <Text className="app-card__time">
                          {app.expirationTime ? `到期: ${app.expirationTime.split(' ')[0]}` : '永久有效'}
                        </Text>
                      </View>
                    </View>
                  </View>
                ))}
              </View>
            )}
          </View>

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

        {/* 底部按钮 */}
        <View className="purchase-btn-wrapper">
          <Button type="primary" block onClick={() => Taro.navigateTo({ url: '/enterprise/apps/purchase' })}>
            购买新应用
          </Button>
        </View>
      </PullToRefresh>
    </View>
  )
}

export default EnterpriseApps
