/* B28 HospeX — Configurações */
function ViewSettings({ hotelId, onLogout }) {
  const [hotels, setHotels] = useState([]);
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);

  const [hotelName, setHotelName] = useState('');
  const [hotelTz, setHotelTz] = useState('America/Sao_Paulo');

  const [userEmail, setUserEmail] = useState('');
  const [userName, setUserName] = useState('');
  const [userPass, setUserPass] = useState('');

  async function fetchHotels() {
    const res = await fetch('/api/hotels');
    const json = await res.json();
    setHotels(Array.isArray(json?.hotels) ? json.hotels : []);
  }

  async function fetchUsers() {
    const res = await fetch('/api/users');
    const json = await res.json();
    setUsers(Array.isArray(json?.users) ? json.users : []);
  }

  useEffect(() => {
    let canceled = false;
    async function load() {
      try {
        await Promise.all([fetchHotels(), fetchUsers()]);
      } catch (e) {
        if (!canceled) {
          setHotels([]);
          setUsers([]);
        }
      } finally {
        if (!canceled) setLoading(false);
      }
    }
    load();
    return () => {
      canceled = true;
    };
  }, []);

  async function createHotel() {
    if (!hotelName.trim()) return;
    const res = await fetch('/api/hotels', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ name: hotelName.trim(), timezone: hotelTz })
    });
    if (res.ok) {
      setHotelName('');
      await fetchHotels();
    }
  }

  async function createUser() {
    if (!userEmail.trim() || !userPass) return;
    const res = await fetch('/api/users', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email: userEmail.trim(), password: userPass, full_name: userName || null })
    });
    if (res.ok) {
      setUserEmail('');
      setUserName('');
      setUserPass('');
      await fetchUsers();
    }
  }

  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: '1fr 1fr', gap: 18, marginBottom: 22 }}>
        <Card pad={26}>
          <SectionHead eyebrow="Unidades" title="Hotéis" right={<button className="hx-link" onClick={fetchHotels}>Atualizar <Icon name="refresh" size={15} /></button>} />
          <div style={{ display: 'flex', gap: 10, marginBottom: 14 }}>
            <input value={hotelName} onChange={e => setHotelName(e.target.value)} placeholder="Nome do hotel" style={{ flex: 1, padding: '11px 12px', borderRadius: 10, border: '1px solid var(--outline-variant)', background: 'var(--surface-container-lowest)' }} />
            <input value={hotelTz} onChange={e => setHotelTz(e.target.value)} placeholder="Timezone" style={{ width: 160, padding: '11px 12px', borderRadius: 10, border: '1px solid var(--outline-variant)', background: 'var(--surface-container-lowest)' }} />
            <button className="btn btn-primary" onClick={createHotel} style={{ padding: '10px 14px' }}><Icon name="add" size={16} /> Criar</button>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {hotels.length ? hotels.map(h => (
              <div key={h.id} style={{ padding: '12px 14px', borderRadius: 12, background: 'var(--surface-container-low)', display: 'flex', justifyContent: 'space-between', gap: 12 }}>
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontSize: 13.5, fontWeight: 800, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{h.name}</div>
                  <div style={{ fontSize: 12, color: 'var(--on-surface-variant)' }}>{h.timezone || '—'} · {h.id.slice(0, 8)}</div>
                </div>
                {hotelId === h.id && <Chip bg="var(--secondary-container)" color="var(--on-secondary-container)">Selecionado</Chip>}
              </div>
            )) : (
              <div style={{ padding: 14, borderRadius: 12, background: 'var(--surface-container-low)', color: 'var(--on-surface-variant)', fontSize: 13 }}>
                Nenhum hotel cadastrado.
              </div>
            )}
          </div>
        </Card>

        <Card pad={26}>
          <SectionHead eyebrow="Acesso" title="Usuários" right={<button className="hx-link" onClick={fetchUsers}>Atualizar <Icon name="refresh" size={15} /></button>} />
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 12 }}>
            <input value={userName} onChange={e => setUserName(e.target.value)} placeholder="Nome" style={{ padding: '11px 12px', borderRadius: 10, border: '1px solid var(--outline-variant)', background: 'var(--surface-container-lowest)' }} />
            <input value={userEmail} onChange={e => setUserEmail(e.target.value)} placeholder="E-mail" style={{ padding: '11px 12px', borderRadius: 10, border: '1px solid var(--outline-variant)', background: 'var(--surface-container-lowest)' }} />
            <input value={userPass} onChange={e => setUserPass(e.target.value)} placeholder="Senha" type="password" style={{ gridColumn: '1 / -1', padding: '11px 12px', borderRadius: 10, border: '1px solid var(--outline-variant)', background: 'var(--surface-container-lowest)' }} />
          </div>
          <button className="btn btn-primary" onClick={createUser} style={{ width: '100%', justifyContent: 'center', marginBottom: 14 }}><Icon name="person_add" size={17} /> Criar usuário</button>

          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {users.length ? users.map(u => (
              <div key={u.id} style={{ padding: '12px 14px', borderRadius: 12, background: 'var(--surface-container-low)', display: 'flex', justifyContent: 'space-between', gap: 12 }}>
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontSize: 13.5, fontWeight: 800, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{u.full_name || '—'}</div>
                  <div style={{ fontSize: 12, color: 'var(--on-surface-variant)' }}>{u.email}</div>
                </div>
                <Chip bg="var(--surface-container-high)" color="var(--on-surface-variant)">{u.id.slice(0, 8)}</Chip>
              </div>
            )) : (
              <div style={{ padding: 14, borderRadius: 12, background: 'var(--surface-container-low)', color: 'var(--on-surface-variant)', fontSize: 13 }}>
                Nenhum usuário cadastrado (além do admin).
              </div>
            )}
          </div>
        </Card>
      </div>

      <Card pad={22}>
        <SectionHead eyebrow="Sessão" title="Conta" />
        <button className="btn btn-outline" onClick={onLogout} style={{ justifyContent: 'center' }}><Icon name="logout" size={17} /> Sair</button>
      </Card>
    </div>
  );
}

window.ViewSettings = ViewSettings;

