import { useEffect, useState } from 'react';
import Taro from '@tarojs/taro';
import { Button, Input, Text, View } from '@tarojs/components';
import {
  loadPlatformQuestionBankGrants,
  loadPlatformQuestionBanks,
  upsertPlatformQuestionBankGrant,
  type PlatformQuestionBankGrant,
  type PlatformQuestionBankItem,
} from '@/services/platformAdmin';
import '../platform.css';

function targetText(item: PlatformQuestionBankGrant) {
  if (item.grantScope === 'all_active_tenants') return '全部活跃租户';
  const planCount = item.allowedPlanCodes?.length || 0;
  const tenantCount = item.allowedTenantIds?.length || 0;
  if (planCount && tenantCount) return `${planCount} 个套餐 + ${tenantCount} 个租户`;
  if (planCount) return `${planCount} 个套餐`;
  if (tenantCount) return `${tenantCount} 个租户`;
  return '未配置目标';
}

export default function PlatformQuestionBanksPage() {
  const [keyword, setKeyword] = useState('');
  const [includeTenantBanks, setIncludeTenantBanks] = useState(false);
  const [banks, setBanks] = useState<PlatformQuestionBankItem[]>([]);
  const [grants, setGrants] = useState<PlatformQuestionBankGrant[]>([]);
  const [grantForm, setGrantForm] = useState({
    id: '',
    sourceQuestionBankId: '',
    grantScope: 'plans',
    allowedPlanCodes: '',
    allowedTenantIds: '',
    status: 'active',
    startsAt: '',
    expiresAt: '',
  });
  const [busy, setBusy] = useState('');
  const [error, setError] = useState('');

  function reload(nextKeyword = keyword, nextIncludeTenantBanks = includeTenantBanks) {
    Promise.all([
      loadPlatformQuestionBanks({ q: nextKeyword || undefined, includeTenantBanks: nextIncludeTenantBanks, limit: 100 }),
      loadPlatformQuestionBankGrants({ limit: 160 }),
    ]).then(([bankPayload, grantPayload]) => {
      setBanks(bankPayload.items || []);
      setGrants(grantPayload.items || []);
    }).catch(nextError => setError(nextError instanceof Error ? nextError.message : '公共题库加载失败'));
  }

  useEffect(() => {
    reload('', false);
  }, []);

  function toggleTenantBanks() {
    const nextValue = !includeTenantBanks;
    setIncludeTenantBanks(nextValue);
    reload(keyword, nextValue);
  }

  function updateGrantForm(key: keyof typeof grantForm, value: string) {
    setGrantForm(current => ({ ...current, [key]: value }));
  }

  function commaList(value: string) {
    return value.split(',').map(item => item.trim()).filter(Boolean);
  }

  async function confirm(title: string, content: string) {
    const result = await Taro.showModal({ title, content, confirmText: '确认', cancelText: '取消' });
    return result.confirm;
  }

  async function submitGrant() {
    setError('');
    if (!grantForm.sourceQuestionBankId) {
      setError('请先选择平台公共题库。');
      return;
    }
    const allowedPlanCodes = commaList(grantForm.allowedPlanCodes);
    const allowedTenantIds = commaList(grantForm.allowedTenantIds);
    if (grantForm.grantScope === 'plans' && !allowedPlanCodes.length) {
      setError('按套餐授权时必须填写套餐编码。');
      return;
    }
    if (grantForm.grantScope === 'tenants' && !allowedTenantIds.length) {
      setError('按租户授权时必须填写租户 ID。');
      return;
    }
    if (grantForm.grantScope === 'mixed' && !allowedPlanCodes.length && !allowedTenantIds.length) {
      setError('混合授权至少需要填写套餐编码或租户 ID。');
      return;
    }
    const ok = await confirm('更新题库授权', '确认更新公共题库披露规则？租户后台可见范围会受该规则影响。');
    if (!ok) return;
    setBusy('grant');
    try {
      await upsertPlatformQuestionBankGrant({
        id: grantForm.id || undefined,
        sourceQuestionBankId: grantForm.sourceQuestionBankId,
        grantScope: grantForm.grantScope,
        allowedPlanCodes,
        allowedTenantIds,
        status: grantForm.status || 'active',
        startsAt: grantForm.startsAt || undefined,
        expiresAt: grantForm.expiresAt || undefined,
      });
      Taro.showToast({ title: '已保存', icon: 'success' });
      reload(keyword, includeTenantBanks);
    } 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'>Question Banks</Text>
          <Text className='platform-title'>公共题库授权</Text>
          <Text className='platform-subtitle'>管理平台公共/地区题库披露范围，支撑租户按套餐或指定授权采纳题库快照。</Text>
        </View>

        <View className='platform-actions'>
          <Input className='platform-input' placeholder='题库名或地区' value={keyword} onInput={event => setKeyword(String(event.detail.value || ''))} />
          <Button className='platform-button primary' onClick={() => reload(keyword, includeTenantBanks)}>搜索</Button>
          <Button className={`platform-button ${includeTenantBanks ? 'active' : ''}`} onClick={toggleTenantBanks}>含租户库</Button>
        </View>

        <View className='platform-grid'>
          <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(banks.filter(item => item.sourceScope === 'platform').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(grants.filter(item => item.status === 'active').length)}</Text></View>
        </View>

        <View className='platform-section'>
          <Text className='platform-section-title'>授权编辑</Text>
          <View className='platform-form compact'>
            <View className='platform-field wide'><Text className='platform-field-label'>授权 ID</Text><Input className='platform-input' placeholder='留空则新增' value={grantForm.id} onInput={event => updateGrantForm('id', String(event.detail.value || ''))} /></View>
            <View className='platform-field wide'><Text className='platform-field-label'>题库 ID</Text><Input className='platform-input' placeholder='sourceQuestionBankId' value={grantForm.sourceQuestionBankId} onInput={event => updateGrantForm('sourceQuestionBankId', String(event.detail.value || ''))} /></View>
            <View className='platform-field'><Text className='platform-field-label'>范围</Text><Input className='platform-input' placeholder='plans / tenants / mixed / all_active_tenants' value={grantForm.grantScope} onInput={event => updateGrantForm('grantScope', String(event.detail.value || ''))} /></View>
            <View className='platform-field'><Text className='platform-field-label'>状态</Text><Input className='platform-input' placeholder='active / disabled' value={grantForm.status} onInput={event => updateGrantForm('status', String(event.detail.value || ''))} /></View>
            <View className='platform-field wide'><Text className='platform-field-label'>套餐编码</Text><Input className='platform-input' placeholder='starter_yearly,regional_yearly' value={grantForm.allowedPlanCodes} onInput={event => updateGrantForm('allowedPlanCodes', String(event.detail.value || ''))} /></View>
            <View className='platform-field wide'><Text className='platform-field-label'>租户 ID</Text><Input className='platform-input' placeholder='多个用英文逗号分隔' value={grantForm.allowedTenantIds} onInput={event => updateGrantForm('allowedTenantIds', String(event.detail.value || ''))} /></View>
            <View className='platform-field'><Text className='platform-field-label'>开始</Text><Input className='platform-input' placeholder='YYYY-MM-DD，可选' value={grantForm.startsAt} onInput={event => updateGrantForm('startsAt', String(event.detail.value || ''))} /></View>
            <View className='platform-field'><Text className='platform-field-label'>结束</Text><Input className='platform-input' placeholder='YYYY-MM-DD，可选' value={grantForm.expiresAt} onInput={event => updateGrantForm('expiresAt', String(event.detail.value || ''))} /></View>
          </View>
          <View className='platform-actions'>
            <Button className='platform-button primary' loading={busy === 'grant'} onClick={submitGrant}>保存授权</Button>
          </View>
        </View>

        <View className='platform-section'>
          <Text className='platform-section-title'>公共题库</Text>
          <View className='platform-list'>
            {banks.map(item => (
              <View className='platform-row' key={item.id}>
                <Text className='platform-row-main'>{item.name}</Text>
                <Text className='platform-row-meta'>{item.regionName || '通用'} · {item.sourceScope || 'tenant'} · {item.status || '-'} · {String(item.questionCount || 0)} 题</Text>
                <Text className='platform-row-meta'>来源租户 {item.tenantName || item.tenantSlug || item.tenantId || '-'}</Text>
                <View className='platform-row-actions'>
                  <Button className='platform-mini-button' onClick={() => setGrantForm(current => ({ ...current, sourceQuestionBankId: item.id }))}>选择题库</Button>
                </View>
              </View>
            ))}
          </View>
          {!banks.length ? <View className='platform-empty'>暂无公共题库，或筛选条件下没有结果。</View> : null}
        </View>

        <View className='platform-section'>
          <Text className='platform-section-title'>授权规则</Text>
          <View className='platform-list'>
            {grants.map(item => (
              <View className='platform-row' key={item.id}>
                <Text className='platform-row-main'>{item.sourceQuestionBankName || item.sourceQuestionBankId || item.id}</Text>
                <Text className='platform-row-meta'>{item.sourceRegionName || '通用'} · {item.grantScope || 'plans'} · {targetText(item)} · {item.status || '-'}</Text>
                <Text className='platform-row-meta'>有效期 {item.startsAt ? String(item.startsAt).slice(0, 10) : '-'} 至 {item.expiresAt ? String(item.expiresAt).slice(0, 10) : '长期'}</Text>
                <View className='platform-row-actions'>
                  <Button className='platform-mini-button' onClick={() => setGrantForm({
                    id: item.id,
                    sourceQuestionBankId: item.sourceQuestionBankId || '',
                    grantScope: item.grantScope || 'plans',
                    allowedPlanCodes: (item.allowedPlanCodes || []).join(','),
                    allowedTenantIds: (item.allowedTenantIds || []).join(','),
                    status: item.status || 'active',
                    startsAt: item.startsAt ? String(item.startsAt).slice(0, 10) : '',
                    expiresAt: item.expiresAt ? String(item.expiresAt).slice(0, 10) : '',
                  })}>编辑</Button>
                  <Button className='platform-mini-button danger' onClick={() => setGrantForm({
                    id: item.id,
                    sourceQuestionBankId: item.sourceQuestionBankId || '',
                    grantScope: item.grantScope || 'plans',
                    allowedPlanCodes: (item.allowedPlanCodes || []).join(','),
                    allowedTenantIds: (item.allowedTenantIds || []).join(','),
                    status: 'disabled',
                    startsAt: item.startsAt ? String(item.startsAt).slice(0, 10) : '',
                    expiresAt: item.expiresAt ? String(item.expiresAt).slice(0, 10) : '',
                  })}>准备禁用</Button>
                </View>
              </View>
            ))}
          </View>
          {!grants.length ? <View className='platform-empty'>暂无授权规则。后续编辑表单会调用 PUT /api/platform-admin/question-bank-grants。</View> : null}
        </View>
        {error ? <Text className='platform-error'>{error}</Text> : null}
      </View>
    </View>
  );
}
