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 { pageMyApp, pageJoinedApp } from '@/api/developer'
import type { App } from '@/types/developer'
import { APP_TYPE_NAME } from '@/types/developer'
import './index.scss'

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

  // 加载数据 - 同时查询创建的应用和参与的应用
  const loadData = async () => {
    try {
      setLoading(true)
      // 同时调用两个接口：创建的应用 + 参与的应用（通过邀请加入）
      const [myAppsResult, joinedAppsResult] = await Promise.all([
        pageMyApp({ current: 1, size: 10 }),
        pageJoinedApp({ current: 1, size: 10 }),
      ])

      // 合并两个列表，去重（根据 productId）
      const myApps = myAppsResult?.records || []
      const joinedApps = joinedAppsResult?.records || []

      // 使用 Map 去重，优先保留创建的应用（排在前面）
      const appMap = new Map<number, App>()

      // 先加入创建的应用
      myApps.forEach((app) => {
        if (app.productId) {
          appMap.set(app.productId, { ...app, isOwner: true })
        }
      })

      // 再加入参与的应用（如果已存在则跳过）
      joinedApps.forEach((app) => {
        if (app.productId && !appMap.has(app.productId)) {
          appMap.set(app.productId, { ...app, isOwner: false })
        }
      })

      const mergedApps = Array.from(appMap.values())

      setApps(mergedApps)
      setStats({
        totalApps: mergedApps.length,
        runningApps: mergedApps.filter((a) => a.status === 1).length,
        totalCalls: 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) => {
    const colors: Record<number, string> = {
      0: '#6b7280',
      1: '#10b981',
      2: '#f59e0b',
      3: '#ef4444',
      4: '#ef4444',
      5: '#ef4444',
    }
    return colors[status || 0] || '#6b7280'
  }

  // 获取状态文本
  const getStatusText = (status?: number) => {
    const texts: Record<number, string> = {
      0: '未开通',
      1: '运行中',
      2: '维护中',
      3: '已关闭',
      4: '已欠费',
      5: '违规停机',
    }
    return texts[status || 0] || '未知'
  }

  return (
    <View className="developer-page">
      <ScrollView scrollY className="developer-page__scroll">
        {/* 头部区域 */}
        <View className="developer-header" style={themeStyles.primaryBackground}>
          <View className="developer-header__glow" />
          <View className="developer-header__content">
            <View className="developer-header__title">
              <Text className="developer-header__titleText">🛠️ 开发者中心</Text>
            </View>
            <Text className="developer-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.totalCalls}</Text>
              <Text className="stats-card__label">API 调用</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('/developer/project/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('/developer/app/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('/developer/app/api-keys')}>
              <View className="quick-actions__icon quick-actions__icon--purple">
                <Text>🔑</Text>
              </View>
              <Text className="quick-actions__text">API Key</Text>
            </View>
            <View className="quick-actions__item" onClick={() => navigateTo('/developer/docs/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('/developer/app/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(`/developer/app/${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_TYPE_NAME[app.appType as keyof typeof APP_TYPE_NAME] || '未知'}</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('/developer/app/create')}>
              创建新应用
            </Button>
          </View>
        </View>

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

export default DeveloperIndex
