/* B28 HospeX — Integrações */
function ViewIntegrations({ hotelId }) {
  const [tab, setTab] = useState("Todas");
  const [neon, setNeon] = useState({ loading: true, ok: false, db: false, hotels: null });
  const [dbIntegrations, setDbIntegrations] = useState([]);
  const [loadingIntegrations, setLoadingIntegrations] = useState(true);
  const [configItem, setConfigItem] = useState(null); // Item being configured
  const [settings, setSettings] = useState({});
  const [googleLocations, setGoogleLocations] = useState([]);
  const [loadingGoogleLocations, setLoadingGoogleLocations] = useState(false);

  const fetchIntegrations = async () => {
    try {
      const url = hotelId ? `/api/integrations?hotel_id=${encodeURIComponent(hotelId)}` : '/api/integrations';
      const res = await fetch(url);
      const json = await res.json();
      if (json.integrations) setDbIntegrations(json.integrations);
    } catch (e) {
      console.error("Erro ao carregar integrações", e);
    } finally {
      setLoadingIntegrations(false);
    }
  };

  useEffect(() => {
    let canceled = false;
    async function run() {
      try {
        const healthRes = await fetch('/api/health');
        const health = await healthRes.json();

        let hotelsCount = null;
        if (health?.ok) {
          const hotelsRes = await fetch('/api/hotels');
          const hotels = await hotelsRes.json();
          hotelsCount = Array.isArray(hotels?.hotels) ? hotels.hotels.length : null;
          fetchIntegrations();
        }

        if (!canceled) {
          setNeon({ loading: false, ok: !!health?.ok, db: !!health?.db, hotels: hotelsCount });
        }
      } catch (e) {
        if (!canceled) setNeon({ loading: false, ok: false, db: false, hotels: null });
      }
    }
    run();
    return () => {
      canceled = true;
    };
  }, []);

  async function saveIntegration() {
    if (!configItem) return;

    if (!hotelId) {
      alert("Selecione um hotel no topo para configurar a integração.");
      return;
    }

    try {
      const res = await fetch('/api/integrations', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          hotel_id: hotelId,
          provider: configItem.tag === 'OTAs' ? 'ota' : (configItem.tag === 'PMS' ? 'pms' : 'channel'),
          name: configItem.nome,
          status: 'connected',
          settings: settings
        })
      });
      if (res.ok) {
        setConfigItem(null);
        fetchIntegrations();
      }
    } catch (e) {
      alert("Erro ao salvar integração");
    }
  }

  async function connectGoogle() {
    if (!hotelId) return alert('Selecione um hotel no topo para conectar o Google.');
    window.location.href = `/api/oauth/google/start?hotel_id=${encodeURIComponent(hotelId)}`;
  }

  async function loadGoogleLocations() {
    if (!hotelId) return;
    setLoadingGoogleLocations(true);
    try {
      const res = await fetch(`/api/google/locations?hotel_id=${encodeURIComponent(hotelId)}`);
      const json = await res.json();
      setGoogleLocations(Array.isArray(json?.locations) ? json.locations : []);
    } finally {
      setLoadingGoogleLocations(false);
    }
  }

  async function saveGoogleLocation() {
    if (!hotelId) return;
    if (!settings.location_name) return;
    const res = await fetch('/api/google/location', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ hotel_id: hotelId, location_name: settings.location_name, account_name: settings.account_name || null })
    });
    if (res.ok) {
      await fetchIntegrations();
    }
  }

  async function syncGoogle() {
    if (!hotelId) return;
    const res = await fetch('/api/google/sync', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ hotel_id: hotelId })
    });
    if (!res.ok) alert('Falha ao sincronizar Google');
  }

  async function connectBooking() {
    if (!hotelId) return alert('Selecione um hotel no topo para conectar o Booking.');
    if (!settings.property_id || !settings.username || !settings.password) return;
    const res = await fetch('/api/booking/connect', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        hotel_id: hotelId,
        property_id: settings.property_id,
        username: settings.username,
        password: settings.password
      })
    });
    if (res.ok) {
      await fetchIntegrations();
    } else {
      alert('Falha ao conectar Booking');
    }
  }

  async function syncBooking() {
    if (!hotelId) return;
    const res = await fetch('/api/booking/sync', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ hotel_id: hotelId })
    });
    if (!res.ok) alert('Falha ao sincronizar Booking');
  }

  const isConnected = (name) => dbIntegrations.some(i => i.name === name && i.status === 'connected');
  
  const cats = [
    {
      cat: "Avaliações & OTAs", tag: "OTAs",
      items: [
        { nome: "Booking.com", desc: "Coleta de reviews e respostas", cor: "#003580" },
        { nome: "Google", desc: "Avaliações e Business Profile", cor: "#34a853" },
        { nome: "TripAdvisor", desc: "Reviews e ranking de destino", cor: "#00aa6c" },
        { nome: "Facebook", desc: "Recomendações e mensagens", cor: "#1877f2" },
        { nome: "Expedia", desc: "Coleta de avaliações", cor: "#ffc94d" },
        { nome: "Airbnb", desc: "Reviews de hospedagem", cor: "#ff5a5f" },
      ],
    },
    {
      cat: "PMS — Property Management", tag: "PMS",
      items: [
        { nome: "CM Solutions", desc: "Sincronização de reservas e perfis", cor: "#2f803a" },
        { nome: "Opera Cloud", desc: "Oracle Hospitality", cor: "#c74634" },
        { nome: "Desbravador", desc: "PMS nacional", cor: "#0e6624" },
        { nome: "HITS", desc: "Gestão hoteleira", cor: "#416924" },
        { nome: "Stays", desc: "Aluguel por temporada", cor: "#7c4dff" },
        { nome: "+ 45 outros PMS", desc: "Veja o catálogo completo", cor: "var(--tertiary)", more: true },
      ],
    },
    {
      cat: "Mensageria & Canais", tag: "Canais",
      items: [
        { nome: "WhatsApp Business", desc: "Pesquisas e concierge", cor: "#25b34a" },
        { nome: "E-mail (SMTP)", desc: "Pesquisas pós-estadia", cor: "#2f803a" },
        { nome: "QR Code", desc: "Pontos de contato físicos", cor: "#585857" },
        { nome: "SMS", desc: "Disparo de pesquisas", cor: "#caa53a" },
      ],
    },
    {
      cat: "BI & Dados", tag: "BI",
      items: [
        { nome: "Power BI", desc: "Exportação de dashboards", cor: "#f2c811" },
        { nome: "Looker Studio", desc: "Relatórios conectados", cor: "#4285f4" },
        { nome: "API / Webhooks", desc: "Acesso programático aos dados", cor: "#0e6624" },
      ],
    },
  ];

  const tabs = ["Todas", "OTAs", "PMS", "Canais", "BI"];
  const visible = tab === "Todas" ? cats : cats.filter(c => c.tag === tab);
  const totalOn = dbIntegrations.filter(i => i.status === 'connected').length;

  return (
    <div style={{ position: 'relative' }}>
      {/* Config Modal */}
      {configItem && (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.6)', display: 'grid', placeItems: 'center', zIndex: 1000, backdropFilter: 'blur(4px)' }}>
          <Card pad={32} style={{ width: '100%', maxWidth: 460, animation: 'hxFadeUp .3s ease' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 24 }}>
              <div style={{ width: 48, height: 48, borderRadius: 12, background: configItem.cor, display: 'grid', placeItems: 'center', color: '#fff' }}>
                <span className="font-headline" style={{ fontSize: 22, fontWeight: 800 }}>{configItem.nome[0]}</span>
              </div>
              <div>
                <h2 className="font-headline" style={{ margin: 0, fontSize: 20, fontWeight: 800 }}>Configurar {configItem.nome}</h2>
                <div style={{ fontSize: 13, color: 'var(--on-surface-variant)' }}>{configItem.desc}</div>
              </div>
            </div>

            <div style={{ display: 'flex', flexDirection: 'column', gap: 18, marginBottom: 28 }}>
              {configItem.nome === 'Google' ? (
                <>
                  <div style={{ padding: 14, borderRadius: 12, background: 'var(--surface-container-low)', fontSize: 13, color: 'var(--on-surface-variant)', lineHeight: 1.55 }}>
                    Conexão oficial via OAuth. Depois de conectar, selecione a unidade (location) e sincronize as avaliações.
                  </div>

                  <button className="btn btn-primary" onClick={connectGoogle} style={{ width: '100%', justifyContent: 'center' }}>
                    <Icon name="login" size={17} /> Conectar Google
                  </button>

                  <div style={{ display: 'flex', gap: 10 }}>
                    <button className="btn btn-outline" onClick={loadGoogleLocations} style={{ flex: 1, justifyContent: 'center' }}>
                      <Icon name="list" size={17} /> Listar unidades
                    </button>
                    <button className="btn btn-outline" onClick={syncGoogle} style={{ flex: 1, justifyContent: 'center' }}>
                      <Icon name="sync" size={17} /> Sincronizar
                    </button>
                  </div>

                  {loadingGoogleLocations ? (
                    <div style={{ fontSize: 12.5, color: 'var(--on-surface-variant)' }}>Carregando unidades do Google…</div>
                  ) : googleLocations.length ? (
                    <div>
                      <label style={{ display: 'block', fontSize: 12.5, fontWeight: 700, marginBottom: 8 }}>Unidade (Location)</label>
                      <select value={settings.location_name || ''} onChange={e => setSettings({ ...settings, location_name: e.target.value })} style={{ width: '100%', padding: '12px 16px', borderRadius: 10, border: '1.5px solid var(--outline-variant)', background: 'var(--surface-container-low)' }}>
                        <option value="">Selecione…</option>
                        {googleLocations.map((l, idx) => (
                          <option key={idx} value={l.location_name}>{l.title || l.location_name}</option>
                        ))}
                      </select>
                      <button className="btn btn-primary" onClick={saveGoogleLocation} style={{ width: '100%', justifyContent: 'center', marginTop: 12 }}>
                        <Icon name="save" size={17} /> Salvar unidade
                      </button>
                    </div>
                  ) : null}
                </>
              ) : configItem.nome === 'Booking.com' ? (
                <>
                  <div style={{ padding: 14, borderRadius: 12, background: 'var(--surface-container-low)', fontSize: 13, color: 'var(--on-surface-variant)', lineHeight: 1.55 }}>
                    Requer credenciais de <b>Connectivity Partner (Review API)</b>. Após conectar, sincronize as avaliações e responda pelo módulo Reputação.
                  </div>

                  <div>
                    <label style={{ display: 'block', fontSize: 12.5, fontWeight: 700, marginBottom: 8 }}>Property ID</label>
                    <input type="text" value={settings.property_id || ''} onChange={e => setSettings({ ...settings, property_id: e.target.value })} style={{ width: '100%', padding: '12px 16px', borderRadius: 10, border: '1.5px solid var(--outline-variant)', background: 'var(--surface-container-low)' }} />
                  </div>
                  <div>
                    <label style={{ display: 'block', fontSize: 12.5, fontWeight: 700, marginBottom: 8 }}>Machine account username</label>
                    <input type="text" value={settings.username || ''} onChange={e => setSettings({ ...settings, username: e.target.value })} style={{ width: '100%', padding: '12px 16px', borderRadius: 10, border: '1.5px solid var(--outline-variant)', background: 'var(--surface-container-low)' }} />
                  </div>
                  <div>
                    <label style={{ display: 'block', fontSize: 12.5, fontWeight: 700, marginBottom: 8 }}>Machine account password</label>
                    <input type="password" value={settings.password || ''} onChange={e => setSettings({ ...settings, password: e.target.value })} style={{ width: '100%', padding: '12px 16px', borderRadius: 10, border: '1.5px solid var(--outline-variant)', background: 'var(--surface-container-low)' }} />
                  </div>

                  <div style={{ display: 'flex', gap: 10 }}>
                    <button className="btn btn-primary" onClick={connectBooking} style={{ flex: 1, justifyContent: 'center' }}>
                      <Icon name="add_link" size={17} /> Conectar
                    </button>
                    <button className="btn btn-outline" onClick={syncBooking} style={{ flex: 1, justifyContent: 'center' }}>
                      <Icon name="sync" size={17} /> Sincronizar
                    </button>
                  </div>
                </>
              ) : (
                <>
                  <div>
                    <label style={{ display: 'block', fontSize: 12.5, fontWeight: 700, marginBottom: 8 }}>ID da Propriedade / API Key</label>
                    <input
                      type="text"
                      value={settings.apiKey || ""}
                      onChange={e => setSettings({ ...settings, apiKey: e.target.value })}
                      placeholder="Ex: 123456789"
                      style={{ width: '100%', padding: '12px 16px', borderRadius: 10, border: '1.5px solid var(--outline-variant)', background: 'var(--surface-container-low)' }}
                    />
                  </div>
                  <div>
                    <label style={{ display: 'block', fontSize: 12.5, fontWeight: 700, marginBottom: 8 }}>Token de Acesso / Secret</label>
                    <input
                      type="password"
                      value={settings.token || ""}
                      onChange={e => setSettings({ ...settings, token: e.target.value })}
                      placeholder="••••••••••••"
                      style={{ width: '100%', padding: '12px 16px', borderRadius: 10, border: '1.5px solid var(--outline-variant)', background: 'var(--surface-container-low)' }}
                    />
                  </div>
                </>
              )}
            </div>

            <div style={{ display: 'flex', gap: 12 }}>
              <button className="btn btn-outline" onClick={() => setConfigItem(null)} style={{ flex: 1, justifyContent: 'center' }}>Fechar</button>
              {configItem.nome !== 'Google' && configItem.nome !== 'Booking.com' && (
                <button className="btn btn-primary" onClick={saveIntegration} style={{ flex: 1, justifyContent: 'center' }}>Salvar Conexão</button>
              )}
            </div>
          </Card>
        </div>
      )}

      <Card pad={18} style={{ marginBottom: 18, background: 'linear-gradient(90deg, rgba(46, 125, 50, 0.10), rgba(125, 82, 255, 0.08))' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <div style={{ width: 44, height: 44, borderRadius: 12, background: 'rgba(125, 82, 255, 0.18)', display: 'grid', placeItems: 'center' }}>
              <Icon name="storage" size={22} style={{ color: 'var(--on-surface)' }} />
            </div>
            <div>
              <div className="font-headline" style={{ fontSize: 14.5, fontWeight: 800, marginBottom: 2 }}>Neon DB (Postgres)</div>
              <div style={{ fontSize: 12.5, color: 'var(--on-surface-variant)' }}>
                {neon.loading
                  ? 'Verificando conexão…'
                  : neon.ok && neon.db
                    ? `Conectado${typeof neon.hotels === 'number' ? ` · ${neon.hotels} hotéis no banco` : ''}`
                    : 'Sem conexão (execute o servidor local)'}
              </div>
            </div>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            {neon.ok && neon.db
              ? <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 11, fontWeight: 800, color: 'var(--primary)', background: 'var(--secondary-container)', padding: '6px 12px', borderRadius: 999 }}><Icon name="check_circle" size={14} fill={1} />Online</span>
              : <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 11, fontWeight: 800, color: 'var(--on-surface-variant)', background: 'var(--surface-container-high)', padding: '6px 12px', borderRadius: 999 }}><Icon name="cloud_off" size={14} />Offline</span>}
            <button className="btn btn-outline" style={{ fontSize: 13, padding: '10px 14px' }} onClick={() => window.location.reload()}>
              <Icon name="refresh" size={16} /> Atualizar
            </button>
          </div>
        </div>
      </Card>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 18, marginBottom: 22 }}>
        <Stat label="Integrações ativas" value={totalOn} icon="link" accent="var(--primary)" />
        <Stat label="PMS compatíveis" value="50+" icon="hub" accent="var(--secondary)" />
        <Stat label="OTAs & canais" value="8" icon="public" accent="#caa53a" />
      </div>

      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 20 }}>
        <Segmented options={tabs} value={tab} onChange={setTab} />
        <div style={{ display: "flex", alignItems: "center", gap: 8, background: "var(--surface-container-low)", borderRadius: 999, padding: "9px 16px" }}>
          <Icon name="search" size={17} style={{ color: "var(--on-surface-variant)" }} />
          <span style={{ fontSize: 13, color: "var(--on-surface-variant)" }}>Buscar integração…</span>
        </div>
      </div>

      <div style={{ display: "flex", flexDirection: "column", gap: 28 }}>
        {visible.map((c, ci) => (
          <div key={ci}>
            <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 14 }}>
              <h3 className="font-headline" style={{ margin: 0, fontSize: 16, fontWeight: 800 }}>{c.cat}</h3>
              <span style={{ fontSize: 12, fontWeight: 700, color: "var(--on-surface-variant)", background: "var(--surface-container-high)", borderRadius: 999, padding: "2px 10px" }}>{c.items.length}</span>
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 16 }}>
              {c.items.map((it, i) => {
                const on = isConnected(it.nome);
                const dbItem = dbIntegrations.find(di => di.name === it.nome);
                
                return (
                  <Card key={i} pad={20} style={it.more ? { borderStyle: "dashed", background: "var(--surface-container-low)" } : {}}>
                    <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", marginBottom: 14 }}>
                      <div style={{ width: 44, height: 44, borderRadius: 12, background: it.more ? "var(--surface-container-high)" : it.cor, display: "grid", placeItems: "center", color: "#fff", flexShrink: 0 }}>
                        {it.more ? <Icon name="grid_view" size={22} style={{ color: "var(--on-surface-variant)" }} /> : <span className="font-headline" style={{ fontSize: 19, fontWeight: 800 }}>{it.nome[0]}</span>}
                      </div>
                      {!it.more && (on
                        ? <span style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 11, fontWeight: 700, color: "var(--primary)", background: "var(--secondary-container)", padding: "5px 11px", borderRadius: 999 }}><Icon name="check_circle" size={13} fill={1} />Conectado</span>
                        : <span style={{ fontSize: 11, fontWeight: 700, color: "var(--on-surface-variant)", background: "var(--surface-container-high)", padding: "5px 11px", borderRadius: 999 }}>Disponível</span>)}
                    </div>
                    <div className="font-headline" style={{ fontSize: 15, fontWeight: 800, marginBottom: 4 }}>{it.nome}</div>
                    <div style={{ fontSize: 12.5, color: "var(--on-surface-variant)", lineHeight: 1.45, marginBottom: 16, minHeight: 34 }}>{it.desc}</div>
                    {it.more
                      ? <button className="btn btn-outline" style={{ width: "100%", justifyContent: "center", fontSize: 13, padding: "10px 16px" }}>Ver catálogo</button>
                      : <button 
                          className={on ? "btn btn-outline" : "btn btn-primary"} 
                          onClick={() => {
                            setConfigItem({...it, tag: c.tag});
                            setSettings(dbItem?.settings || {});
                          }}
                          style={{ width: "100%", justifyContent: "center", fontSize: 13, padding: "10px 16px" }}
                        >
                          {on ? <><Icon name="settings" size={16} /> Gerenciar</> : <><Icon name="add_link" size={16} /> Conectar</>}
                        </button>}
                  </Card>
                );
              })}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}
window.ViewIntegrations = ViewIntegrations;
