import React, { useState, useEffect } from 'react';
import { Box, VStack } from '@chakra-ui/react';
import Login from './components/Login';
import Chat from './components/Chat';

const App: React.FC = () => {
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [token, setToken] = useState('');

  useEffect(() => {
    const storedToken = localStorage.getItem('token');
    console.log('STORED', storedToken)
    if (storedToken) {
      setIsLoggedIn(true);
      setToken(storedToken);
    }
  }, []);

  const handleLogin = (newToken: string) => {
    setIsLoggedIn(true);
    setToken(newToken);
    console.log('NEW TOKEN', newToken)
    localStorage.setItem('token', newToken);
  };

  const handleLogout = () => {
    setIsLoggedIn(false);
    setToken('');
    localStorage.removeItem('token');
  };

  return (
    <>
      {!isLoggedIn ? (
        <Box minHeight="100vh" bg="gray.100">
          <VStack spacing={8} py={10}>
            <Login onLogin={handleLogin} />
          </VStack>
        </Box>
      ) : (
        <Chat token={token} onLogout={handleLogout} />
      )}
    </>
  );
};

export default App;