// Upload inteligente — modal com upload real para a API.
// Depois de enviado, o arquivo é analisado (regex sempre; IA quando configurada)
// e o usuário escolhe o que fazer: virar cliente novo, virar caso novo, só
// entrar no histórico do cliente, ou só entrar na linha do tempo do caso.

const UploadModal = ({ onClose }) => {
  const [stage, setStage] = React.useState('drop'); // drop -> uploading -> classify -> action
  const [over, setOver] = React.useState(false);
  const [file, setFile] = React.useState(null);
  const [result, setResult] = React.useState(null);
  const [error, setError] = React.useState('');
  const [saving, setSaving] = React.useState(false);
  const [done, setDone] = React.useState(null); // mensagem de sucesso final

  // Listas reais (a versão anterior usava window.PAC_DATA — mock estático,
  // desatualizado e não isolado por organização).
  const [clients, setClients] = React.useState([]);
  const [cases, setCases] = React.useState([]);
  React.useEffect(() => {
    window.OctaleApi.clients.list().then(setClients).catch(() => {});
    window.OctaleApi.cases.list().then(setCases).catch(() => {});
  }, []);

  // Ação escolhida (uma das 4 opções rápidas) ou 'manual' (fallback antigo).
  const [action, setAction] = React.useState(null);
  const [clientId, setClientId] = React.useState('');
  const [caseId, setCaseId] = React.useState('');
  const [category, setCategory] = React.useState('');
  const [newClient, setNewClient] = React.useState({ name: '', short_name: '', person_type: 'PJ', cnpj: '', cpf: '' });
  const [newCase, setNewCase] = React.useState({ title: '', area: 'Contratos', numero_processo: '' });

  const CATEGORIES = [
    { value: 'balanco_contabil', label: 'Balanço auditado / contábil' },
    { value: 'atos_societarios', label: 'Atos societários' },
    { value: 'contrato_minuta', label: 'Contrato / minuta' },
    { value: 'documento_fiscal', label: 'Documento fiscal' },
    { value: 'documento_trabalhista', label: 'Documento trabalhista' },
    { value: 'email_comunicacao', label: 'E-mail / comunicação' },
    { value: 'audio_transcricao', label: 'Áudio / transcrição' },
    { value: 'outros', label: 'Outros' },
  ];

  const CASE_AREAS = ['M&A', 'Franchising', 'Societário', 'Contratos', 'Venture Capital', 'Propriedade Intelectual', 'Contencioso', 'Tributário', 'Trabalhista', 'Outros'];

  const handleFile = async (f) => {
    setFile(f);
    setStage('uploading');
    setError('');
    try {
      const uploadResult = await window.OctaleApi.documents.upload(f);
      setResult(uploadResult);
      setCategory(uploadResult.document.category || '');
      setClientId(uploadResult.document.client_id || '');
      setCaseId(uploadResult.document.case_id || '');

      const detected = uploadResult.detected || {};
      // Pré-preenche o formulário de ação com o que já foi detectado, para o
      // advogado só confirmar em vez de digitar tudo de novo.
      setNewClient(nc => ({ ...nc, name: detected.client_name || '', cnpj: detected.cnpj || '', cpf: detected.cpf || '', person_type: detected.cnpj ? 'PJ' : detected.cpf ? 'PF' : 'PJ' }));
      setNewCase(nk => ({ ...nk, numero_processo: detected.numero_processo || '' }));
      setAction(detected.suggested_action || null);
      setStage('classify');
    } catch (err) {
      setError(err.message || 'Erro no upload.');
      setStage('drop');
    }
  };

  const onDragOver = (e) => { e.preventDefault(); setOver(true); };
  const onDragLeave = () => setOver(false);
  const onDrop = (e) => {
    e.preventDefault(); setOver(false);
    const f = e.dataTransfer.files[0];
    if (f) handleFile(f);
  };

  const onFileInput = (e) => {
    const f = e.target.files[0];
    if (f) handleFile(f);
  };

  const fmtSize = (bytes) => {
    if (bytes < 1024) return `${bytes} B`;
    if (bytes < 1048576) return `${(bytes / 1024).toFixed(0)} KB`;
    return `${(bytes / 1048576).toFixed(1)} MB`;
  };

  // Ação manual (fallback antigo): só define categoria/cliente/caso do documento
  // já criado, sem gerar novos registros. Cobre "outras automações possíveis"
  // ou o caso em que nenhuma das 4 opções rápidas se aplica.
  const runManualSave = async () => {
    await window.OctaleApi.documents.update(result.document.id, {
      category,
      client_id: clientId || undefined,
      case_id: caseId || undefined,
    });
    setDone('Documento classificado e salvo.');
  };

  const runAction = async () => {
    if (!result) return;
    setSaving(true);
    setError('');
    try {
      if (action === 'manual' || action === null) {
        await runManualSave();
      } else if (action === 'create_client') {
        if (!newClient.name.trim() || !newClient.short_name.trim()) {
          throw new Error('Informe nome e nome curto do cliente.');
        }
        const r = await window.OctaleApi.documents.action(result.document.id, {
          action: 'create_client',
          client: newClient,
        });
        setDone(`Cliente "${r.client.name}" criado e documento vinculado ao histórico dele.`);
      } else if (action === 'create_case') {
        if (!clientId) throw new Error('Selecione o cliente deste caso.');
        if (!newCase.title.trim()) throw new Error('Informe o título do caso.');
        const r = await window.OctaleApi.documents.action(result.document.id, {
          action: 'create_case',
          client_id: clientId,
          case: newCase,
        });
        setDone(`Caso "${r.case.title}" (${r.case.number}) criado — documento na linha do tempo.`);
      } else if (action === 'link_client') {
        if (!clientId) throw new Error('Selecione o cliente.');
        await window.OctaleApi.documents.action(result.document.id, { action: 'link_client', client_id: clientId });
        setDone('Documento salvo no histórico do cliente.');
      } else if (action === 'link_case_timeline') {
        if (!caseId) throw new Error('Selecione o caso.');
        await window.OctaleApi.documents.action(result.document.id, { action: 'link_case_timeline', case_id: caseId });
        setDone('Documento salvo na linha do tempo do caso.');
      }
    } catch (err) {
      setError(err.message || 'Erro ao salvar.');
    } finally {
      setSaving(false);
    }
  };

  const filteredCases = cases.filter(c => !clientId || c.client_id === clientId);

  const ACTION_OPTIONS = [
    { key: 'create_client', icon: 'users', label: 'Novo cliente', desc: 'O arquivo tem dados de uma pessoa/empresa ainda não cadastrada.' },
    { key: 'create_case', icon: 'briefcase', label: 'Novo caso', desc: 'O arquivo é de um processo/matéria que ainda não existe no sistema.' },
    { key: 'link_client', icon: 'fileText', label: 'Histórico do cliente', desc: 'Só anexar a um cliente já cadastrado, sem criar caso.' },
    { key: 'link_case_timeline', icon: 'clock', label: 'Linha do tempo do caso', desc: 'Só anexar a um caso já existente, com marco na timeline.' },
  ];

  return (
    <div className="scrim" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <div className="modal-head">
          <div style={{ width: 32, height: 32, borderRadius: 4, background: 'var(--octale-navy)', color: '#fff', display: 'grid', placeItems: 'center' }}>
            <Icon name="upload" size={16} />
          </div>
          <div>
            <h2>Upload inteligente</h2>
            <div style={{ fontSize: 12, color: 'var(--fg-muted)' }}>O sistema analisa e sugere o que fazer com o arquivo.</div>
          </div>
          <button className="x" onClick={onClose}><Icon name="x" size={16} /></button>
        </div>

        <div className="modal-body">
          {error && (
            <div style={{ padding: '10px 14px', background: 'rgba(194,37,62,.08)', border: '1px solid rgba(194,37,62,.2)', borderRadius: 6, color: '#C2253E', fontSize: 12, marginBottom: 14 }}>
              {error}
            </div>
          )}

          {done && (
            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 14, padding: '32px 16px', textAlign: 'center' }}>
              <div style={{ width: 44, height: 44, borderRadius: 999, background: 'rgba(34,212,138,.12)', display: 'grid', placeItems: 'center' }}>
                <Icon name="check" size={22} style={{ color: '#16a34a' }} />
              </div>
              <div style={{ fontSize: 13.5, color: 'var(--octale-black)', fontWeight: 600, maxWidth: 360 }}>{done}</div>
            </div>
          )}

          {/* Estágio: drop */}
          {!done && stage === 'drop' && (
            <>
              <label htmlFor="file-input" style={{ display: 'block', cursor: 'pointer' }}>
                <div
                  className={`drop ${over ? 'over' : ''}`}
                  onDragOver={onDragOver}
                  onDragLeave={onDragLeave}
                  onDrop={onDrop}
                >
                  <Icon name="upload" size={28} style={{ color: 'var(--octale-navy)' }} />
                  <div className="ttl">Arraste arquivos aqui ou clique para enviar</div>
                  <div className="sub">PDFs, DOCXs, áudios, imagens, e-mails (.eml), notas e prints</div>
                  <div className="types">
                    <span><Icon name="fileText" size={11} style={{ verticalAlign: 'middle' }} /> Documentos</span>
                    <span>·</span>
                    <span><Icon name="audio" size={11} style={{ verticalAlign: 'middle' }} /> Áudio</span>
                    <span>·</span>
                    <span><Icon name="image" size={11} style={{ verticalAlign: 'middle' }} /> Imagens</span>
                    <span>·</span>
                    <span><Icon name="mail" size={11} style={{ verticalAlign: 'middle' }} /> E-mails</span>
                  </div>
                </div>
              </label>
              <input id="file-input" type="file" style={{ display: 'none' }} onChange={onFileInput}
                accept=".pdf,.docx,.doc,.txt,.eml,.png,.jpg,.jpeg,.webp,.mp3,.mp4,.wav,.ogg" />

              <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginTop: 20, fontSize: 12, color: 'var(--fg-muted)' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                  <Icon name="lock" size={12} /> Criptografia ponta a ponta
                </div>
                <span>·</span>
                <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                  <Icon name="sparkles" size={12} style={{ color: 'var(--octale-navy)' }} /> Classificação automática
                </div>
              </div>
            </>
          )}

          {/* Estágio: uploading */}
          {!done && stage === 'uploading' && (
            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 16, padding: '32px 0' }}>
              <div className="spinner" style={{ width: 32, height: 32, borderWidth: 3 }} />
              <div style={{ fontSize: 13, color: 'var(--octale-navy)', fontWeight: 600 }}>
                Enviando e analisando…
              </div>
              {file && (
                <div style={{ fontSize: 12, color: 'var(--fg-muted)' }}>
                  {file.name} · {fmtSize(file.size)}
                </div>
              )}
            </div>
          )}

          {/* Estágio: classify — escolher o que fazer com o arquivo */}
          {!done && stage === 'classify' && result && (
            <>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px', background: '#fff', border: '1px solid var(--border)', borderRadius: 6 }}>
                <div style={{ width: 36, height: 36, background: 'rgba(23,23,15,.06)', borderRadius: 4, display: 'grid', placeItems: 'center' }}>
                  <Icon name="fileText" size={18} style={{ color: 'var(--octale-navy)' }} />
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, color: 'var(--octale-navy)', fontWeight: 600 }}>{result.document.filename}</div>
                  <div style={{ fontSize: 11, color: 'var(--fg-muted)' }}>{fmtSize(result.document.size)}</div>
                </div>
                <span className="chip soft">✓ Enviado</span>
              </div>

              {result.summary && (
                <div style={{ marginTop: 10, padding: '10px 14px', background: 'rgba(23,23,15,.03)', borderRadius: 4, fontSize: 12, color: 'var(--octale-black)', lineHeight: 1.55 }}>
                  {result.summary}
                </div>
              )}

              {result.detected?.suggested_action && (
                <div className="ai-suggest" style={{ marginTop: 14 }}>
                  <Icon name="sparkles" size={14} style={{ color: 'var(--octale-navy)' }} />
                  <div style={{ flex: 1 }}>
                    {result.detected.numero_processo && <div><b>Processo detectado:</b> {result.detected.numero_processo}</div>}
                    {result.detected.cnpj && <div><b>CNPJ detectado:</b> {result.detected.cnpj}</div>}
                    {result.detected.cpf && <div><b>CPF detectado:</b> {result.detected.cpf}</div>}
                    {result.detected.client_name && <div><b>Parte identificada:</b> {result.detected.client_name}</div>}
                  </div>
                </div>
              )}

              <div style={{ fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.08em', color: 'var(--fg-muted)', marginTop: 18, marginBottom: 8 }}>
                O que fazer com este arquivo?
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
                {ACTION_OPTIONS.map(opt => (
                  <button
                    key={opt.key}
                    onClick={() => setAction(opt.key)}
                    style={{
                      textAlign: 'left', padding: '10px 12px', borderRadius: 8, cursor: 'pointer',
                      border: '1.5px solid ' + (action === opt.key ? 'var(--octale-navy)' : 'var(--border)'),
                      background: action === opt.key ? 'rgba(23,23,15,.05)' : '#fff',
                    }}
                  >
                    <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12.5, fontWeight: 700, color: 'var(--octale-navy)', marginBottom: 3 }}>
                      <Icon name={opt.icon} size={13} />
                      {opt.label}
                      {result.detected?.suggested_action === opt.key && (
                        <span style={{ marginLeft: 'auto', fontSize: 9, fontWeight: 700, background: 'var(--octale-navy)', color: '#fff', borderRadius: 999, padding: '1px 6px' }}>sugerido</span>
                      )}
                    </div>
                    <div style={{ fontSize: 11, color: 'var(--fg-muted)', lineHeight: 1.4 }}>{opt.desc}</div>
                  </button>
                ))}
              </div>

              {/* Formulário específico da ação escolhida */}
              {action === 'create_client' && (
                <div className="field-grid" style={{ marginTop: 14 }}>
                  <div className="field-w">
                    <label>Tipo</label>
                    <select value={newClient.person_type} onChange={e => setNewClient(c => ({ ...c, person_type: e.target.value }))}>
                      <option value="PJ">Pessoa Jurídica</option>
                      <option value="PF">Pessoa Física</option>
                    </select>
                  </div>
                  <div className="field-w">
                    <label>{newClient.person_type === 'PJ' ? 'CNPJ' : 'CPF'}</label>
                    <input
                      value={newClient.person_type === 'PJ' ? newClient.cnpj : newClient.cpf}
                      onChange={e => setNewClient(c => ({ ...c, [newClient.person_type === 'PJ' ? 'cnpj' : 'cpf']: e.target.value }))}
                    />
                  </div>
                  <div className="field-w">
                    <label>Nome / Razão social</label>
                    <input value={newClient.name} onChange={e => setNewClient(c => ({ ...c, name: e.target.value }))} />
                  </div>
                  <div className="field-w">
                    <label>Nome curto (até 10 caracteres)</label>
                    <input value={newClient.short_name} maxLength={10} onChange={e => setNewClient(c => ({ ...c, short_name: e.target.value }))} />
                  </div>
                </div>
              )}

              {action === 'create_case' && (
                <div className="field-grid" style={{ marginTop: 14 }}>
                  <div className="field-w" style={{ gridColumn: '1 / -1' }}>
                    <label>Cliente deste caso</label>
                    <SearchableSelect value={clientId} onChange={(e) => setClientId(e.target.value)}>
                      <option value="">— Selecione —</option>
                      {clients.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
                    </SearchableSelect>
                  </div>
                  <div className="field-w" style={{ gridColumn: '1 / -1' }}>
                    <label>Título do caso</label>
                    <input value={newCase.title} onChange={e => setNewCase(k => ({ ...k, title: e.target.value }))} />
                  </div>
                  <div className="field-w">
                    <label>Área</label>
                    <select value={newCase.area} onChange={e => setNewCase(k => ({ ...k, area: e.target.value }))}>
                      {CASE_AREAS.map(a => <option key={a} value={a}>{a}</option>)}
                    </select>
                  </div>
                  <div className="field-w">
                    <label>Nº do processo (opcional)</label>
                    <input value={newCase.numero_processo} onChange={e => setNewCase(k => ({ ...k, numero_processo: e.target.value }))} />
                  </div>
                </div>
              )}

              {action === 'link_client' && (
                <div className="field-grid" style={{ marginTop: 14 }}>
                  <div className="field-w" style={{ gridColumn: '1 / -1' }}>
                    <label>Cliente</label>
                    <SearchableSelect value={clientId} onChange={(e) => setClientId(e.target.value)}>
                      <option value="">— Selecione —</option>
                      {clients.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
                    </SearchableSelect>
                  </div>
                </div>
              )}

              {action === 'link_case_timeline' && (
                <div className="field-grid" style={{ marginTop: 14 }}>
                  <div className="field-w">
                    <label>Cliente</label>
                    <SearchableSelect value={clientId} onChange={(e) => { setClientId(e.target.value); setCaseId(''); }}>
                      <option value="">— Todos —</option>
                      {clients.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
                    </SearchableSelect>
                  </div>
                  <div className="field-w">
                    <label>Caso</label>
                    <SearchableSelect value={caseId} onChange={(e) => setCaseId(e.target.value)}>
                      <option value="">— Selecione —</option>
                      {filteredCases.map(k => <option key={k.id} value={k.id}>{k.number} · {k.title}</option>)}
                    </SearchableSelect>
                  </div>
                </div>
              )}

              {!action && (
                <div style={{ marginTop: 14 }}>
                  <button className="btn ghost sm" onClick={() => setAction('manual')}>
                    Nenhuma das opções — só classificar manualmente
                  </button>
                </div>
              )}

              {action === 'manual' && (
                <div className="field-grid" style={{ marginTop: 14 }}>
                  <div className="field-w">
                    <label>Cliente</label>
                    <SearchableSelect value={clientId} onChange={(e) => setClientId(e.target.value)}>
                      <option value="">— Nenhum —</option>
                      {clients.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
                    </SearchableSelect>
                  </div>
                  <div className="field-w">
                    <label>Caso</label>
                    <SearchableSelect value={caseId} onChange={(e) => setCaseId(e.target.value)}>
                      <option value="">— Nenhum —</option>
                      {filteredCases.map(k => <option key={k.id} value={k.id}>{k.number} · {k.title}</option>)}
                    </SearchableSelect>
                  </div>
                  <div className="field-w" style={{ gridColumn: '1 / -1' }}>
                    <label>Categoria</label>
                    <select value={category} onChange={(e) => setCategory(e.target.value)}>
                      {CATEGORIES.map(c => <option key={c.value} value={c.value}>{c.label}</option>)}
                    </select>
                  </div>
                </div>
              )}
            </>
          )}
        </div>

        <div className="modal-foot">
          {!done && stage === 'classify' && (
            <button className="btn ghost sm" onClick={() => { setStage('drop'); setResult(null); setFile(null); setAction(null); }}>
              <Icon name="chevronLeft" size={12} /> Novo arquivo
            </button>
          )}
          {!done && stage === 'drop' && <span style={{ fontSize: 11, color: 'var(--fg-muted)' }}>Máx. 50 MB por arquivo.</span>}
          <div style={{ display: 'flex', gap: 8, marginLeft: 'auto' }}>
            <button className="btn ghost sm" onClick={onClose}>{done ? 'Fechar' : 'Cancelar'}</button>
            {!done && stage === 'classify' && action && (
              <button className="btn sm" onClick={runAction} disabled={saving}>
                {saving ? <><span className="spinner" style={{ width: 12, height: 12, borderWidth: 2, marginRight: 6 }} />Salvando…</> : 'Confirmar'}
              </button>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

window.UploadModal = UploadModal;
