/* B28 HospeX — Gestão de casos */
function ViewCases({ hotelId }) {
  const [cases, setCases] = useState([]);
  const [openCase, setOpenCase] = useState(null);
  const [loading, setLoading] = useState(true);
  const [newTitle, setNewTitle] = useState('');
  const [newPriority, setNewPriority] = useState('medium');

  const cols = [
    { key: 'open', label: 'Novo', color: 'var(--error)' },
    { key: 'in_progress', label: 'Em andamento', color: '#caa53a' },
    { key: 'resolved', label: 'Resolvido', color: 'var(--primary)' },
    { key: 'closed', label: 'Fechado', color: 'var(--outline)' }
  ];

  async function fetchCases() {
    const url = hotelId ? `/api/cases?hotel_id=${encodeURIComponent(hotelId)}` : '/api/cases';
    const res = await fetch(url);
    const json = await res.json();
    setCases(Array.isArray(json?.cases) ? json.cases : []);
  }

  useEffect(() => {
    let canceled = false;
    async function load() {
      try {
        await fetchCases();
      } catch (e) {
        if (!canceled) setCases([]);
      } finally {
        if (!canceled) setLoading(false);
      }
    }
    load();
    return () => {
      canceled = true;
    };
  }, [hotelId]);

  async function createCase() {
    if (!hotelId) return alert('Selecione um hotel no topo para criar casos.');
    if (!newTitle.trim()) return;

    const res = await fetch('/api/cases', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        hotel_id: hotelId,
        title: newTitle.trim(),
        priority: newPriority,
        status: 'open',
        source: 'manual'
      })
    });
    if (res.ok) {
      setNewTitle('');
      setNewPriority('medium');
      fetchCases();
    }
  }

  function prioLabel(p) {
    return p === 'high' ? 'Alta' : p === 'low' ? 'Baixa' : 'Média';
  }

  const openCount = cases.filter(c => c.status === 'open' || c.status === 'in_progress').length;

  if (loading) return (
    <div style={{ display: 'grid', placeItems: 'center', height: '40vh' }}>
      <Icon name="progress_activity" size={40} className="hx-spin" style={{ color: 'var(--primary)' }} />
    </div>
  );

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 18, marginBottom: 22 }}>
        <Stat label="Casos abertos" value={openCount} icon="flag" accent="var(--error)" />
        <Stat label="Total de casos" value={cases.length} icon="list_alt" accent="var(--secondary)" />
        <Stat label="Resolvidos" value={cases.filter(c => c.status === 'resolved').length} icon="task_alt" accent="var(--primary)" />
      </div>

      <Card pad={18} style={{ marginBottom: 18 }}>
        <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
          <input value={newTitle} onChange={e => setNewTitle(e.target.value)} placeholder="Novo caso (título)" style={{ flex: 1, padding: '12px 14px', borderRadius: 12, border: '1px solid var(--outline-variant)', background: 'var(--surface-container-lowest)' }} />
          <select value={newPriority} onChange={e => setNewPriority(e.target.value)} style={{ padding: '12px 14px', borderRadius: 12, border: '1px solid var(--outline-variant)', background: 'var(--surface-container-lowest)' }}>
            <option value="low">Baixa</option>
            <option value="medium">Média</option>
            <option value="high">Alta</option>
          </select>
          <button className="btn btn-primary" onClick={createCase} style={{ fontSize: 13.5, padding: '10px 18px' }}><Icon name="add" size={17} /> Novo caso</button>
        </div>
      </Card>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16, alignItems: 'start' }}>
        {cols.map(col => {
          const items = cases.filter(c => c.status === col.key);
          return (
            <div key={col.key} style={{ background: 'var(--surface-container-low)', borderRadius: 16, padding: 14 }}>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '4px 6px 14px' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <span style={{ width: 9, height: 9, borderRadius: 999, background: col.color }}></span>
                  <span style={{ fontSize: 13, fontWeight: 800, fontFamily: 'var(--font-headline)' }}>{col.label}</span>
                </div>
                <span style={{ fontSize: 12, fontWeight: 700, color: 'var(--on-surface-variant)', background: 'var(--surface-container-high)', borderRadius: 999, padding: '2px 9px' }}>{items.length}</span>
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 11 }}>
                {items.map(c => (
                  <div key={c.id} onClick={() => setOpenCase(c)} className="hx-casecard" style={{ background: 'var(--surface-container-lowest)', border: '1px solid color-mix(in srgb, var(--outline-variant) 55%, transparent)', borderRadius: 13, padding: 15, cursor: 'pointer' }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 9 }}>
                      <span style={{ fontSize: 11, fontWeight: 700, color: 'var(--on-surface-variant)', fontFamily: 'var(--font-headline)' }}>{c.id}</span>
                      <PrioBadge prio={prioLabel(c.priority)} />
                    </div>
                    <div style={{ fontSize: 13.5, fontWeight: 700, lineHeight: 1.35, marginBottom: 9 }}>{c.title}</div>
                    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', paddingTop: 10, borderTop: '1px solid var(--outline-variant)' }}>
                      <span style={{ fontSize: 10.5, fontWeight: 600, color: 'var(--on-surface-variant)', display: 'inline-flex', alignItems: 'center', gap: 4 }}>
                        <Icon name="bolt" size={13} fill={1} style={{ color: c.source === 'manual' ? 'var(--on-surface-variant)' : 'var(--primary)' }} />{c.source}
                      </span>
                      <span style={{ fontSize: 10.5, fontWeight: 700, color: 'var(--on-surface-variant)' }}>{col.label}</span>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          );
        })}
      </div>

      {openCase && <CaseDrawer c={openCase} hotelId={hotelId} onClose={() => setOpenCase(null)} onUpdated={fetchCases} />}
    </div>
  );
}

function CaseDrawer({ c, hotelId, onClose, onUpdated }) {
  const [messages, setMessages] = useState([]);
  const [body, setBody] = useState('');
  const [saving, setSaving] = useState(false);

  async function fetchMessages() {
    const res = await fetch(`/api/cases/${c.id}/messages`);
    const json = await res.json();
    setMessages(Array.isArray(json?.messages) ? json.messages : []);
  }

  useEffect(() => {
    fetchMessages();
  }, [c?.id]);

  async function setStatus(status) {
    setSaving(true);
    try {
      const res = await fetch(`/api/cases/${c.id}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ status })
      });
      if (res.ok) onUpdated();
    } finally {
      setSaving(false);
    }
  }

  async function sendMessage() {
    if (!hotelId) return;
    if (!body.trim()) return;

    setSaving(true);
    try {
      const res = await fetch(`/api/cases/${c.id}/messages`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ hotel_id: hotelId, body: body.trim() })
      });
      if (res.ok) {
        setBody('');
        fetchMessages();
      }
    } finally {
      setSaving(false);
    }
  }

  return (
    <div style={{ position: 'fixed', inset: 0, zIndex: 60 }}>
      <div onClick={onClose} style={{ position: 'absolute', inset: 0, background: 'rgba(26,28,28,0.42)', backdropFilter: 'blur(2px)' }}></div>
      <div className="hx-drawer" style={{ position: 'absolute', top: 0, right: 0, bottom: 0, width: 480, background: 'var(--background)', boxShadow: 'var(--shadow-lg)', display: 'flex', flexDirection: 'column' }}>
        <div style={{ padding: '22px 26px', borderBottom: '1px solid var(--outline-variant)', display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 12 }}>
          <div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
              <span style={{ fontSize: 12, fontWeight: 800, color: 'var(--on-surface-variant)', fontFamily: 'var(--font-headline)' }}>{c.id}</span>
              <span style={{ fontSize: 11, fontWeight: 700, padding: '3px 10px', borderRadius: 999, background: 'var(--surface-container-high)', color: 'var(--on-surface-variant)' }}>{c.status}</span>
            </div>
            <h2 className="font-headline" style={{ margin: 0, fontSize: 19, fontWeight: 800, letterSpacing: '-0.02em', lineHeight: 1.25 }}>{c.title}</h2>
          </div>
          <button onClick={onClose} style={{ width: 36, height: 36, borderRadius: 999, border: 'none', background: 'var(--surface-container-high)', cursor: 'pointer', display: 'grid', placeItems: 'center', flexShrink: 0 }}><Icon name="close" size={20} /></button>
        </div>

        <div style={{ padding: 18, display: 'flex', gap: 10, borderBottom: '1px solid var(--outline-variant)' }}>
          {['open', 'in_progress', 'resolved', 'closed'].map(s => (
            <button key={s} className="btn btn-outline" disabled={saving} onClick={() => setStatus(s)} style={{ padding: '10px 12px', fontSize: 12.5 }}>
              {s}
            </button>
          ))}
        </div>

        <div style={{ flex: 1, overflow: 'auto', padding: 18, display: 'flex', flexDirection: 'column', gap: 10 }}>
          {messages.length ? messages.map(m => (
            <div key={m.id} style={{ padding: '12px 14px', borderRadius: 12, background: 'var(--surface-container-low)' }}>
              <div style={{ fontSize: 11.5, color: 'var(--on-surface-variant)', marginBottom: 6 }}>{new Date(m.created_at).toLocaleString('pt-BR')}</div>
              <div style={{ fontSize: 13.5, lineHeight: 1.55 }}>{m.body}</div>
            </div>
          )) : (
            <div style={{ padding: 16, borderRadius: 12, background: 'var(--surface-container-low)', color: 'var(--on-surface-variant)', fontSize: 13 }}>
              Sem mensagens ainda.
            </div>
          )}
        </div>

        <div style={{ padding: 16, borderTop: '1px solid var(--outline-variant)', display: 'flex', gap: 10 }}>
          <input value={body} onChange={e => setBody(e.target.value)} placeholder="Escreva uma atualização..." style={{ flex: 1, padding: '12px 14px', borderRadius: 12, border: '1px solid var(--outline-variant)', background: 'var(--surface-container-lowest)' }} />
          <button className="btn btn-primary" disabled={saving} onClick={sendMessage} style={{ padding: '10px 16px' }}><Icon name="send" size={16} /> Enviar</button>
        </div>
      </div>
    </div>
  );
}

window.ViewCases = ViewCases;

