import React, {
  // useEffect,
  useState} from 'react';
import { Link as RouterLink } from 'react-router-dom';
import {useNavigate} from 'react-router-dom';
// material-ui
import {
  Button,
  //Checkbox,
  //Divider,
  //FormControlLabel,
  FormHelperText,
  Grid,
  Link,
  IconButton,
  InputAdornment,
  InputLabel,
  OutlinedInput,
  Stack,
  Typography
} from '@mui/material';

// third party
import * as Yup from 'yup';
import { Formik } from 'formik';

// project import
//import FirebaseSocial from './FirebaseSocial';
import AnimateButton from 'components/@extended/AnimateButton';

// assets
import { EyeOutlined, EyeInvisibleOutlined } from '@ant-design/icons';
// import axios from "axios";
import iAmSmartICon from 'assets/images/icons/icon_iAmSmart.png';
import {useDispatch} from "react-redux";
import {handleLogin} from "auth/index";
import useJwt from "../../../auth/jwt/useJwt";

// ============================|| FIREBASE - LOGIN ||============================ //

const AuthLoginCustom = () => {
  const dispatch = useDispatch()
  const navigate = useNavigate()

  const [showPassword, setShowPassword] = useState(false);
  const handleClickShowPassword = () => {
    setShowPassword(!showPassword);
  };

  // let [posts, setPosts] = useState([]);
  let [userName, setUserName] = useState(null);
  let [userPassword, setUserPassword] = useState(null);

  // useEffect(() => {
  //   // console.log("POST: " + posts.accessToken);
  // },[posts]);

  const handleMouseDownPassword = (event) => {
    event.preventDefault();
  };

  const tryLogin = () => {
    useJwt
      .login({username: userName, password: userPassword})
      .then((response) => {
        const userData = {
          id: response.data.id,
          fullName: response.data.name,
          email: response.data.email,
          role: response.data.role,
          abilities: response.data.abilities,
          //avatar: require('src/assets/images/users/avatar-3.png').default,
        }
        const data = {...userData, accessToken: response.data.accessToken, refreshToken: response.data.refreshToken}
        dispatch(handleLogin(data))
        //const abilities = response.data.abilities
        //ability.update(abilities)
        navigate('/dashboard');
      })
      .catch((error) => {
        console.error(error)
      });
}



  const onUserNameChange = (event) => {
    setUserName(event.target.value);
  }

  const onPasswordChange = (event) => {
     setUserPassword(event.target.value);
  }

  return (
      <Formik
        initialValues={{
          username: '',
          password: '',
          submit: null
        }}
        validationSchema={Yup.object().shape({
          username: Yup.string().max(255).required('請輸入用戶名稱'),
          password: Yup.string().max(255).required('請輸入密碼'),
        })}
        onSubmit={async (values, { setErrors, setStatus, setSubmitting }) => {
          try {
            setStatus({ success: false });
            setSubmitting(false);
          } catch (err) {
            setStatus({ success: false });
            setErrors({ submit: err.message });
            setSubmitting(false);
          }
        }}
      >
        {({ errors, handleBlur, handleSubmit, isSubmitting, touched }) => (
          <form noValidate onSubmit={handleSubmit}>
            <Grid container spacing={3}>
              <Grid item xs={12}>
                <Stack spacing={1}>
                  <InputLabel htmlFor="email-login">用戶帳號或別名</InputLabel>
                  <OutlinedInput
                    id="username"
                    name="username"
                    onBlur={handleBlur}
                    onChange={onUserNameChange}
                    placeholder=""
                    fullWidth
                    error={Boolean(touched.email && errors.email)}
                  />
                  {touched.email && errors.email && (
                    <FormHelperText error id="standard-weight-helper-text-email-login">
                      {errors.email}
                    </FormHelperText>
                  )}
                </Stack>
              </Grid>
              <Grid item xs={12}>
                <Stack spacing={1}>
                  <InputLabel htmlFor="password-login">密碼</InputLabel>
                  <OutlinedInput
                    fullWidth
                    // error={Boolean(touched.password && errors.password)}
                    id="password-login"
                    type={showPassword ? 'text' : 'password'}
                    name="password"
                    // onBlur={handleBlur}
                    onChange={onPasswordChange}
                    endAdornment={
                      <InputAdornment position="end">
                        <IconButton
                          aria-label="toggle password visibility"
                          onClick={handleClickShowPassword}
                          onMouseDown={handleMouseDownPassword}
                          edge="end"
                          size="large"
                        >
                          {showPassword ? <EyeOutlined /> : <EyeInvisibleOutlined />}
                        </IconButton>
                      </InputAdornment>
                    }
                    placeholder=""
                  />
                  {/* {touched.password && errors.password && (
                    <FormHelperText error id="standard-weight-helper-text-password-login">
                      {errors.password}
                    </FormHelperText>
                  )} */}
                </Stack>
              </Grid>

              <Grid item xs={12}>
                <AnimateButton>
                  <Button disableElevation onClick={tryLogin}
                          disabled={isSubmitting} fullWidth size="large" type="submit" variant="contained" color="primary">
                    登錄
                  </Button>
                </AnimateButton>
              </Grid>
              <Grid item xs={12}>
                <Stack direction="row" justifyContent="space-between" alignItems="center" spacing={2}>
                  <Link variant="h6" component={RouterLink} to="" color="text.primary">
                    <Typography align="center">
                    忘記密碼?
                    </Typography> 
                  </Link>
                </Stack>
              </Grid>
              <Grid item xs={12}>
                <Stack direction="row" justifyContent="space-between" alignItems="center" spacing={2}>
                  <Button fullWidth size="large" variant="outlined" startIcon={<img src={iAmSmartICon} alt="iAM Smart" width="30" />}>智方便登入</Button>
                </Stack>
              </Grid>
              <Grid item xs={12}>
                <Stack direction="row" justifyContent="space-between" alignItems="center" spacing={2}>
                  <Link href="#">了解更多智方便</Link>
                </Stack>
              </Grid>
              <Grid item xs={12}>
                <Stack direction="row" justifyContent="space-between" alignItems="center" spacing={2}>
                  <Button fullWidth size="large" variant="outlined" href="/register" >建立/重新啟動帳戶</Button>
                </Stack>
              </Grid>
              {/* <Grid item xs={12}>*/}
              {/*  <Divider>*/}
              {/*    <Typography variant="caption"> Login with</Typography>*/}
              {/*  </Divider>*/}
              {/*</Grid>*/}
              {/*<Grid item xs={12}>*/}
              {/*  <FirebaseSocial />*/}
              {/*</Grid> */}
            </Grid>
          </form>
        )}
      </Formik>
  );
};

export default AuthLoginCustom;
