import { useEffect, useState } from 'react';
import Taro from '@tarojs/taro';
import { Button, Text, View } from '@tarojs/components';
import {
  exportPlatformAuditLogs,
  loadPlatformAuditAlerts,
  loadPlatformAuditLogs,
  loadPlatformAuditNotificationChannels,
  loadPlatformAuditNotificationEvents,
  loadPlatformDunningNotificationChannels,
  loadPlatformDunningNotificationEvents,
  loadPlatformInvoices,
  loadPlatformOverview,
  loadPlatformQuestionBankGrants,
  loadPlatformQuestionBanks,
  loadPlatformTenants,
  updatePlatformAuditAlertStatus,
  type PlatformAuditAlertItem,
  type PlatformAuditLogItem,
  type PlatformAuditNotificationChannelItem,
  type PlatformAuditNotificationEventItem,
  type PlatformDunningNotificationChannelItem,
  type PlatformDunningNotificationEventItem,
  type PlatformInvoiceItem,
  type PlatformOverview,
  type PlatformQuestionBankGrant,
  type PlatformQuestionBankItem,
  type PlatformTenantItem,
} from '@/services/platformAdmin';
import '../platform.css';

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

function downloadBase64File(filename: string, contentBase64: string, mimeType: string) {
  if (typeof document === 'undefined') return false;
  const link = document.createElement('a');
  link.href = `data:${mimeType};base64,${contentBase64}`;
  link.download = filename;
  document.body.appendChild(link);
  link.click();
  link.remove();
  return true;
}

export default function PlatformWorkbenchPage() {
  const [overview, setOverview] = useState<PlatformOverview | null>(null);
  const [tenants, setTenants] = useState<PlatformTenantItem[]>([]);
  const [invoices, setInvoices] = useState<PlatformInvoiceItem[]>([]);
  const [auditLogs, setAuditLogs] = useState<PlatformAuditLogItem[]>([]);
  const [auditAlerts, setAuditAlerts] = useState<PlatformAuditAlertItem[]>([]);
  const [auditNotificationChannels, setAuditNotificationChannels] = useState<PlatformAuditNotificationChannelItem[]>([]);
  const [auditNotificationEvents, setAuditNotificationEvents] = useState<PlatformAuditNotificationEventItem[]>([]);
  const [dunningNotificationChannels, setDunningNotificationChannels] = useState<PlatformDunningNotificationChannelItem[]>([]);
  const [dunningNotificationEvents, setDunningNotificationEvents] = useState<PlatformDunningNotificationEventItem[]>([]);
  const [banks, setBanks] = useState<PlatformQuestionBankItem[]>([]);
  const [grants, setGrants] = useState<PlatformQuestionBankGrant[]>([]);
  const [error, setError] = useState('');
  const [busy, setBusy] = useState('');

  useEffect(() => {
    Promise.all([
      loadPlatformOverview().catch(() => ({ item: null })),
      loadPlatformTenants({ limit: 6 }).catch(() => ({ items: [] })),
      loadPlatformInvoices({ limit: 6 }).catch(() => ({ items: [] })),
      loadPlatformQuestionBanks({ limit: 6 }).catch(() => ({ items: [] })),
      loadPlatformQuestionBankGrants({ limit: 6 }).catch(() => ({ items: [] })),
      loadPlatformAuditLogs({ limit: 6 }).catch(() => ({ items: [] })),
      loadPlatformAuditAlerts({ status: 'open', limit: 6 }).catch(() => ({ items: [] })),
      loadPlatformAuditNotificationChannels({ enabled: true, limit: 6 }).catch(() => ({ items: [] })),
      loadPlatformAuditNotificationEvents({ limit: 6 }).catch(() => ({ items: [] })),
      loadPlatformDunningNotificationChannels({ enabled: true, limit: 6 }).catch(() => ({ items: [] })),
      loadPlatformDunningNotificationEvents({ limit: 6 }).catch(() => ({ items: [] })),
    ]).then(([overviewPayload, tenantPayload, invoicePayload, bankPayload, grantPayload, auditPayload, alertPayload, channelPayload, eventPayload, dunningChannelPayload, dunningEventPayload]) => {
      setOverview(overviewPayload.item || null);
      setTenants(tenantPayload.items || []);
      setInvoices(invoicePayload.items || []);
      setBanks(bankPayload.items || []);
      setGrants(grantPayload.items || []);
      setAuditLogs(auditPayload.items || []);
      setAuditAlerts(alertPayload.items || []);
      setAuditNotificationChannels(channelPayload.items || []);
      setAuditNotificationEvents(eventPayload.items || []);
      setDunningNotificationChannels(dunningChannelPayload.items || []);
      setDunningNotificationEvents(dunningEventPayload.items || []);
    }).catch(nextError => setError(nextError instanceof Error ? nextError.message : '平台后台加载失败'));
  }, []);

  const modules = [
    { name: '租户管理', path: '/pages/platform-admin/tenants/index', meta: '租户状态、套餐、欠费和到期' },
    { name: '账务中心', path: '/pages/platform-admin/billing/index', meta: 'SaaS 套餐、发票、收款、用量' },
    { name: '公共题库', path: '/pages/platform-admin/question-banks/index', meta: '地区题库、授权、披露范围' },
    { name: '平台员工', path: '/pages/platform-admin/staff/index', meta: '员工账号、平台权限、禁用恢复' },
  ];

  async function exportAuditLogs() {
    setBusy('audit-export');
    setError('');
    try {
      const payload = await exportPlatformAuditLogs({ format: 'csv', limit: 1000 });
      const item = payload.item;
      if (item?.contentBase64 && item.filename) {
        const ok = downloadBase64File(item.filename, item.contentBase64, item.mimeType || 'text/csv');
        Taro.showToast({ title: ok ? '已导出' : '已生成', icon: 'success' });
      }
    } catch (nextError) {
      setError(nextError instanceof Error ? nextError.message : '审计导出失败');
    } finally {
      setBusy('');
    }
  }

  async function updateAuditAlert(alertId: string, status: 'acknowledged' | 'resolved') {
    setBusy(`alert-${alertId}-${status}`);
    setError('');
    try {
      await updatePlatformAuditAlertStatus({
        alertId,
        status,
        resolutionNote: status === 'resolved' ? '平台后台工作台处理' : undefined,
      });
      const payload = await loadPlatformAuditAlerts({ status: 'open', limit: 6 });
      setAuditAlerts(payload.items || []);
      Taro.showToast({ title: status === 'resolved' ? '已解决' : '已确认', icon: 'success' });
    } catch (nextError) {
      setError(nextError instanceof Error ? nextError.message : '告警状态更新失败');
    } finally {
      setBusy('');
    }
  }

  return (
    <View className='platform-page'>
      <View className='platform-shell'>
        <View className='platform-header'>
          <Text className='platform-kicker'>Platform Admin</Text>
          <Text className='platform-title'>SaaS 平台后台</Text>
          <Text className='platform-subtitle'>租户、套餐、服务费账单、平台公共题库授权和用量状态的统一工作台。</Text>
        </View>

        <View className='platform-grid'>
          <View className='platform-metric'><Text className='platform-metric-label'>活跃租户</Text><Text className='platform-metric-value'>{String(overview?.tenants?.active || 0)}/{String(overview?.tenants?.total || 0)}</Text></View>
          <View className='platform-metric'><Text className='platform-metric-label'>待收金额</Text><Text className='platform-metric-value'>{money(overview?.billing?.unpaidAmountCents)}</Text></View>
          <View className='platform-metric'><Text className='platform-metric-label'>即将到期</Text><Text className='platform-metric-value'>{String(overview?.subscriptions?.expiringSoon || 0)}</Text></View>
          <View className='platform-metric'><Text className='platform-metric-label'>题目用量</Text><Text className='platform-metric-value'>{String(overview?.usage?.questions || 0)}</Text></View>
        </View>

        <View className='platform-section'>
          <Text className='platform-section-title'>后台模块</Text>
          <View className='platform-list'>
            {modules.map(item => (
              <View className='platform-row' key={item.path} onClick={() => Taro.navigateTo({ url: item.path })}>
                <Text className='platform-row-main'>{item.name}</Text>
                <Text className='platform-row-meta'>{item.meta}</Text>
              </View>
            ))}
          </View>
        </View>

        <View className='platform-actions'>
          <Button className='platform-button primary' onClick={() => Taro.navigateTo({ url: '/pages/platform-admin/tenants/index' })}>租户管理</Button>
          <Button className='platform-button' onClick={() => Taro.navigateTo({ url: '/pages/platform-admin/billing/index' })}>账务中心</Button>
          <Button className='platform-button' onClick={() => Taro.navigateTo({ url: '/pages/platform-admin/question-banks/index' })}>公共题库</Button>
          <Button className='platform-button' onClick={() => Taro.navigateTo({ url: '/pages/platform-admin/staff/index' })}>平台员工</Button>
        </View>

        <View className='platform-section'>
          <Text className='platform-section-title'>近期租户</Text>
          <View className='platform-list'>
            {tenants.slice(0, 4).map(item => (
              <View className='platform-row' key={item.id}>
                <Text className='platform-row-main'>{item.brandName || item.name}</Text>
                <Text className='platform-row-meta'>{item.slug} · {item.status || '-'} · {item.planCode || '未订阅'} · 欠款 {money(item.openBalanceCents)}</Text>
              </View>
            ))}
          </View>
          {!tenants.length ? <View className='platform-empty'>暂无租户数据，或当前账号没有平台管理员权限。</View> : null}
        </View>

        <View className='platform-section'>
          <Text className='platform-section-title'>账单与题库授权</Text>
          <View className='platform-grid'>
            <View className='platform-metric'><Text className='platform-metric-label'>最近账单</Text><Text className='platform-metric-value'>{String(invoices.length)}</Text></View>
            <View className='platform-metric'><Text className='platform-metric-label'>公共题库</Text><Text className='platform-metric-value'>{String(banks.length)}</Text></View>
            <View className='platform-metric'><Text className='platform-metric-label'>授权规则</Text><Text className='platform-metric-value'>{String(grants.length)}</Text></View>
            <View className='platform-metric'><Text className='platform-metric-label'>逾期账单</Text><Text className='platform-metric-value'>{String(overview?.billing?.overdueInvoices || 0)}</Text></View>
          </View>
        </View>
        <View className='platform-section'>
          <Text className='platform-section-title'>最近平台审计</Text>
          <View className='platform-actions'>
            <Button className='platform-button' loading={busy === 'audit-export'} onClick={exportAuditLogs}>导出审计 CSV</Button>
          </View>
          <View className='platform-list'>
            {auditLogs.map(item => (
              <View className='platform-row' key={item.id}>
                <Text className='platform-row-main'>{item.action || '-'}</Text>
                <Text className='platform-row-meta'>{item.tenantName || item.tenantSlug || '平台'} · {item.actorName || item.actorUsername || 'system'} · {item.targetType || '-'} · {String(item.createdAt || '').slice(0, 19).replace('T', ' ')}</Text>
              </View>
            ))}
          </View>
          {!auditLogs.length ? <View className='platform-empty'>暂无审计记录。</View> : null}
        </View>
        <View className='platform-section'>
          <Text className='platform-section-title'>平台审计告警</Text>
          <View className='platform-list'>
            {auditAlerts.map(item => (
              <View className='platform-row' key={item.id}>
                <Text className='platform-row-main'>{item.title || item.action || '-'}</Text>
                <Text className='platform-row-meta'>{item.severity || '-'} · {item.tenantName || item.tenantSlug || '平台'} · {item.summary || item.targetType || '-'} · {String(item.auditCreatedAt || item.createdAt || '').slice(0, 19).replace('T', ' ')}</Text>
                <View className='platform-actions'>
                  <Button className='platform-button' size='mini' loading={busy === `alert-${item.id}-acknowledged`} onClick={() => updateAuditAlert(item.id, 'acknowledged')}>确认</Button>
                  <Button className='platform-button' size='mini' loading={busy === `alert-${item.id}-resolved`} onClick={() => updateAuditAlert(item.id, 'resolved')}>解决</Button>
                </View>
              </View>
            ))}
          </View>
          {!auditAlerts.length ? <View className='platform-empty'>暂无开放审计告警。</View> : null}
        </View>
        <View className='platform-section'>
          <Text className='platform-section-title'>告警外部通知</Text>
          <View className='platform-grid'>
            <View className='platform-metric'><Text className='platform-metric-label'>启用渠道</Text><Text className='platform-metric-value'>{String(auditNotificationChannels.length)}</Text></View>
            <View className='platform-metric'><Text className='platform-metric-label'>最近事件</Text><Text className='platform-metric-value'>{String(auditNotificationEvents.length)}</Text></View>
            <View className='platform-metric'><Text className='platform-metric-label'>失败事件</Text><Text className='platform-metric-value'>{String(auditNotificationEvents.filter(item => item.status === 'failed').length)}</Text></View>
            <View className='platform-metric'><Text className='platform-metric-label'>待重试</Text><Text className='platform-metric-value'>{String(auditNotificationEvents.filter(item => item.status === 'retrying').length)}</Text></View>
          </View>
          <View className='platform-list'>
            {auditNotificationChannels.map(item => (
              <View className='platform-row' key={item.id}>
                <Text className='platform-row-main'>{item.name || item.channelCode || '-'}</Text>
                <Text className='platform-row-meta'>{item.provider || '-'} · {item.minSeverity || '-'} · {item.webhook?.host || '-'} · {item.statusFilter?.join('/') || '-'}</Text>
              </View>
            ))}
            {auditNotificationEvents.map(item => (
              <View className='platform-row' key={item.id}>
                <Text className='platform-row-main'>{item.alertTitle || item.alertAction || '-'}</Text>
                <Text className='platform-row-meta'>{item.channelName || item.channelCode || '-'} · {item.status || '-'} · HTTP {String(item.lastHttpCode || '-')} · {item.tenantName || item.tenantSlug || '平台'}</Text>
              </View>
            ))}
          </View>
          {!auditNotificationChannels.length && !auditNotificationEvents.length ? <View className='platform-empty'>暂无外部通知渠道或发送事件。</View> : null}
        </View>
        <View className='platform-section'>
          <Text className='platform-section-title'>催缴外部通知</Text>
          <View className='platform-grid'>
            <View className='platform-metric'><Text className='platform-metric-label'>启用渠道</Text><Text className='platform-metric-value'>{String(dunningNotificationChannels.length)}</Text></View>
            <View className='platform-metric'><Text className='platform-metric-label'>最近事件</Text><Text className='platform-metric-value'>{String(dunningNotificationEvents.length)}</Text></View>
            <View className='platform-metric'><Text className='platform-metric-label'>失败事件</Text><Text className='platform-metric-value'>{String(dunningNotificationEvents.filter(item => item.status === 'failed').length)}</Text></View>
            <View className='platform-metric'><Text className='platform-metric-label'>待重试</Text><Text className='platform-metric-value'>{String(dunningNotificationEvents.filter(item => item.status === 'retrying').length)}</Text></View>
          </View>
          <View className='platform-list'>
            {dunningNotificationChannels.map(item => (
              <View className='platform-row' key={item.id}>
                <Text className='platform-row-main'>{item.name || item.channelCode || '-'}</Text>
                <Text className='platform-row-meta'>{item.provider || '-'} · level {String(item.minReminderLevel || '-')} · {item.webhook?.host || '-'} · {item.reminderTypes?.join('/') || '-'}</Text>
              </View>
            ))}
            {dunningNotificationEvents.map(item => (
              <View className='platform-row' key={item.id}>
                <Text className='platform-row-main'>{item.invoiceNo || item.invoiceId || '-'}</Text>
                <Text className='platform-row-meta'>{item.channelName || item.channelCode || '-'} · {item.status || '-'} · HTTP {String(item.lastHttpCode || '-')} · {item.tenantName || item.tenantSlug || '-'} · 欠款 {money(item.invoiceBalanceCents)}</Text>
              </View>
            ))}
          </View>
          {!dunningNotificationChannels.length && !dunningNotificationEvents.length ? <View className='platform-empty'>暂无催缴通知渠道或发送事件。</View> : null}
        </View>
        {error ? <Text className='platform-error'>{error}</Text> : null}
      </View>
    </View>
  );
}
