import { useEffect, useState } from "react";
import { useRouter } from 'next/router'
import { Container, Card, Row, Col, Form, FormGroup, Label, Input, Alert } from "reactstrap";
import styles from "./Login.module.scss";
import Link from "next/link";
import { Button } from "reactstrap";
import { login, getUser } from "../../../lib/requests";

export default function Login({ data }) {
  const router = useRouter()
  const [loginState, setLoginState] = useState({
    username: "",
    password: "",
  });
  const [isVisibleErrorMessage, setIsVisibleErrorMessage] = useState(false);
  const [errorMessage, setErrorMessage] = useState(null)
  const [loggedInUser, setLoggedInUser] = useState(null)

  useEffect(async () => {
    setLoggedInUser(await getUser())
  }, [])


  async function loginUser() {
    let response = await login(loginState)
    if (response) {
      router.push("/")
    } else {
      setErrorMessage("Invalid Credentials")
      setIsVisibleErrorMessage(true)
    }
  }

  if (loggedInUser) {
    router.push("/")
  }

  const onDismiss = () => setIsVisibleErrorMessage(false);

  function isValidData() {
    return (loginState.username && loginState.password)
  }

  return (
    <>
      <Container>
        <Card className={styles.card}>
          {errorMessage ? (
            <Alert color="danger" isOpen={isVisibleErrorMessage} toggle={onDismiss}>
              {errorMessage}
            </Alert>
          ) : (undefined)}
          <Form className="mt-2">
            <FormGroup>
              <Label for="username">
                Username
              </Label>
              <Input
                id="username"
                name="username"
                placeholder="Username"
                type="text"
                onChange={(event) => setLoginState({ ...loginState, username: event.target.value })}
              />
            </FormGroup>
            <FormGroup className="mt-2">
              <Label for="password">
                Password
              </Label>
              <Input
                id="password"
                name="password"
                placeholder="Password"
                type="password"
                onChange={(event) => setLoginState({ ...loginState, password: event.target.value })}
              />
            </FormGroup>
            <Row>
              <Col xs={12}>
              {isValidData() ? (
                <Button className={`my-2 mx-2 float-end ${styles.signInButton}`} onClick={loginUser}>
                  Sign in
                </Button>): (
                  <Button className={`my-2 mx-2 float-end ${styles.signInButton}`} disabled>
                    Sign in
                  </Button>
                )}
                <Link href="/register">
                  <Button className={`my-2 float-end ${styles.signUpButton}`} onClick={loginUser}>
                    Sign up
                  </Button>
                </Link>
              </Col>
            </Row>
          </Form>
        </Card>
      </Container >
    </>

  );
}
