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

const ManagePage = () => {
  const [courseData, setCourseData] = useState([]);
  const { currentUser } = useContext(UserContext);
  const [showAddCourseForm, setShowAddCourseForm] = useState(false);

  const AddCourseForm = () => {
    const [name, setName] = useState("");
    const [description, setDescription] = useState("");
    const [username, setUsername] = useState("");
    const [coursecode, setCoursecode] = useState("");

    const submitCourseForm = () => {
      makeRequest({
        endpoint: `course/${username}`,
        method: "POST",
        body: {
          course_code: coursecode,
          name,
          description,
        },
      })
        .then((resp) => resp.json())
        .then((data) => {
          window.location.reload();
        });
    };

    return (
      <div>
        <Form
          className="my-4 p-2 border justify-between items-center"
          onSubmit={(e) => {
            e.preventDefault();
            submitCourseForm();
          }}
        >
          <Form.Group controlId="courseCode">
            <Form.Label>Course code</Form.Label>
            <Form.Control
              type="text"
              placeholder="Enter course code"
              onChange={(e) => setCoursecode(e.target.value)}
            />
          </Form.Group>
          <Form.Group controlId="courseName">
            <Form.Label>Name</Form.Label>
            <Form.Control
              type="text"
              placeholder="Enter course name"
              onChange={(e) => setName(e.target.value)}
            />
          </Form.Group>
          <Form.Group controlId="courseDescription">
            <Form.Label>Description</Form.Label>
            <Form.Control
              type="text"
              placeholder="Enter course description"
              onChange={(e) => setDescription(e.target.value)}
            />
          </Form.Group>
          <Form.Group controlId="courseInstructor">
            <Form.Label>Instructor Username</Form.Label>
            <Form.Control
              type="text"
              placeholder="Instructor"
              onChange={(e) => setUsername(e.target.value)}
            />
          </Form.Group>
          <Button className="my-2" type="submit" variant="success">
            Submit
          </Button>
        </Form>
      </div>
    );
  };

  const sendDeleteCourseRequest = (cid) => {
    makeRequest({
      endpoint: `course/${cid}`,
      method: "DELETE",
    })
      .then((resp) => resp.json())
      .then((data) => {
        window.location.reload();
      });
  };

  useEffect(() => {
    makeRequest({
      endpoint: `user/${currentUser.id}/courses`,
      method: "GET",
    })
      .then((req) => req.json())
      .then((data) => {
        setCourseData(data.courses);
      })
      .catch((err) => {
        console.error(err);
      });
  }, []);

  return (
    <div>
      <MyNavbar />
      <Container className="p-5 border">
        <h1 className="mb-4">Manage Courses</h1>
        {currentUser.role === "admin" && (
          <Button
            className="my-3"
            variant="primary"
            onClick={() => {
              setShowAddCourseForm(!showAddCourseForm);
            }}
          >
            {(showAddCourseForm && "-") || "+"} Add course
          </Button>
        )}
        {showAddCourseForm && <AddCourseForm />}
        <Table bordered striped hover>
          <thead>
            <tr>
              <th>#</th>
              <th>Course Code</th>
              <th>Name</th>
              <th>Instructor</th>
              <th>Manage</th>
            </tr>
          </thead>
          <tbody>
            {courseData.map((course, k) => {
              return (
                <tr key={k}>
                  <td>{course.id}</td>
                  <td>{course.course_code}</td>
                  <td>{course.name}</td>
                  <td>{course.instructor}</td>
                  <td>
                    <div>
                      <Link href={`/manage/${course.id}/students`}>
                        Students
                      </Link>
                      <br />
                      <Link href={`/manage/${course.id}/content`}>
                        Course Content
                      </Link>
                      <br />
                      <Link href={`/manage/${course.id}/assignments`}>
                        Assignments
                      </Link>
                      {currentUser?.role === "admin" && (
                        <React.Fragment>
                          <br />
                          <Button
                            variant="danger"
                            onClick={() => sendDeleteCourseRequest(course.id)}
                          >
                            Delete
                          </Button>
                        </React.Fragment>
                      )}
                    </div>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </Table>
      </Container>
    </div>
  );
};

export default ManagePage;
