const { useState } = React;

// ─── Authority Table ─────────────────────────────────────────────────────────
function AuthorityTable() {
  const rows = [
    { range: 'Até R$ 10k',         authority: 'Gerente de Disciplina',              sla: '4h',  badge: 'default'  },
    { range: 'R$ 10k – R$ 50k',    authority: 'Gerente Obra + Coord. Financeiro',   sla: '8h',  badge: 'default'  },
    { range: 'R$ 50k – R$ 200k',   authority: 'PMO Sênior + Controller',            sla: '24h', badge: 'primary'  },
    { range: 'R$ 200k – R$ 500k',  authority: 'CFO + Ger. Geral Obras',             sla: '48h', badge: 'warning'  },
    { range: 'Acima R$ 500k',      authority: 'Diretoria (2 assinaturas) + CEx',    sla: '72h', badge: 'danger'   },
    { range: 'Urgência',           authority: 'Qualquer alçada + superior',          sla: '2h',  badge: 'danger'   },
  ];
  return (
    <div style={{ overflowX:'auto' }}>
      <table style={{ width:'100%', borderCollapse:'collapse', fontSize:11.5 }}>
        <thead>
          <tr style={{ background:'#F8FAFC' }}>
            <Th>Faixa de Valor</Th>
            <Th>Autoridade Aprovadora</Th>
            <Th>SLA</Th>
          </tr>
        </thead>
        <tbody>
          {rows.map((r, i) => (
            <tr key={i} style={{ background: r.range === 'Urgência' ? '#FFF5F5' : i%2===0 ? '#FAFBFC' : C.card }}>
              <Td><strong style={{ color: r.range === 'Urgência' ? C.danger : C.text }}>{r.range}</strong></Td>
              <Td>{r.authority}</Td>
              <Td>
                <span style={{ fontFamily:'IBM Plex Mono, monospace', fontWeight:700, color: parseInt(r.sla) <= 8 ? C.warning : C.textSub }}>{r.sla}</span>
              </Td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

// ─── Auth value bracket ──────────────────────────────────────────────────────
function authBracket(val) {
  if (val <= 10000)   return { label:'≤ R$10k',    variant:'default' };
  if (val <= 50000)   return { label:'≤ R$50k',    variant:'default' };
  if (val <= 200000)  return { label:'≤ R$200k',   variant:'primary' };
  if (val <= 500000)  return { label:'≤ R$500k',   variant:'warning' };
  return                     { label:'> R$500k',   variant:'danger'  };
}

// ─── Request Row ─────────────────────────────────────────────────────────────
function RequestRow({ req, onAction }) {
  const [expanded, setExpanded] = useState(false);
  const [comment, setComment] = useState('');
  const brk = authBracket(req.value);
  const slaRatio = req.slaRemaining / req.slaHours;
  const slaExpired = req.slaRemaining <= 0;

  return (
    <>
      <tr style={{ background: req.urgent ? '#FFF5F5' : C.card, cursor:'pointer' }} onClick={() => setExpanded(e => !e)}>
        <Td>
          <div style={{ display:'flex', alignItems:'center', gap:6 }}>
            {req.urgent && <span style={{ fontSize:9, fontWeight:800, background:C.danger, color:'#fff', padding:'1px 5px', borderRadius:3, letterSpacing:0.5 }}>URGENTE</span>}
            <span style={{ fontFamily:'IBM Plex Mono, monospace', fontSize:11, color:C.textSub }}>{req.id}</span>
          </div>
        </Td>
        <Td><span style={{ fontWeight:600, color:C.text }}>{req.item}</span></Td>
        <Td style={{ fontSize:11, color:C.textSub }}>{req.requester}</Td>
        <Td><span style={{ fontFamily:'IBM Plex Mono, monospace', fontWeight:700, color:C.text }}>{fmtBRL(req.value)}</span></Td>
        <Td><span style={{ fontFamily:'IBM Plex Mono, monospace', fontSize:11 }}>{req.wbs}</span></Td>
        <Td>
          <div style={{ fontSize:11 }}>
            <span style={{ color: req.budgetBalance > req.value ? C.success : C.danger, fontWeight:600 }}>{fmtBRL(req.budgetBalance)}</span>
          </div>
        </Td>
        <Td><Badge label={brk.label} variant={brk.variant} small /></Td>
        <Td><SLABadge slaHours={req.slaHours} slaRemaining={req.slaRemaining} /></Td>
        <Td>
          <div style={{ display:'flex', gap:4 }} onClick={e => e.stopPropagation()}>
            <Btn variant="success" small onClick={() => onAction(req.id, 'approve')}>Aprovar</Btn>
            <Btn variant="danger"  small onClick={() => setExpanded(true)}>Reprovar</Btn>
          </div>
        </Td>
      </tr>
      {expanded && (
        <tr style={{ background:'#F8FAFC' }}>
          <td colSpan={9} style={{ padding:'10px 14px' }}>
            <div style={{ display:'flex', gap:10, alignItems:'flex-end' }}>
              <div style={{ flex:1 }}>
                <div style={{ fontSize:11, fontWeight:600, color:C.text, marginBottom:4 }}>Autoridade: <span style={{ color:C.primary }}>{req.authority}</span> · SLA: {req.slaHours}h · Restante: {req.slaRemaining}h</div>
                <div style={{ fontSize:11, color:C.textSub, marginBottom:6 }}>Comentário obrigatório para valores acima de R$50k</div>
                <textarea
                  value={comment} onChange={e => setComment(e.target.value)}
                  placeholder="Justificativa da decisão..."
                  style={{ width:'100%', padding:'7px 10px', border:`1px solid ${C.border}`, borderRadius:5, fontSize:12, fontFamily:'inherit', resize:'vertical', minHeight:60, boxSizing:'border-box' }}
                />
              </div>
              <div style={{ display:'flex', flexDirection:'column', gap:6 }}>
                <Btn variant="success" onClick={() => { onAction(req.id, 'approve'); setExpanded(false); }}>✓ Confirmar Aprovação</Btn>
                <Btn variant="danger"  onClick={() => { onAction(req.id, 'reject');  setExpanded(false); }}>✗ Reprovar</Btn>
                <Btn variant="default" onClick={() => { onAction(req.id, 'return');  setExpanded(false); }}>↩ Devolver</Btn>
              </div>
            </div>
          </td>
        </tr>
      )}
    </>
  );
}

// ─── Screen 3: Autorizações de Pedidos ──────────────────────────────────────
function Screen3Auth() {
  const { approvalQueue, approvalHistory } = window.SIGP_DATA;
  const [queue, setQueue] = useState(approvalQueue);
  const [history, setHistory] = useState(approvalHistory);
  const [filter, setFilter] = useState('all');

  const totalPending = queue.reduce((s, r) => s + r.value, 0);
  const overSLA = queue.filter(r => r.slaRemaining <= 0).length;
  const maxVal = Math.max(...queue.map(r => r.value));

  function handleAction(id, action) {
    const req = queue.find(r => r.id === id);
    if (!req) return;
    setQueue(q => q.filter(r => r.id !== id));
    setHistory(h => [{ id: req.id, item: req.item, value: req.value, approver: 'PMO Sênior', status: action === 'approve' ? 'approved' : action === 'reject' ? 'rejected' : 'returned', date: '23/05/2026' }, ...h]);
  }

  const filtered = filter === 'urgent' ? queue.filter(r => r.urgent) : filter === 'overdue' ? queue.filter(r => r.slaRemaining <= 0) : queue;

  return (
    <ScreenShell
      title="Sistema de Autorizações de Pedidos"
      subtitle="AUT · Fluxo de aprovação com escalonamento automático por alçada e SLA"
    >
      {/* ── Indicators ── */}
      <div style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:10, marginBottom:14 }}>
        <KPICard label="Total Pendente" value={fmtBRL(totalPending)} sub={`${queue.length} pedidos aguardando`} />
        <KPICard label="Em Atraso de SLA" value={overSLA} sub="pedidos com SLA vencido" status={overSLA > 0 ? 'critical' : 'ok'} />
        <KPICard label="Maior Valor Aguardando" value={fmtBRL(maxVal)} sub="Caldeira Aquatubular" status="warning" />
        <KPICard label="Pedidos Urgentes" value={queue.filter(r => r.urgent).length} sub="requerem aprovação em 2h" status={queue.filter(r=>r.urgent).length > 0 ? 'critical' : 'ok'} />
      </div>

      {/* ── URGENTE alert ── */}
      {queue.some(r => r.urgent) && (
        <div style={{ padding:'8px 14px', background:'#FFF5F5', border:`2px solid ${C.danger}`, borderRadius:7, marginBottom:12, display:'flex', alignItems:'center', gap:10 }}>
          <span style={{ fontSize:18 }}>🚨</span>
          <div>
            <strong style={{ color:C.danger, fontSize:12 }}>PEDIDO URGENTE</strong>
            <span style={{ color:C.text, fontSize:11.5, marginLeft:8 }}>REQ-2849 · Serviço guincho 100t — R$ 42.000 · SLA: 30 min restante · Solicitante: Eng. Roberto Lima</span>
          </div>
        </div>
      )}

      {/* ── Authority table ── */}
      <Card title="Tabela de Alçadas" subtitle="Regras de aprovação por faixa de valor" style={{ marginBottom:14 }}>
        <AuthorityTable />
      </Card>

      {/* ── Filter bar + Queue ── */}
      <Card title="Fila de Pedidos Pendentes" subtitle={`${queue.length} pedidos aguardando aprovação`}
        headerRight={
          <div style={{ display:'flex', gap:4 }}>
            {['all','urgent','overdue'].map(f => (
              <button key={f} onClick={() => setFilter(f)} style={{
                padding:'4px 10px', fontSize:10.5, fontWeight:600, cursor:'pointer',
                background: filter===f ? C.primary : C.card,
                color: filter===f ? '#fff' : C.textSub,
                border:`1px solid ${filter===f ? C.primary : C.border}`,
                borderRadius:4, fontFamily:'inherit',
              }}>{f==='all'?'Todos':f==='urgent'?'Urgentes':'SLA Vencido'}</button>
            ))}
          </div>
        }
        noPad
      >
        <Table>
          <thead>
            <tr>
              <Th>ID</Th>
              <Th>Item / Descrição</Th>
              <Th>Solicitante</Th>
              <Th>Valor</Th>
              <Th>WBS</Th>
              <Th>Saldo WBS</Th>
              <Th>Alçada</Th>
              <Th>SLA Restante</Th>
              <Th>Ações</Th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(req => <RequestRow key={req.id} req={req} onAction={handleAction} />)}
            {filtered.length === 0 && (
              <tr><td colSpan={9} style={{ textAlign:'center', padding:24, color:C.textSub, fontSize:12 }}>Nenhum pedido nesta categoria</td></tr>
            )}
          </tbody>
        </Table>
      </Card>

      {/* ── History ── */}
      <Card title="Histórico Recente de Aprovações" subtitle="Últimas decisões registradas" style={{ marginTop:14 }} noPad>
        <Table>
          <thead>
            <tr>
              <Th>ID</Th>
              <Th>Item</Th>
              <Th>Valor</Th>
              <Th>Aprovador</Th>
              <Th>Status</Th>
              <Th>Data</Th>
            </tr>
          </thead>
          <tbody>
            {history.map((h, i) => (
              <tr key={i} style={{ background: i%2===0 ? '#FAFBFC' : C.card }}>
                <Td><span style={{ fontFamily:'IBM Plex Mono, monospace', fontSize:11 }}>{h.id}</span></Td>
                <Td>{h.item}</Td>
                <Td><span style={{ fontFamily:'IBM Plex Mono, monospace', fontWeight:600 }}>{fmtBRL(h.value)}</span></Td>
                <Td style={{ fontSize:11 }}>{h.approver}</Td>
                <Td>
                  <Badge
                    label={h.status === 'approved' ? '✓ Aprovado' : h.status === 'rejected' ? '✗ Reprovado' : '↩ Devolvido'}
                    variant={h.status === 'approved' ? 'success' : h.status === 'rejected' ? 'danger' : 'default'}
                    small
                  />
                </Td>
                <Td style={{ fontSize:11, color:C.textSub }}>{h.date}</Td>
              </tr>
            ))}
          </tbody>
        </Table>
      </Card>
    </ScreenShell>
  );
}

Object.assign(window, { Screen3Auth });
