import { useEffect, useState } from 'react';
import Taro from '@tarojs/taro';
import { Button, Input, Text, View } from '@tarojs/components';
import {
  createPlatformTenant,
  loadPlatformAuditLogs,
  loadPlatformPlans,
  loadPlatformTenantDetail,
  loadPlatformTenants,
  updatePlatformTenantStatus,
  upsertPlatformTenantBillingProfile,
  type PlatformAuditLogItem,
  type PlatformSaasPlan,
  type PlatformTenantDetail,
  type PlatformTenantItem,
} from '@/services/platformAdmin';
import '../platform.css';

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

function centsFromYuan(value: string) {
  const amount = Number(value || 0);
  if (!Number.isFinite(amount) || amount < 0) return 0;
  return Math.round(amount * 100);
}

function dateText(value?: string | null) {
  return value ? String(value).slice(0, 10) : '-';
}

function auditDetailsText(item: PlatformAuditLogItem) {
  try {
    const text = JSON.stringify(item.details || {});
    return text.length > 160 ? `${text.slice(0, 160)}...` : text;
  } catch {
    return '{}';
  }
}

const emptyBillingForm = {
  tenantId: '',
  billingName: '',
  taxId: '',
  contactName: '',
  contactPhone: '',
  contactEmail: '',
  billingAddress: '',
  invoiceTitle: '',
  invoiceType: 'none',
  bankName: '',
  bankAccountMasked: '',
};

export default function PlatformTenantsPage() {
  const [keyword, setKeyword] = useState('');
  const [status, setStatus] = useState('');
  const [plans, setPlans] = useState<PlatformSaasPlan[]>([]);
  const [tenants, setTenants] = useState<PlatformTenantItem[]>([]);
  const [selectedTenantId, setSelectedTenantId] = useState('');
  const [detail, setDetail] = useState<PlatformTenantDetail | null>(null);
  const [auditLogs, setAuditLogs] = useState<PlatformAuditLogItem[]>([]);
  const [tenantForm, setTenantForm] = useState({
    slug: '',
    name: '',
    legalName: '',
    brandName: '',
    primaryHost: '',
    planCode: '',
    billingStatus: 'trial',
    amountYuan: '',
  });
  const [statusForm, setStatusForm] = useState({
    tenantId: '',
    status: 'active',
    billingStatus: '',
    reason: '',
  });
  const [billingForm, setBillingForm] = useState(emptyBillingForm);
  const [busy, setBusy] = useState('');
  const [error, setError] = useState('');

  function reload(nextStatus = status, nextKeyword = keyword) {
    loadPlatformTenants({ q: nextKeyword || undefined, status: nextStatus || undefined, limit: 100 })
      .then(payload => setTenants(payload.items || []))
      .catch(nextError => setError(nextError instanceof Error ? nextError.message : '租户列表加载失败'));
  }

  function fillBillingForm(nextDetail: PlatformTenantDetail | null, fallbackTenantId = '') {
    const tenant = nextDetail?.tenant;
    setBillingForm({
      tenantId: tenant?.id || fallbackTenantId,
      billingName: tenant?.billingName || '',
      taxId: tenant?.taxId || '',
      contactName: tenant?.contactName || '',
      contactPhone: tenant?.contactPhone || '',
      contactEmail: tenant?.contactEmail || '',
      billingAddress: tenant?.billingAddress || '',
      invoiceTitle: tenant?.invoiceTitle || '',
      invoiceType: tenant?.invoiceType || 'none',
      bankName: tenant?.bankName || '',
      bankAccountMasked: tenant?.bankAccountMasked || '',
    });
  }

  async function loadDetail(tenantId: string) {
    if (!tenantId) return;
    setError('');
    setBusy('detail');
    try {
      const [detailPayload, auditPayload] = await Promise.all([
        loadPlatformTenantDetail(tenantId),
        loadPlatformAuditLogs({ tenantId, limit: 30 }).catch(() => ({ items: [] })),
      ]);
      const nextDetail = detailPayload.item || null;
      setDetail(nextDetail);
      fillBillingForm(nextDetail, tenantId);
      setAuditLogs(auditPayload.items || []);
    } catch (nextError) {
      setError(nextError instanceof Error ? nextError.message : '租户详情加载失败');
    } finally {
      setBusy('');
    }
  }

  useEffect(() => {
    reload('', '');
    loadPlatformPlans().then(payload => {
      const nextPlans = payload.items || [];
      setPlans(nextPlans);
      setTenantForm(current => ({ ...current, planCode: current.planCode || nextPlans[0]?.code || 'starter_yearly' }));
    }).catch(() => setPlans([]));
  }, []);

  function chooseStatus(nextStatus: string) {
    setStatus(nextStatus);
    reload(nextStatus, keyword);
  }

  function updateTenantForm(key: keyof typeof tenantForm, value: string) {
    setTenantForm(current => ({ ...current, [key]: value }));
  }

  function updateStatusForm(key: keyof typeof statusForm, value: string) {
    setStatusForm(current => ({ ...current, [key]: value }));
  }

  function updateBillingForm(key: keyof typeof billingForm, value: string) {
    setBillingForm(current => ({ ...current, [key]: value }));
  }

  function chooseTenant(item: PlatformTenantItem) {
    setSelectedTenantId(item.id);
    setStatusForm(current => ({
      ...current,
      tenantId: item.id,
      status: item.status || 'active',
      billingStatus: item.billingStatus || '',
    }));
    fillBillingForm(null, item.id);
    loadDetail(item.id);
  }

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

  async function submitCreateTenant() {
    setError('');
    const slug = tenantForm.slug.trim();
    const name = tenantForm.name.trim();
    if (!slug || !name) {
      setError('创建租户需要填写 slug 和租户名称。');
      return;
    }
    const ok = await confirm('创建租户', `确认创建租户 ${name}，并绑定套餐 ${tenantForm.planCode || 'starter_yearly'}？`);
    if (!ok) return;
    setBusy('create');
    try {
      const payload = await createPlatformTenant({
        slug,
        name,
        legalName: tenantForm.legalName.trim() || undefined,
        brandName: tenantForm.brandName.trim() || name,
        shortName: tenantForm.brandName.trim() || name,
        primaryHost: tenantForm.primaryHost.trim() || undefined,
        planCode: tenantForm.planCode || plans[0]?.code || 'starter_yearly',
        billingStatus: tenantForm.billingStatus || 'trial',
        amountCents: tenantForm.amountYuan ? centsFromYuan(tenantForm.amountYuan) : undefined,
      });
      Taro.showToast({ title: '已创建', icon: 'success' });
      setTenantForm(current => ({
        ...current,
        slug: '',
        name: '',
        legalName: '',
        brandName: '',
        primaryHost: '',
        amountYuan: '',
      }));
      reload(status, keyword);
      if (payload.item?.id) {
        setSelectedTenantId(payload.item.id);
        await loadDetail(payload.item.id);
      }
    } catch (nextError) {
      setError(nextError instanceof Error ? nextError.message : '创建租户失败');
    } finally {
      setBusy('');
    }
  }

  async function submitStatusChange() {
    setError('');
    if (!statusForm.tenantId) {
      setError('请先从租户列表选择要操作的租户。');
      return;
    }
    if (!statusForm.status && !statusForm.billingStatus) {
      setError('至少需要选择一个租户状态或账务状态。');
      return;
    }
    const ok = await confirm('变更租户状态', '该操作会影响租户后台和学生端访问，请确认已完成线下沟通或风控检查。');
    if (!ok) return;
    setBusy('status');
    try {
      await updatePlatformTenantStatus({
        tenantId: statusForm.tenantId,
        status: statusForm.status || undefined,
        billingStatus: statusForm.billingStatus || undefined,
        reason: statusForm.reason.trim() || undefined,
      });
      Taro.showToast({ title: '已更新', icon: 'success' });
      reload(status, keyword);
      await loadDetail(statusForm.tenantId);
    } catch (nextError) {
      setError(nextError instanceof Error ? nextError.message : '状态更新失败');
    } finally {
      setBusy('');
    }
  }

  async function submitBillingProfile() {
    setError('');
    if (!billingForm.tenantId) {
      setError('请先选择租户，再维护账务资料。');
      return;
    }
    const ok = await confirm('保存账务资料', '确认更新该租户的开票和收款联系资料？');
    if (!ok) return;
    setBusy('billing');
    try {
      await upsertPlatformTenantBillingProfile({
        tenantId: billingForm.tenantId,
        billingName: billingForm.billingName.trim() || undefined,
        taxId: billingForm.taxId.trim() || undefined,
        contactName: billingForm.contactName.trim() || undefined,
        contactPhone: billingForm.contactPhone.trim() || undefined,
        contactEmail: billingForm.contactEmail.trim() || undefined,
        billingAddress: billingForm.billingAddress.trim() || undefined,
        invoiceTitle: billingForm.invoiceTitle.trim() || undefined,
        invoiceType: billingForm.invoiceType.trim() || 'none',
        bankName: billingForm.bankName.trim() || undefined,
        bankAccountMasked: billingForm.bankAccountMasked.trim() || undefined,
      });
      Taro.showToast({ title: '已保存', icon: 'success' });
      await loadDetail(billingForm.tenantId);
    } catch (nextError) {
      setError(nextError instanceof Error ? nextError.message : '账务资料保存失败');
    } finally {
      setBusy('');
    }
  }

  const selectedTenant = detail?.tenant;

  return (
    <View className='platform-page'>
      <View className='platform-shell'>
        <View className='platform-header'>
          <Text className='platform-kicker'>Tenants</Text>
          <Text className='platform-title'>租户管理</Text>
          <Text className='platform-subtitle'>创建合作商租户、维护 SaaS 状态和账务资料，并追踪租户级平台审计证据。</Text>
        </View>

        <View className='platform-actions'>
          <Input className='platform-input' placeholder='租户名、slug、公司名' value={keyword} onInput={event => setKeyword(String(event.detail.value || ''))} />
          <Button className='platform-button primary' onClick={() => reload(status, keyword)}>搜索</Button>
        </View>

        <View className='platform-tabs'>
          {[
            { label: '全部', value: '' },
            { label: 'active', value: 'active' },
            { label: 'suspended', value: 'suspended' },
          ].map(item => (
            <Button key={item.label} className={`platform-button ${status === item.value ? 'active' : ''}`} onClick={() => chooseStatus(item.value)}>{item.label}</Button>
          ))}
        </View>

        <View className='platform-grid'>
          <View className='platform-metric'><Text className='platform-metric-label'>当前列表</Text><Text className='platform-metric-value'>{String(tenants.length)}</Text></View>
          <View className='platform-metric'><Text className='platform-metric-label'>欠费租户</Text><Text className='platform-metric-value'>{String(tenants.filter(item => Number(item.openBalanceCents || 0) > 0).length)}</Text></View>
          <View className='platform-metric'><Text className='platform-metric-label'>试用租户</Text><Text className='platform-metric-value'>{String(tenants.filter(item => item.billingStatus === 'trial').length)}</Text></View>
          <View className='platform-metric'><Text className='platform-metric-label'>已选租户</Text><Text className='platform-metric-value'>{selectedTenant ? selectedTenant.slug : '-'}</Text></View>
        </View>

        <View className='platform-section'>
          <Text className='platform-section-title'>创建租户</Text>
          <View className='platform-form'>
            <View className='platform-field'><Text className='platform-field-label'>slug</Text><Input className='platform-input' placeholder='tenant-slug' value={tenantForm.slug} onInput={event => updateTenantForm('slug', String(event.detail.value || ''))} /></View>
            <View className='platform-field'><Text className='platform-field-label'>租户名称</Text><Input className='platform-input' placeholder='合作商名称' value={tenantForm.name} onInput={event => updateTenantForm('name', String(event.detail.value || ''))} /></View>
            <View className='platform-field'><Text className='platform-field-label'>公司名称</Text><Input className='platform-input' placeholder='开票主体，可选' value={tenantForm.legalName} onInput={event => updateTenantForm('legalName', String(event.detail.value || ''))} /></View>
            <View className='platform-field'><Text className='platform-field-label'>品牌名称</Text><Input className='platform-input' placeholder='前台展示品牌，可选' value={tenantForm.brandName} onInput={event => updateTenantForm('brandName', String(event.detail.value || ''))} /></View>
            <View className='platform-field'><Text className='platform-field-label'>主域名</Text><Input className='platform-input' placeholder='tiku.example.com，可选' value={tenantForm.primaryHost} onInput={event => updateTenantForm('primaryHost', String(event.detail.value || ''))} /></View>
            <View className='platform-field'><Text className='platform-field-label'>套餐编码</Text><Input className='platform-input' placeholder={plans[0]?.code || 'starter_yearly'} value={tenantForm.planCode} onInput={event => updateTenantForm('planCode', String(event.detail.value || ''))} /></View>
            <View className='platform-field'><Text className='platform-field-label'>账务状态</Text><Input className='platform-input' placeholder='trial / active' value={tenantForm.billingStatus} onInput={event => updateTenantForm('billingStatus', String(event.detail.value || ''))} /></View>
            <View className='platform-field'><Text className='platform-field-label'>首期金额</Text><Input className='platform-input' placeholder='元，可留空用套餐默认价' type='digit' value={tenantForm.amountYuan} onInput={event => updateTenantForm('amountYuan', String(event.detail.value || ''))} /></View>
          </View>
          <View className='platform-actions'>
            <Button className='platform-button primary' loading={busy === 'create'} onClick={submitCreateTenant}>创建租户</Button>
          </View>
        </View>

        <View className='platform-section'>
          <Text className='platform-section-title'>租户列表</Text>
          <View className='platform-list'>
            {tenants.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.legalName || '未填公司'} · {item.status || '-'} · {item.billingStatus || '-'}</Text>
                <Text className='platform-row-meta'>套餐 {item.planCode || '未订阅'} · 订阅 {item.subscriptionStatus || '-'} · 到期 {dateText(item.subscriptionExpiresAt)}</Text>
                <Text className='platform-row-meta'>未收余额 {money(item.openBalanceCents)}</Text>
                <View className='platform-row-actions'>
                  <Button className='platform-mini-button' loading={busy === 'detail' && selectedTenantId === item.id} onClick={() => chooseTenant(item)}>详情</Button>
                  <Button className='platform-mini-button danger' onClick={() => {
                    setSelectedTenantId(item.id);
                    setStatusForm({ tenantId: item.id, status: 'suspended', billingStatus: item.billingStatus || '', reason: 'platform manual suspend' });
                    fillBillingForm(null, item.id);
                  }}>准备暂停</Button>
                </View>
              </View>
            ))}
          </View>
          {!tenants.length ? <View className='platform-empty'>暂无租户，或当前平台管理员权限未通过。</View> : null}
        </View>

        {selectedTenant ? (
          <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'>{selectedTenant.brandName || selectedTenant.name}</Text></View>
              <View className='platform-metric'><Text className='platform-metric-label'>租户状态</Text><Text className='platform-metric-value'>{selectedTenant.status || '-'}</Text></View>
              <View className='platform-metric'><Text className='platform-metric-label'>账务状态</Text><Text className='platform-metric-value'>{selectedTenant.billingStatus || '-'}</Text></View>
              <View className='platform-metric'><Text className='platform-metric-label'>主体</Text><Text className='platform-metric-value'>{selectedTenant.legalName || '-'}</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='tenantId' value={statusForm.tenantId} onInput={event => updateStatusForm('tenantId', String(event.detail.value || ''))} /></View>
                <View className='platform-field'><Text className='platform-field-label'>租户状态</Text><Input className='platform-input' placeholder='active / suspended' value={statusForm.status} onInput={event => updateStatusForm('status', String(event.detail.value || ''))} /></View>
                <View className='platform-field'><Text className='platform-field-label'>账务状态</Text><Input className='platform-input' placeholder='trial / active / past_due' value={statusForm.billingStatus} onInput={event => updateStatusForm('billingStatus', String(event.detail.value || ''))} /></View>
                <View className='platform-field wide'><Text className='platform-field-label'>原因</Text><Input className='platform-input' placeholder='内部审计备注' value={statusForm.reason} onInput={event => updateStatusForm('reason', String(event.detail.value || ''))} /></View>
              </View>
              <View className='platform-actions'>
                <Button className='platform-button primary' loading={busy === 'status'} onClick={submitStatusChange}>提交状态变更</Button>
              </View>
            </View>

            <View className='platform-section'>
              <Text className='platform-section-title'>账务资料</Text>
              <View className='platform-form'>
                <View className='platform-field wide'><Text className='platform-field-label'>租户 ID</Text><Input className='platform-input' value={billingForm.tenantId} onInput={event => updateBillingForm('tenantId', String(event.detail.value || ''))} /></View>
                <View className='platform-field'><Text className='platform-field-label'>开票名称</Text><Input className='platform-input' placeholder='公司或个人抬头' value={billingForm.billingName} onInput={event => updateBillingForm('billingName', String(event.detail.value || ''))} /></View>
                <View className='platform-field'><Text className='platform-field-label'>税号</Text><Input className='platform-input' placeholder='可选' value={billingForm.taxId} onInput={event => updateBillingForm('taxId', String(event.detail.value || ''))} /></View>
                <View className='platform-field'><Text className='platform-field-label'>联系人</Text><Input className='platform-input' value={billingForm.contactName} onInput={event => updateBillingForm('contactName', String(event.detail.value || ''))} /></View>
                <View className='platform-field'><Text className='platform-field-label'>联系电话</Text><Input className='platform-input' value={billingForm.contactPhone} onInput={event => updateBillingForm('contactPhone', String(event.detail.value || ''))} /></View>
                <View className='platform-field'><Text className='platform-field-label'>联系邮箱</Text><Input className='platform-input' value={billingForm.contactEmail} onInput={event => updateBillingForm('contactEmail', String(event.detail.value || ''))} /></View>
                <View className='platform-field'><Text className='platform-field-label'>发票类型</Text><Input className='platform-input' placeholder='none / normal_vat / special_vat' value={billingForm.invoiceType} onInput={event => updateBillingForm('invoiceType', String(event.detail.value || ''))} /></View>
                <View className='platform-field wide'><Text className='platform-field-label'>发票抬头</Text><Input className='platform-input' value={billingForm.invoiceTitle} onInput={event => updateBillingForm('invoiceTitle', String(event.detail.value || ''))} /></View>
                <View className='platform-field wide'><Text className='platform-field-label'>账单地址</Text><Input className='platform-input' value={billingForm.billingAddress} onInput={event => updateBillingForm('billingAddress', String(event.detail.value || ''))} /></View>
                <View className='platform-field'><Text className='platform-field-label'>开户行</Text><Input className='platform-input' value={billingForm.bankName} onInput={event => updateBillingForm('bankName', String(event.detail.value || ''))} /></View>
                <View className='platform-field'><Text className='platform-field-label'>银行账号掩码</Text><Input className='platform-input' placeholder='仅保存掩码' value={billingForm.bankAccountMasked} onInput={event => updateBillingForm('bankAccountMasked', String(event.detail.value || ''))} /></View>
              </View>
              <View className='platform-actions'>
                <Button className='platform-button primary' loading={busy === 'billing'} onClick={submitBillingProfile}>保存账务资料</Button>
                <Button className='platform-button' onClick={() => Taro.navigateTo({ url: '/pages/platform-admin/billing/index' })}>去账务中心</Button>
              </View>
            </View>

            <View className='platform-section'>
              <Text className='platform-section-title'>域名 / 订阅 / 账单 / 用量</Text>
              <View className='platform-list'>
                {(detail?.domains || []).map(item => (
                  <View className='platform-row' key={item.id}>
                    <Text className='platform-row-main'>{item.host || item.id}</Text>
                    <Text className='platform-row-meta'>{item.domainType || 'domain'} · {item.status || '-'} · {item.isPrimary ? 'primary' : 'secondary'} · 验证 {dateText(item.verifiedAt)}</Text>
                  </View>
                ))}
                {(detail?.subscriptions || []).slice(0, 3).map(item => (
                  <View className='platform-row' key={item.id}>
                    <Text className='platform-row-main'>{item.planCode || item.id}</Text>
                    <Text className='platform-row-meta'>{item.status || '-'} · {item.billingCycle || '-'} · {money(item.amountCents)} · {dateText(item.startsAt)} 至 {dateText(item.expiresAt)}</Text>
                  </View>
                ))}
                {(detail?.invoices || []).slice(0, 4).map(item => (
                  <View className='platform-row' key={item.id}>
                    <Text className='platform-row-main'>{item.invoiceNo || item.id}</Text>
                    <Text className='platform-row-meta'>{item.status || '-'} · 总额 {money(item.totalCents)} · 已收 {money(item.paidCents)} · 余额 {money(item.balanceCents)} · 到期 {dateText(item.dueDate)}</Text>
                  </View>
                ))}
                {(detail?.usage || []).slice(0, 6).map(item => (
                  <View className='platform-row' key={item.id}>
                    <Text className='platform-row-main'>{item.metricKey || 'metric'}</Text>
                    <Text className='platform-row-meta'>{String(item.metricValue || 0)} · {dateText(item.periodStart)} 至 {dateText(item.periodEnd)}</Text>
                  </View>
                ))}
              </View>
            </View>

            <View className='platform-section'>
              <Text className='platform-section-title'>最近平台审计</Text>
              <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'>{dateText(item.createdAt)} · {item.actorName || item.actorUsername || item.actorPhone || 'system'} · {item.targetType || '-'} · {item.targetId || '-'}</Text>
                    <Text className='platform-row-meta'>{auditDetailsText(item)}</Text>
                  </View>
                ))}
              </View>
              {!auditLogs.length ? <View className='platform-empty'>暂无平台审计记录。</View> : null}
            </View>
          </View>
        ) : (
          <View className='platform-empty'>从租户列表点击“详情”后，可以查看域名、订阅、账单、用量、账务资料和平台审计。</View>
        )}

        {error ? <Text className='platform-error'>{error}</Text> : null}
      </View>
    </View>
  );
}
