import './App.css';
import './login'
import Login from './login.js';
import Home from './Home.js';
import React, { useState, useEffect } from 'react'

// MUI imports
import Typography from '@mui/material/Typography';
import Toolbar from '@mui/material/Toolbar';
import AppBar from '@mui/material/AppBar';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import Divider from '@mui/material/Divider';
import Grid from '@mui/material/Grid';

import CollectionList from './collection_list';
import CollectionEditor from './collection_editor';
import { dbGetCollections, dbGetItems } from './database_util';


function App() {
  const [foo, setFoo] = useState('');
  const [authenticated, setAuthenticated] = useState(false);
  const [username, setUsername] = useState(""); //test_user
  const [password, setPassword] = useState(""); //CETSp@ssword!

  useEffect(() => {
    // Check if user is already authenticated from sessionStorage
    const isAuthenticated = sessionStorage.getItem('authenticated');
    if (isAuthenticated === 'true') {
        setAuthenticated(true);
    }
  }, []);

  useEffect(() => {
    if (authenticated) {
        // If user is authenticated, save the state in sessionStorage
        sessionStorage.setItem('authenticated', 'true');
    } else {
        // If user is not authenticated, remove the state from sessionStorage
        sessionStorage.removeItem('authenticated');
    }
  }, [authenticated]);

  const [loadedCollections, setLoadedCollections] = useState([]);
  const [selectedCollection, setSelectedCollection] = useState(null);
  
  const [loadedRawFiles, setLoadedRawFiles] = useState([]);
  const [loadedLinkFiles, setLoadedLinkFiles] = useState([]);
  const [loadedXMLFiles, setLoadedXMLFiles] = useState([]);

  const [collectionFileCache, setCollectionFileCache] = useState(null);

  const updateCollectionList = async () => {
    let r = await dbGetCollections(0);
    setLoadedCollections(r)
  }

  const updateFileLists = async () => {
    let r = await dbGetItems(selectedCollection.collection_id);
    setLoadedRawFiles(r)
  }

  useEffect(
    () => {
      updateCollectionList();
    },[]
  );

  useEffect(
    () => {
    },[loadedRawFiles,loadedLinkFiles,loadedXMLFiles]
  );

  useEffect(
    () => {
      console.log("Updated loaded collections",loadedCollections);
    },[loadedCollections]
  );
  
  useEffect(
    () => {
      console.log("collectionFileCache Changed: ", collectionFileCache);
    },[collectionFileCache]
  );
  
  useEffect(
    () => {
      console.log("update: selectedCollection");
      if (selectedCollection != null){
        updateFileLists();
      }
    },[selectedCollection]
  );

  const showEditor= () => {
    if (selectedCollection == null) {
      return (<Home></Home>); // Landing page
    } else {
      return (<CollectionEditor collection={selectedCollection} onCollectionUpdate={setSelectedCollection} onFileSelect={onFileChange} loadedRawFiles={loadedRawFiles}/>);
    }
  }

  const onFileSelect = async (e) => {
    var formData = new FormData();
    formData.append(e.target.files[0].name, e.target.files[0]);
    setCollectionFileCache(formData); 
  }

  const onFileChange = async (e) => {
    var formData = new FormData();
    formData.append(e.target.files[0].name, e.target.files[0]);

    await fetch('http://127.0.0.1:5000//api/v1/upload_raw_text?collection=0', {
    // content-type header should not be specified!
      method: 'POST',
      body: formData,
    })
    .then(response => response.json())
    .then(success => {
      console.log(success)
      // Do something with the successful response
    })
    .catch(error => console.log(error)
  );

  updateFileLists();
  }

  const handleDeletedCollection = () => {
    setSelectedCollection(null);
    showEditor();
  }

  const logoutFunction = () => {
    setAuthenticated(false);
    sessionStorage.setItem('authenticated', 'false');
  };

  if (!authenticated) {
    return (
      <div
        style={{
          backgroundImage: 'url(/images/login_background.jpg)',
          backgroundSize: 'cover',
          backgroundPosition: 'center',
          minHeight: '100vh',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center'
        }}
      >
        <Login
          username={username}
          password={password}
          authenticated={authenticated}
          setUsername={setUsername}
          setPassword={setPassword}
          setAuthenticated={setAuthenticated}
          setFoo={setFoo}
        ></Login>
      </div>
    )
  }

  return (
    <div className="App">
      <Box sx={{paddingTop: '50px', paddingLeft: '30px'}}>
        {/* <Box sx={{textAlign:"left", padding:3}}> */}
          <AppBar>
            <Toolbar>
              <Button 
                style={{border: '1px solid white', color: 'white', width: '100px'}}
                onClick={() => {
                  setSelectedCollection(null);
                  showEditor();
                }}
              >
                Home
              </Button>
              <Typography variant="h6" component="div" sx={{ flexGrow: 1, textAlign: 'center' }}>
                Crisis Events Text Summarization (CETS)
              </Typography>
              <Button 
                style={{border: '1px solid white', color: 'white', width: '100px'}}
                onClick={logoutFunction}
              >
                Logout
              </Button>
            </Toolbar>
          </AppBar>
          <br/>
        {/* </Box> */}
        
        <Divider orientation="horizontal" flexItem />

        {/* <Box sx={{border: '1px dashed grey', padding:1}}> */}
          <Grid container spacing={2}>
            <Grid item xs={2}>
              <CollectionList collections={loadedCollections} onSelectCollection={setSelectedCollection} onListUpdate={updateCollectionList} onFileSelect={onFileSelect} collectionFileCache={collectionFileCache} onDeletedCollection={handleDeletedCollection}/>
            </Grid>
            <Grid item xs={10}>
              {
                showEditor()
              }
            </Grid>
          </Grid>
        {/* </Box> */}
      </Box>
    </div>
  );
}

export default App;