import { useEffect, useState } from 'react';
import Taro from '@tarojs/taro';
import { Button, Text, View } from '@tarojs/components';
import { getTenantContext } from '@/services/api';
import {
  loadTenantDashboard,
  loadTenantOverview,
  loadTenantPermissions,
  type TenantDashboard,
  type TenantOverview,
  type TenantPermissionsPayload,
} from '@/services/tenantAdmin';
import '../admin.css';

interface AdminModule {
  key: string;
  name: string;
  path: string;
  meta: string;
  permission?: string;
}

const MODULES: AdminModule[] = [
  { key: 'dashboard', name: '数据看板', path: '/pages/tenant-admin/dashboard/index', meta: '收益、注册、学习、内容', permission: 'dashboard:read' },
  { key: 'students', name: '学生运营', path: '/pages/tenant-admin/students/index', meta: '学生、班级、教师范围', permission: 'students:read' },
  { key: 'content', name: '题库内容', path: '/pages/tenant-admin/content/index', meta: '入口、导入、公共题库', permission: 'content:*' },
  { key: 'marketing', name: '营销中心', path: '/pages/tenant-admin/marketing/index', meta: '优惠券、激活码、分佣', permission: 'marketing:read' },
  { key: 'commerce', name: '财务运营', path: '/pages/tenant-admin/finance/index', meta: '退款、对账、差错、凭证', permission: 'tenant:reconciliation:read' },
  { key: 'settings', name: '租户设置', path: '/pages/tenant-admin/settings/index', meta: '品牌、域名、支付、登录、角色', permission: 'tenant:overview:read' },
];

function boolRecord(value: unknown) {
  return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {};
}

function explicitPermission(permissions: Record<string, unknown>, permission: string) {
  const parts = permission.split(':').filter(Boolean);
  const candidates = [permission];
  for (let index = parts.length - 1; index >= 1; index -= 1) {
    candidates.push(`${parts.slice(0, index).join(':')}:*`);
  }
  candidates.push('*');
  for (const key of candidates) {
    if (typeof permissions[key] === 'boolean') return permissions[key] as boolean;
  }
  return null;
}

function canOpenModule(payload: TenantPermissionsPayload, item: AdminModule) {
  const current = payload.current || {};
  const menuPermissions = boolRecord(current.menuPermissions);
  if (typeof menuPermissions[item.key] === 'boolean') return menuPermissions[item.key] as boolean;

  if (!item.permission) return true;
  const effectivePermissions = boolRecord(current.effectivePermissions);
  const explicit = explicitPermission(effectivePermissions, item.permission);
  if (explicit !== null) return explicit;

  const role = String(current.role || '');
  const defaults = payload.roleDefaults?.[role] || [];
  return defaults.some(permission => {
    if (permission === '*') return true;
    if (permission === item.permission) return true;
    if (permission.endsWith(':*')) return item.permission?.startsWith(permission.slice(0, -1));
    return false;
  });
}

export default function TenantWorkbenchPage() {
  const tenant = getTenantContext();
  const [dashboard, setDashboard] = useState<TenantDashboard | null>(null);
  const [overview, setOverview] = useState<TenantOverview | null>(null);
  const [permissions, setPermissions] = useState<TenantPermissionsPayload>({});

  useEffect(() => {
    loadTenantDashboard('30d').then(payload => setDashboard(payload.item || null)).catch(() => setDashboard(null));
    loadTenantOverview().then(payload => setOverview(payload.item || null)).catch(() => setOverview(null));
    loadTenantPermissions().then(payload => setPermissions(payload)).catch(() => setPermissions({}));
  }, []);

  const cards = dashboard?.cards || {};
  const payment = dashboard?.paymentStats || {};
  const modules = MODULES.filter(item => canOpenModule(permissions, item));

  return (
    <View className='admin-page'>
      <View className='admin-shell'>
        <View className='admin-header'>
          <Text className='admin-kicker'>{overview?.slug || 'Tenant Admin'}</Text>
          <Text className='admin-title'>{overview?.brandName || tenant?.branding.brandName || '租户运营后台'}</Text>
          <Text className='admin-subtitle'>品牌、题库、学生、订单、营销和数据看板的统一工作台。</Text>
        </View>

        <View className='admin-grid'>
          <View className='admin-metric'>
            <Text className='admin-metric-label'>30 日收入</Text>
            <Text className='admin-metric-value'>¥{((Number(payment.revenueCentsInRange || 0)) / 100).toFixed(2)}</Text>
          </View>
          <View className='admin-metric'>
            <Text className='admin-metric-label'>学生数</Text>
            <Text className='admin-metric-value'>{String(cards.students?.total || 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'>{String(cards.content?.questions || 0)}</Text>
          </View>
        </View>

        <View className='admin-section'>
          <Text className='admin-section-title'>后台模块</Text>
          <View className='admin-list'>
            {modules.map(item => (
              <View className='admin-row' key={item.path} onClick={() => Taro.navigateTo({ url: item.path })}>
                <Text className='admin-row-main'>{item.name}</Text>
                <Text className='admin-row-meta'>{item.meta}</Text>
              </View>
            ))}
          </View>
          {!modules.length ? <View className='admin-empty'>当前角色暂无可见后台模块。</View> : null}
        </View>

        <View className='admin-actions'>
          <Button className='admin-button primary' onClick={() => Taro.navigateTo({ url: '/pages/tenant-admin/content/index' })}>内容导入</Button>
          <Button className='admin-button' onClick={() => Taro.navigateTo({ url: '/pages/tenant-admin/marketing/index' })}>激活码</Button>
          <Button className='admin-button' onClick={() => Taro.navigateTo({ url: '/pages/tenant-admin/finance/index' })}>财务运营</Button>
          <Button className='admin-button' onClick={() => Taro.navigateTo({ url: '/pages/tenant-admin/settings/index' })}>品牌设置</Button>
        </View>
      </View>
    </View>
  );
}
