import { useEffect, useState } from 'react';
import { Button, Text, View } from '@tarojs/components';
import { loadTenantDashboard, type TenantDashboard } from '@/services/tenantAdmin';
import '../admin.css';

function money(cents: unknown) {
  return `¥${(Number(cents || 0) / 100).toFixed(2)}`;
}

export default function TenantDashboardPage() {
  const [range, setRange] = useState('30d');
  const [dashboard, setDashboard] = useState<TenantDashboard | null>(null);
  const [error, setError] = useState('');

  useEffect(() => {
    loadTenantDashboard(range)
      .then(payload => setDashboard(payload.item || null))
      .catch(nextError => setError(nextError instanceof Error ? nextError.message : '看板加载失败'));
  }, [range]);

  const cards = dashboard?.cards || {};
  const payment = dashboard?.paymentStats || {};

  return (
    <View className='admin-page'>
      <View className='admin-shell'>
        <View className='admin-header'>
          <Text className='admin-kicker'>Dashboard</Text>
          <Text className='admin-title'>数据看板</Text>
          <Text className='admin-subtitle'>收益、注册、学习、内容、反馈和激活码使用情况。</Text>
        </View>

        <View className='admin-tabs'>
          {['7d', '30d', '90d'].map(item => (
            <Button key={item} className={`admin-button ${item === range ? 'active' : ''}`} onClick={() => setRange(item)}>{item}</Button>
          ))}
        </View>

        <View className='admin-grid'>
          <View className='admin-metric'><Text className='admin-metric-label'>区间收入</Text><Text className='admin-metric-value'>{money(payment.revenueCentsInRange)}</Text></View>
          <View className='admin-metric'><Text className='admin-metric-label'>付费订单</Text><Text className='admin-metric-value'>{String(payment.paidOrdersInRange || 0)}</Text></View>
          <View className='admin-metric'><Text className='admin-metric-label'>新增学生</Text><Text className='admin-metric-value'>{String(cards.students?.newInRange || 0)}</Text></View>
          <View className='admin-metric'><Text className='admin-metric-label'>活跃学生</Text><Text className='admin-metric-value'>{String(cards.learning?.activeStudents || 0)}</Text></View>
          <View className='admin-metric'><Text className='admin-metric-label'>答题次数</Text><Text className='admin-metric-value'>{String(cards.learning?.answers || 0)}</Text></View>
          <View className='admin-metric'><Text className='admin-metric-label'>正确率</Text><Text className='admin-metric-value'>{`${Math.round(Number(cards.learning?.accuracy || 0) * 100)}%`}</Text></View>
        </View>

        <View className='admin-section'>
          <Text className='admin-section-title'>套餐销售</Text>
          <View className='admin-list'>
            {(dashboard?.planSales || []).slice(0, 8).map(item => (
              <View className='admin-row' key={String(item.planId || item.name)}>
                <Text className='admin-row-main'>{String(item.name || '未命名套餐')}</Text>
                <Text className='admin-row-meta'>{String(item.paidOrders || 0)} 单 · {money(item.revenueCents)}</Text>
              </View>
            ))}
          </View>
        </View>

        <View className='admin-section'>
          <Text className='admin-section-title'>运营动态</Text>
          <View className='admin-list'>
            {(dashboard?.recentActivities || []).slice(0, 8).map((item, index) => (
              <View className='admin-row' key={`${String(item.activityType)}-${index}`}>
                <Text className='admin-row-main'>{String(item.title || item.activityType)}</Text>
                <Text className='admin-row-meta'>{String(item.occurredAt || '')}</Text>
              </View>
            ))}
          </View>
          {!dashboard?.recentActivities?.length ? <View className='admin-empty'>暂无运营动态。</View> : null}
        </View>
        {error ? <Text className='admin-error'>{error}</Text> : null}
      </View>
    </View>
  );
}
