/* Painel do Proprietário / Super Administração do SaaS */

const AdminPanel = () => {
  const t = useTheme();
  const { showToast } = useToast();
  const isBloom = t.name === 'BLOOM';
  const { prompt, confirm } = useDialog();

  // Dados mockados/fictícios de alta fidelidade para o painel de faturamento e administração do SaaS
  const [tenants, setTenants] = React.useState([]);

  React.useEffect(() => {
    window.FluxoApi.get('/api/settings/tenants')
      .then(data => setTenants(data))
      .catch(err => console.error('Erro ao buscar assinantes:', err));
  }, []);

  // Cálculos do Painel de Faturamento
  const totalTenants = tenants.length;
  const activeTenants = tenants.filter(u => u.status === 'Ativo').length;
  const pendingTenants = tenants.filter(u => u.status === 'Pendente').length;
  
  // MRR (Monthly Recurring Revenue)
  const mrr = tenants.filter(u => u.status === 'Ativo').reduce((acc, curr) => acc + curr.price, 0);
  // ARR (Annual Recurring Revenue)
  const arr = mrr * 12;
  // Média de consumo de tokens por usuário
  const totalTokens = tenants.reduce((acc, curr) => acc + curr.tokensUsed, 0);
  
  const handleEditPlan = async (id, currentPlan) => {
    const nextPlan = await prompt(`Digite o novo plano para esta empresa (Starter, Pro, Enterprise):`, currentPlan);
    if (!nextPlan) return;
    
    const validPlans = {
      'Starter': 147,
      'Pro': 297,
      'Enterprise': 799
    };
    
    if (!validPlans[nextPlan]) {
      showToast('Plano inválido. Use Starter, Pro ou Enterprise.', 'error');
      return;
    }
    
    try {
      const updated = await window.FluxoApi.patch(`/api/settings/tenants/${id}`, { plan: nextPlan, price: validPlans[nextPlan] });
      setTenants(prev => prev.map(t => t.id === id ? updated : t));
      showToast('Plano da assinatura alterado com sucesso!', 'success');
    } catch (e) {
      showToast('Erro ao atualizar plano no servidor.', 'error');
    }
  };

  const handleToggleStatus = async (id, currentStatus) => {
    const action = currentStatus === 'Ativo' ? 'Suspender' : 'Ativar';
    if (await confirm(`Deseja realmente ${action.toLowerCase()} o acesso deste cliente comercial?`)) {
      const nextStatus = currentStatus === 'Ativo' ? 'Pendente' : 'Ativo';
      try {
        const updated = await window.FluxoApi.patch(`/api/settings/tenants/${id}`, { status: nextStatus });
        setTenants(prev => prev.map(t => t.id === id ? updated : t));
        showToast(`Acesso do cliente alterado para ${nextStatus}!`, 'success');
      } catch (e) {
        showToast('Erro ao atualizar status no servidor.', 'error');
      }
    }
  };

  return (
    <div style={{ padding: '24px 28px 40px', maxWidth: 1320, margin: '0 auto' }}>
      {/* Header */}
      <div style={{ marginBottom: 24, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <div>
          <div style={{ fontSize: 11, color: t.textMuted, letterSpacing: '0.14em', fontFamily: t.fontMono, marginBottom: 4 }}>
            PROPRIETÁRIO DO SISTEMA (OWNER)
          </div>
          <h1 style={{ margin: 0, fontFamily: t.fontDisplay, fontSize: 32, fontWeight: 800, letterSpacing: '-0.03em', color: t.text }}>
            Super Administração do SaaS
          </h1>
        </div>
        <Btn variant="primary" icon={<Icons.Plus size={14}/>} onClick={async () => {
          const name = await prompt('Nome da Empresa/Negócio:');
          if (name) {
            const owner = await prompt('Nome do Administrador Responsável:') || 'Responsável';
            const email = await prompt('E-mail de Cadastro:') || 'contato@empresa.com';
            const plan = await prompt('Plano Inicial (Starter, Pro, Enterprise):') || 'Pro';
            
            const validPlans = { 'Starter': 147, 'Pro': 297, 'Enterprise': 799 };
            const price = validPlans[plan] || 297;
            
            try {
              const newTenant = await window.FluxoApi.post('/api/settings/tenants', {
                name,
                owner,
                email,
                plan,
                price
              });
              setTenants(prev => [newTenant, ...prev]);
              showToast('Nova empresa parceira cadastrada com sucesso!', 'success');
            } catch (e) {
              showToast('Erro ao cadastrar empresa no servidor.', 'error');
            }
          }
        }}>Cadastrar Empresa</Btn>
      </div>

      {/* KPI Row */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(240px, 1fr))', gap: 18, marginBottom: 24 }}>
        {[
          { label: 'Faturamento Recorrente Mensal (MRR)', val: `R$ ${mrr.toLocaleString('pt-BR')}`, desc: `Previsão fixa baseada nos ativos`, icon: 'Money', color: t.green },
          { label: 'Faturamento Anual Previsto (ARR)', val: `R$ ${arr.toLocaleString('pt-BR')}`, desc: `Previsibilidade a longo prazo`, icon: 'Lightning', color: t.primary },
          { label: 'Empresas Assinantes (Tenants)', val: `${totalTenants} Empresas`, desc: `${activeTenants} ativas · ${pendingTenants} suspensas/pendentes`, icon: 'Users', color: t.pink },
          { label: 'Consumo Global de IA', val: `${(totalTokens / 1000).toFixed(1)}K tokens`, desc: `Uso total acumulado no mês`, icon: 'Sparkles', color: t.orange }
        ].map((k, i) => {
          const I = Icons[k.icon];
          return (
            <Card key={i} style={{ padding: 20, display: 'flex', flexDirection: 'column', gap: 10 }}>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <span style={{ fontSize: 11, fontWeight: 700, color: t.textMuted, letterSpacing: '0.04em', fontFamily: t.fontMono }}>{k.label}</span>
                <div style={{ width: 28, height: 28, borderRadius: '50%', background: `${k.color}15`, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <I size={14} stroke={k.color}/>
                </div>
              </div>
              <div style={{ fontSize: 26, fontWeight: 800, color: t.text, fontFamily: t.fontDisplay, letterSpacing: '-0.02em' }}>{k.val}</div>
              <div style={{ fontSize: 12, color: t.textMuted, marginTop: 2 }}>{k.desc}</div>
            </Card>
          );
        })}
      </div>

      {/* Plan Distribution */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18, marginBottom: 24 }}>
        <Card style={{ padding: 22 }}>
          <h3 style={{ margin: '0 0 16px', fontFamily: t.fontDisplay, fontSize: 17, fontWeight: 700, color: t.text }}>Distribuição de Assinaturas por Plano</h3>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            {[
              { name: 'Enterprise', price: 799, count: tenants.filter(t => t.plan === 'Enterprise').length, color: t.primary },
              { name: 'Pro', price: 297, count: tenants.filter(t => t.plan === 'Pro').length, color: t.green },
              { name: 'Starter', price: 147, count: tenants.filter(t => t.plan === 'Starter').length, color: t.orange }
            ].map((p, idx) => {
              const pct = totalTenants > 0 ? (p.count / totalTenants) * 100 : 0;
              return (
                <div key={idx}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6, fontSize: 13, fontWeight: 600, color: t.text }}>
                    <span>Plano {p.name} (R$ {p.price}/mês)</span>
                    <span style={{ fontFamily: t.fontMono }}>{p.count} assinantes ({pct.toFixed(0)}%)</span>
                  </div>
                  <div style={{ width: '100%', height: 8, background: isBloom ? t.border : 'rgba(255,255,255,0.05)', borderRadius: 4, overflow: 'hidden' }}>
                    <div style={{ width: `${pct}%`, height: '100%', background: p.color, borderRadius: 4 }} />
                  </div>
                </div>
              );
            })}
          </div>
        </Card>

        <Card style={{ padding: 22 }}>
          <h3 style={{ margin: '0 0 16px', fontFamily: t.fontDisplay, fontSize: 17, fontWeight: 700, color: t.text }}>Previsibilidade de Faturamento Recorrente</h3>
          <div style={{ fontSize: 13, color: t.textMuted, lineHeight: 1.5, marginBottom: 14 }}>
            Seu faturamento mensal fixo (MRR) de <strong>R$ {mrr.toLocaleString('pt-BR')}</strong> projeta uma receita bruta garantida a nível anual de **R$ {arr.toLocaleString('pt-BR')}** com os planos ativos na fase comercial.
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <div style={{ padding: 14, borderRadius: t.radiusMd, background: isBloom ? t.greenSoft : 'rgba(16,185,129,0.06)', border: `1px solid ${t.green}30` }}>
              <div style={{ fontSize: 10, color: t.textMuted, fontFamily: t.fontMono }}>Faturamento Médio por Cliente (ARPU)</div>
              <div style={{ fontSize: 20, fontWeight: 700, color: t.text, marginTop: 4, fontFamily: t.fontDisplay }}>R$ {(mrr / (totalTenants || 1)).toFixed(2)}</div>
            </div>
            <div style={{ padding: 14, borderRadius: t.radiusMd, background: isBloom ? t.primarySoft : 'rgba(91,141,239,0.06)', border: `1px solid ${t.primary}30` }}>
              <div style={{ fontSize: 10, color: t.textMuted, fontFamily: t.fontMono }}>Custo de IA Global Estimado</div>
              <div style={{ fontSize: 20, fontWeight: 700, color: t.text, marginTop: 4, fontFamily: t.fontDisplay }}>R$ {((totalTokens / 1000) * 0.05).toFixed(2)}</div>
            </div>
          </div>
        </Card>
      </div>

      {/* Tenants Table */}
      <Card style={{ padding: 0, overflow: 'hidden' }}>
        <div style={{ padding: '18px 22px', borderBottom: isBloom ? `1.5px solid ${t.border}` : `1px solid ${t.border}`, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div>
            <h3 style={{ margin: 0, fontFamily: t.fontDisplay, fontSize: 18, fontWeight: 700, color: t.text }}>Lista de Assinantes SaaS</h3>
            <div style={{ fontSize: 12, color: t.textMuted, marginTop: 2 }}>Gerencie o plano, status de acesso e monitoramento de consumo de cada empresa parceira.</div>
          </div>
        </div>

        <div style={{ overflowX: 'auto' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', textAlign: 'left', minWidth: 800 }}>
            <thead>
              <tr style={{ background: isBloom ? t.surfaceAlt : 'rgba(255,255,255,0.02)', borderBottom: `1px solid ${t.border}` }}>
                {['Empresa / Cliente', 'Administrador', 'Plano', 'Faturamento', 'Tokens IA', 'Cadastro', 'Status', 'Ações'].map((h, i) => (
                  <th key={i} style={{ padding: '12px 18px', fontSize: 11.5, fontWeight: 700, color: t.textMuted, fontFamily: t.fontMono }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {tenants.map((item, idx) => (
                <tr key={item.id} style={{ 
                  borderBottom: idx < tenants.length - 1 ? `1px solid ${t.border}` : 'none',
                  transition: 'background 0.2s' 
                }} onMouseEnter={(e) => { e.currentTarget.style.background = isBloom ? t.surfaceAlt : 'rgba(255,255,255,0.01)'; }} onMouseLeave={(e) => { e.currentTarget.style.background = 'transparent'; }}>
                  
                  {/* Empresa */}
                  <td style={{ padding: '14px 18px' }}>
                    <div style={{ fontSize: 13.5, fontWeight: 700, color: t.text }}>{item.name}</div>
                    <div style={{ fontSize: 11, color: t.textMuted, marginTop: 2, fontFamily: t.fontMono }}>ID: {item.id}</div>
                  </td>
                  
                  {/* Administrador */}
                  <td style={{ padding: '14px 18px' }}>
                    <div style={{ fontSize: 13, color: t.text }}>{item.owner}</div>
                    <div style={{ fontSize: 11, color: t.textMuted, marginTop: 2 }}>{item.email}</div>
                  </td>
                  
                  {/* Plano */}
                  <td style={{ padding: '14px 18px' }}>
                    <Pill soft={item.plan === 'Enterprise' ? t.purpleSoft : item.plan === 'Pro' ? t.greenSoft : t.blueSoft} color={isBloom ? t.text : (item.plan === 'Enterprise' ? t.purple : item.plan === 'Pro' ? t.green : t.blue)} style={{ padding: '3px 8px', fontSize: 11 }}>
                      {item.plan}
                    </Pill>
                  </td>
                  
                  {/* Faturamento */}
                  <td style={{ padding: '14px 18px', fontFamily: t.fontMono, fontSize: 13, fontWeight: 600, color: t.text }}>
                    R$ {item.price},00 <span style={{ fontSize: 10, color: t.textMuted, fontWeight: 400 }}>/mês</span>
                  </td>
                  
                  {/* Tokens IA */}
                  <td style={{ padding: '14px 18px', fontFamily: t.fontMono, fontSize: 12.5, color: t.text }}>
                    {(item.tokensUsed / 1000).toFixed(1)}K <span style={{ fontSize: 10, color: t.textMuted }}>tokens</span>
                  </td>
                  
                  {/* Cadastro */}
                  <td style={{ padding: '14px 18px', fontFamily: t.fontMono, fontSize: 12, color: t.textMuted }}>
                    {new Date(item.registeredAt).toLocaleDateString('pt-BR', { day: '2-digit', month: 'short', year: 'numeric' })}
                  </td>
                  
                  {/* Status */}
                  <td style={{ padding: '14px 18px' }}>
                    <Pill soft={item.status === 'Ativo' ? t.greenSoft : 'rgba(239,68,68,0.1)'} color={isBloom ? t.text : (item.status === 'Ativo' ? t.green : t.red)} style={{ padding: '2px 8px', fontSize: 10.5 }}>
                      {item.status}
                    </Pill>
                  </td>
                  
                  {/* Ações */}
                  <td style={{ padding: '14px 18px' }}>
                    <div style={{ display: 'flex', gap: 6 }}>
                      <Btn variant="ghost" size="sm" onClick={() => handleEditPlan(item.id, item.plan)}>Alterar Plano</Btn>
                      <Btn variant="ghost" size="sm" onClick={() => handleToggleStatus(item.id, item.status)} style={{ color: item.status === 'Ativo' ? t.red : t.green }}>
                        {item.status === 'Ativo' ? 'Suspender' : 'Ativar'}
                      </Btn>
                    </div>
                  </td>

                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </Card>
    </div>
  );
};

window.AdminPanel = AdminPanel;
