// Distribution Center Page

const { useState, useEffect } = React;

function DistributionPage({ activeTab = 'home', setActiveTab, showGenerate = false, onCloseGenerate }) {
  const { navigate, showToast } = useApp();
  const [stats, setStats] = useState(null);
  const [lowerList, setLowerList] = useState([]);
  const [commissions, setCommissions] = useState([]);
  const [materials, setMaterials] = useState([]);
  const [showGenerateLocal, setShowGenerateLocal] = useState(false);
  const [showWithdraw, setShowWithdraw] = useState(false);
  const [withdrawAmount, setWithdrawAmount] = useState('');
  const [generateLink, setGenerateLink] = useState('');
  const [generateCode, setGenerateCode] = useState('');
  const actualShowGenerate = showGenerate || showGenerateLocal;
  const closeGenerate = () => {
    setShowGenerateLocal(false);
    if (onCloseGenerate) onCloseGenerate();
  };

  useEffect(() => {
    loadStats();
  }, []);

  const loadStats = async () => {
    const res = await API.get('/distribution/stats');
    if (res.success) setStats(res.data);
  };

  useEffect(() => {
    if (activeTab === 'team') {
      API.get('/distribution/lower').then(res => {
        if (res.success) setLowerList(res.data || []);
      });
    }
    if (activeTab === 'commission') {
      API.get('/distribution/commissions').then(res => {
        if (res.success) setCommissions(res.data || []);
      });
    }
    if (activeTab === 'material') {
      API.get('/distribution/materials').then(res => {
        if (res.success) setMaterials(res.data || []);
      });
    }
  }, [activeTab]);

  const handleGenerateLink = async () => {
    const res = await API.post('/distribution/generate-link');
    if (res.success) {
      setGenerateLink(res.data.link);
      setGenerateCode(res.data.invite_code);
    }
  };

  const handleWithdraw = async () => {
    if (!withdrawAmount || parseFloat(withdrawAmount) <= 0) {
      showToast('请输入提现金额');
      return;
    }
    const res = await API.post('/distribution/withdraw', { amount: parseFloat(withdrawAmount) });
    if (res.success) {
      showToast('提现申请已提交');
      setShowWithdraw(false);
      setWithdrawAmount('');
      loadStats();
    } else {
      showToast(res.message || '提现失败');
    }
  };

  const copyLink = () => {
    if (generateLink) {
      try {
        navigator.clipboard.writeText(generateLink);
        showToast('链接已复制');
      } catch(e) {
        showToast('复制成功');
      }
    }
  };

  const renderHome = () => (
    <div>
      {/* Stats Header */}
      <div style={{
        background: 'linear-gradient(135deg, #DC2626 0%, #EF4444 100%)',
        padding: '20px 16px',
        color: '#fff',
      }}>
        <div style={{ fontSize: 12, opacity: 0.9, marginBottom: 4 }}>累计收益</div>
        <div style={{ fontSize: 32, fontWeight: 700, marginBottom: 12 }}>
          ¥{stats?.total_commission?.toFixed(2) || '0.00'}
        </div>
        <div className="flex gap-16">
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 11, opacity: 0.85 }}>可提现</div>
            <div style={{ fontSize: 16, fontWeight: 600, marginTop: 2 }}>
              ¥{stats?.available_commission?.toFixed(2) || '0.00'}
            </div>
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 11, opacity: 0.85 }}>已提现</div>
            <div style={{ fontSize: 16, fontWeight: 600, marginTop: 2 }}>
              ¥{stats?.withdrawn_commission?.toFixed(2) || '0.00'}
            </div>
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 11, opacity: 0.85 }}>下级人数</div>
            <div style={{ fontSize: 16, fontWeight: 600, marginTop: 2 }}>
              {stats?.lower_count || 0}人
            </div>
          </div>
        </div>
        <div style={{ display: 'flex', gap: 8, marginTop: 14 }}>
          <button className="btn" style={{
            flex: 1, fontSize: 13, padding: '8px 12px',
            background: '#fff', color: '#DC2626',
          }} onClick={() => setShowWithdraw(true)}>
            提现
          </button>
          <button className="btn" style={{
            flex: 1, fontSize: 13, padding: '8px 12px',
            background: 'rgba(255,255,255,0.2)', color: '#fff',
          }} onClick={() => setShowGenerateLocal(true)}>
            生成推广链接
          </button>
        </div>
      </div>

      {/* Invite Code */}
      <div style={{ padding: 16 }}>
        <div className="card card-shadow">
          <div className="flex items-center gap-12">
            <div style={{
              width: 48, height: 48, borderRadius: 12,
              background: 'linear-gradient(135deg, #DC262622, #EF444422)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 24,
            }}>🎫</div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 12, color: 'var(--text-tertiary)' }}>我的邀请码</div>
              <div style={{ fontSize: 18, fontWeight: 700, color: '#DC2626' }}>
                {stats?.invite_code || 'JIU10001'}
              </div>
            </div>
            <button className="btn" style={{
              fontSize: 12, padding: '6px 12px',
              background: '#DC262622', color: '#DC2626',
            }} onClick={() => { handleGenerateLink(); setShowGenerateLocal(true); }}>
              推广
            </button>
          </div>
        </div>
      </div>

      {/* Quick Actions */}
      <div style={{ padding: '0 16px 16px' }}>
        <div className="card card-shadow">
          <div className="grid-4">
            <div style={{ textAlign: 'center', cursor: 'pointer' }} onClick={() => setActiveTab('material')}>
              <div style={{ fontSize: 24, marginBottom: 4 }}>🖼️</div>
              <div style={{ fontSize: 11 }}>推广物料</div>
            </div>
            <div style={{ textAlign: 'center', cursor: 'pointer' }} onClick={() => setActiveTab('team')}>
              <div style={{ fontSize: 24, marginBottom: 4 }}>👥</div>
              <div style={{ fontSize: 11 }}>下级管理</div>
            </div>
            <div style={{ textAlign: 'center', cursor: 'pointer' }} onClick={() => setActiveTab('commission')}>
              <div style={{ fontSize: 24, marginBottom: 4 }}>💰</div>
              <div style={{ fontSize: 11 }}>佣金明细</div>
            </div>
            <div style={{ textAlign: 'center', cursor: 'pointer' }} onClick={() => setActiveTab('commission')}>
              <div style={{ fontSize: 24, marginBottom: 4 }}>📊</div>
              <div style={{ fontSize: 11 }}>数据统计</div>
            </div>
          </div>
        </div>
      </div>

      {/* Rule Description */}
      <div style={{ padding: '0 16px 16px' }}>
        <div className="card card-shadow">
          <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 10 }}>分销规则</div>
          <div style={{ fontSize: 12, color: 'var(--text-secondary)', lineHeight: 1.8 }}>
            • 好友通过您的久聊号名片/推广链接注册<br/>
            • 好友购买靓号或会员，您可获得佣金<br/>
            • 三级分销体系，层层有收益<br/>
            • 好友越多，收益越多，上不封顶<br/>
            • 佣金可随时提现，快速到账
          </div>
        </div>
      </div>
    </div>
  );

  const renderMaterial = () => (
    <div style={{ padding: 16 }}>
      <div className="section-title">
        <span>推广物料</span>
      </div>
      {materials.map(mat => (
        <div key={mat.id} className="card card-shadow" style={{ marginBottom: 12 }}>
          <div className="flex items-center gap-12">
            <div style={{
              width: 56, height: 56, borderRadius: 10,
              background: 'linear-gradient(135deg, #DC262622, #EF444422)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 28, flexShrink: 0,
            }}>
              {mat.type === 'poster' ? '🖼️' : mat.type === 'long_image' ? '📜' : mat.type === 'infographic' ? '📊' : '📄'}
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 14, fontWeight: 500, marginBottom: 4 }}>{mat.title}</div>
              <div style={{ fontSize: 12, color: 'var(--text-tertiary)' }}>{mat.description}</div>
            </div>
            <button className="btn" style={{
              fontSize: 12, padding: '6px 12px',
              background: '#DC262622', color: '#DC2626',
            }} onClick={() => showToast('物料下载中...')}>
              下载
            </button>
          </div>
        </div>
      ))}
    </div>
  );

  const renderTeam = () => (
    <div style={{ padding: 16 }}>
      <div className="section-title">
        <span>下级成员</span>
        <span className="more">共 {lowerList.length} 人</span>
      </div>
      {lowerList.length === 0 ? (
        <div className="card card-shadow" style={{ textAlign: 'center', padding: 40, color: 'var(--text-tertiary)' }}>
          暂无下级成员，快去邀请吧
        </div>
      ) : (
        lowerList.map(item => (
          <div key={item.user_id} className="card card-shadow" style={{ marginBottom: 10 }}>
            <div className="flex items-center gap-12">
              <div className="avatar" style={{ background: '#DC2626' }}>
                {item.nickname?.charAt(0)}
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 14, fontWeight: 500 }}>{item.nickname}</div>
                <div style={{ fontSize: 11, color: 'var(--text-tertiary)' }}>
                  久聊号: {item.jiuLiaoId}
                </div>
              </div>
              <div style={{ textAlign: 'right' }}>
                <div style={{ fontSize: 14, fontWeight: 600, color: '#DC2626' }}>
                  ¥{item.total_commission?.toFixed(2) || '0.00'}
                </div>
                <div style={{ fontSize: 11, color: 'var(--text-tertiary)' }}>贡献收益</div>
              </div>
            </div>
          </div>
        ))
      )}
    </div>
  );

  const renderCommission = () => (
    <div style={{ padding: 16 }}>
      <div className="section-title">
        <span>佣金明细</span>
      </div>
      {commissions.length === 0 ? (
        <div className="card card-shadow" style={{ textAlign: 'center', padding: 40, color: 'var(--text-tertiary)' }}>
          暂无佣金记录
        </div>
      ) : (
        commissions.map(record => {
          const sourceMap = {
            member_purchase: '会员购买',
            premium_purchase: '靓号购买',
            article_reward: '文章打赏',
          };
          return (
            <div key={record.id} className="card card-shadow" style={{ marginBottom: 10 }}>
              <div className="flex items-center justify-between" style={{ marginBottom: 4 }}>
                <div style={{ fontSize: 13, fontWeight: 500 }}>
                  来自 {record.from_nickname}
                </div>
                <div style={{ fontSize: 15, fontWeight: 600, color: '#DC2626' }}>
                  +¥{parseFloat(record.amount).toFixed(2)}
                </div>
              </div>
              <div className="flex items-center justify-between">
                <div style={{ fontSize: 11, color: 'var(--text-tertiary)' }}>
                  {sourceMap[record.source] || record.source}
                </div>
                <div style={{ fontSize: 11, color: 'var(--text-tertiary)' }}>
                  {record.created_at?.slice(0, 16).replace('T', ' ')}
                </div>
              </div>
            </div>
          );
        })
      )}
    </div>
  );

  return (
    <PageWrapper>
      <AppHeader title="分销中心" subtitle="赚钱模式" showBack />
      {activeTab === 'home' && renderHome()}
      {activeTab === 'material' && renderMaterial()}
      {activeTab === 'team' && renderTeam()}
      {activeTab === 'commission' && renderCommission()}

      {/* Generate Link Sheet */}
      <BottomSheet show={actualShowGenerate} onClose={closeGenerate} title="推广链接">
        <div style={{ textAlign: 'center', marginBottom: 16 }}>
          <div style={{ fontSize: 48, marginBottom: 8 }}>🎫</div>
          <div style={{ fontSize: 14, color: 'var(--text-secondary)', marginBottom: 4 }}>我的邀请码</div>
          <div style={{ fontSize: 24, fontWeight: 700, color: '#DC2626', letterSpacing: 2 }}>
            {generateCode || stats?.invite_code || 'JIU10001'}
          </div>
        </div>
        <div style={{
          background: 'var(--bg-page)',
          borderRadius: 8,
          padding: 12,
          marginBottom: 12,
          fontSize: 12,
          color: 'var(--text-secondary)',
          wordBreak: 'break-all',
        }}>
          {generateLink || '点击下方按钮生成推广链接'}
        </div>
        <div className="flex gap-8">
          <button className="btn btn-outline btn-block" onClick={handleGenerateLink}>
            生成链接
          </button>
          <button className="btn btn-primary btn-block" style={{ background: '#DC2626' }} onClick={copyLink}>
            复制链接
          </button>
        </div>
      </BottomSheet>

      {/* Withdraw Sheet */}
      <BottomSheet show={showWithdraw} onClose={() => setShowWithdraw(false)} title="申请提现">
        <div style={{ textAlign: 'center', marginBottom: 12 }}>
          <div style={{ fontSize: 12, color: 'var(--text-tertiary)' }}>可提现金额</div>
          <div style={{ fontSize: 28, fontWeight: 700, color: '#DC2626' }}>
            ¥{stats?.available_commission?.toFixed(2) || '0.00'}
          </div>
        </div>
        <div style={{ marginBottom: 12 }}>
          <div style={{ fontSize: 12, color: 'var(--text-tertiary)', marginBottom: 6 }}>提现金额</div>
          <input
            type="number"
            className="input"
            style={{ fontSize: 20, fontWeight: 600, textAlign: 'center' }}
            placeholder="0.00"
            value={withdrawAmount}
            onChange={(e) => setWithdrawAmount(e.target.value)}
          />
        </div>
        <button className="btn btn-primary btn-block" style={{ background: '#DC2626' }} onClick={handleWithdraw}>
          确认提现
        </button>
      </BottomSheet>
    </PageWrapper>
  );
}

Object.assign(window, { DistributionPage });
