import React, { useContext, useState } from 'react';
import {CommonMenuList, Headline} from '../component/mod';
import { Button, Dialog, DialogActions, DialogContent, DialogContentText,
     DialogTitle, MenuList, Paper, TextField, Typography, useTheme } from '@mui/material';
import { UserContext } from '../state';
import { useNavigate } from 'react-router-dom';
import {doLogin as doSessionLogin} from '../state';

export const LoginPage = ()=>{
    const theme = useTheme();
    const [userLoginInfo,setUserLoginInfo]= useState({username:"",password:""});
    const [openDialog,setOpenDialog] = useState({open:false,message:""});
    const {setUsername,setPermission} = useContext(UserContext);
    const navigate = useNavigate();
    const handleDialogClose = ()=>{
        setOpenDialog({...openDialog,open:false});
    }
    const doLogin = async ()=>{
        try{
            const b = await doSessionLogin(userLoginInfo);
            if(typeof b === "string"){
                setOpenDialog({open:true,message: b});
                return;
            }
            console.log(`login as ${b.username}`);
            setUsername(b.username);
            setPermission(b.permission);
        }
        catch(e){
            if(e instanceof Error){
                console.error(e);
                setOpenDialog({open:true,message:e.message});
            }
            else console.error(e);
            return;
        }
        navigate("/");
    }
    const menu = CommonMenuList();
    return <Headline menu={menu}>
        <Paper style={{ width: theme.spacing(40), padding: theme.spacing(4), alignSelf:'center'}}>
            <Typography variant="h4">Login</Typography>
            <div style={{minHeight:theme.spacing(2)}}></div>
        <form style={{display:'flex', flexFlow:'column', alignItems:'stretch'}}>
            <TextField label="username" onChange={(e)=>setUserLoginInfo({...userLoginInfo,username:e.target.value ?? "",})}></TextField>
            <TextField label="password" type="password"  onKeyDown={(e)=>{if(e.key === 'Enter') doLogin();}}
                onChange={(e)=>setUserLoginInfo({...userLoginInfo,password:e.target.value ?? "",})}/>
            <div style={{minHeight:theme.spacing(2)}}></div>
            <div style={{display:'flex'}}>
                <Button onClick={doLogin}>login</Button>
                <Button>signin</Button>
            </div>
        </form>
        </Paper>
        <Dialog open={openDialog.open}
            onClose={handleDialogClose}>
            <DialogTitle>Login Failed</DialogTitle>
            <DialogContent>
                <DialogContentText>detail : {openDialog.message}</DialogContentText>
            </DialogContent>
            <DialogActions>
                <Button onClick={handleDialogClose} color="primary" autoFocus>Close</Button>
            </DialogActions>
        </Dialog>
    </Headline>
}