import React, { useContext, useEffect, useState } from "react";
import { Button, Col, Container, Form, Row, Alert } from "react-bootstrap";
import { Link, useLocation } from "wouter";
import MyNavbar from "../components/MyNavbar";
import UserContext from "../contexts/UserContext";
import { makeRequest } from "../utils.ts";

const LoginPage = () => {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState(null);

  const { currentUser, setCurrentUser } = useContext(UserContext);
  const [location, setLocation] = useLocation();

  useEffect(() => {
    if (currentUser?.id) {
      gotoHome();
    }
  }, [currentUser]);

  const gotoHome = () => {
    setLocation("/");
  };

  const sendLoginRequest = async (e) => {
    e?.preventDefault();
    await makeRequest({
      url: "http://localhost:5000/login",
      method: "POST",
      body: { username, password },
    })
      .then((resp) => resp.json())
      .then((data) => {
        if (data.error) {
          setError(data);
          return;
        }
        setCurrentUser(data);
      });
  };

  return (
    <React.Fragment>
      <MyNavbar />
      <Container className="p-5">
        {error && (
          <Container>
            <Alert variant="danger" className="mx-auto w-50 text-center">
              {error.message}
            </Alert>
          </Container>
        )}
        <h2>Login</h2>
        <br />
        <Form onSubmit={sendLoginRequest}>
          <Form.Group as={Row} className="mb-3" controlId="username">
            <Form.Label column sm={2} className="me-2">
              Username
            </Form.Label>
            <Col sm={9}>
              <Form.Control
                type="username"
                placeholder="username"
                onChange={(e) => {
                  setUsername(e.target.value);
                }}
              />
            </Col>
          </Form.Group>
          <Form.Group as={Row} className="mb-3" controlId="password">
            <Form.Label column sm={2} className="me-2">
              Password
            </Form.Label>
            <Col sm={9}>
              <Form.Control
                type="password"
                placeholder="password"
                onChange={(e) => {
                  setPassword(e.target.value);
                }}
              />
            </Col>
          </Form.Group>
          <Form.Group as={Row} className="mb-3" controlId="submit">
            <Col sm={2}></Col>
            <Col sm={2}>
              <Button type="submit">Submit</Button>
            </Col>
          </Form.Group>
          <Form.Group as={Row}>
            <p>
              Don't have an account? <Link href="/register">Register here</Link>
            </p>
          </Form.Group>
        </Form>
      </Container>
    </React.Fragment>
  );
};

export default LoginPage;
