import type { User } from 'oidc-client-ts';
import { useEffect, useState } from 'react';
import './App.css';
import { getUser, handleCallback, login, logout } from './auth/authService';
import { Map } from './components/Map';
import { Parameters } from './components/Parameters';

function App() {
  const [listingData, setListingData] = useState({});
  const [user, setUser] = useState<User | null>(null);

  useEffect(() => {
    // Check if this is a callback from Authentik (after login)
    if (window.location.pathname === '/callback') {
      handleCallback().then(() => {
        window.location.href = '/'; // Redirect to home after login
      });
      return;
    }

    // Load user data
    getUser().then(setUser);
  }, []);


  return (
    <>
      <div>
        <h1>React + Authentik OIDC</h1>
        {user ? (
          <div>
            <p>Welcome, {user.profile.email}!</p>
            <button onClick={logout}>Logout</button>
          </div>
        ) : (
          <button onClick={login}>Login with Authentik</button>
        )}
      </div>
      {/* <div>
        <a href="https://vite.dev" target="_blank">
          <img src={viteLogo} className="logo" alt="Vite logo" />
        </a>
        <a href="https://react.dev" target="_blank">
          <img src={reactLogo} className="logo react" alt="React logo" />
        </a>
      </div>
      <h1>Vite + React</h1>
      <div className="card">
        <button onClick={() => setCount((count) => count + 1)}>
          count is {count}
        </button>
        <p>
          Edit <code>src/App.tsx</code> and save to test HMR
        </p>
      </div>
      <p className="read-the-docs">
        Click on the Vite and React logos to learn more
      </p> */}

      {/* <link href='https://api.mapbox.com/mapbox-gl-js/v3.12.0/mapbox-gl.css' rel='stylesheet' /> */}
      <Parameters setListingData={setListingData} />
      {Object.keys(listingData).length > 0 &&

        <div style={{ width: '100%' }}>
          <Map listingData={listingData} />
        </div>
      }
    </>
  )
}

export default App
