import { useEffect, useState } from "react";
import styles from "../../styles";
import { colors } from "../../styles";
import TextField from "@mui/material/TextField";
import AddToQueueIcon from "@mui/icons-material/AddToQueue";
import Button from "../../Components/Button/Button";
import { toast } from "react-toastify";
import {
  AvailableEquipmentInstancesAPI,
  TransactionCreateAPI,
  TeachersAPI,
  UserAPI,
} from "../../Components/API/API";
import FormControl from "@mui/material/FormControl";
import FormLabel from "@mui/material/FormLabel";
import { useQueryClient } from "@tanstack/react-query";
import { useQuery } from "@tanstack/react-query";
import {
  Select,
  CircularProgress,
  MenuItem,
  OutlinedInput,
} from "@mui/material";
import React from "react";
import Header from "../../Components/Header/Header";
import { useNavigate } from "react-router-dom";

export default function AddTransactionPage() {
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const [transaction, SetTransaction] = useState({
    equipments: [] as number[],
    teacher: 0,
    subject: "",
    remarks: " ",
    transaction_status: "Pending Approval",
    consumables: " ",
    additional_members: " ",
    borrower: 0,
  });
  /*
  const [selecteditems, SetSelectedItems] = useState<number[]>([]);
  const [selectedteacher, SetSelectedTeacher] = useState<number>(0);
  const [subject, SetSubject] = useState("");
  const [remarks, SetRemarks] = useState("");
  const [consumables, SetConsumables] = useState("");
  */
  const [error, setError] = useState("");

  const equipments = useQuery({
    queryKey: ["equipment_instances_available"],
    queryFn: AvailableEquipmentInstancesAPI,
  });

  const teachers = useQuery({
    queryKey: ["teachers"],
    queryFn: TeachersAPI,
  });

  const user = useQuery({
    queryKey: ["user"],
    queryFn: UserAPI,
  });

  useEffect(() => {
    if (user.data) {
      SetTransaction({ ...transaction, borrower: user.data.id });
    }

    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [user.data]);
  const isLoading =
    equipments.isLoading || teachers.isLoading || user.isLoading;

  if (isLoading) {
    return (
      <div style={styles.background}>
        <Header label={"New Transaction"} />
        <div
          style={{
            ...styles.flex_column,
            ...{
              alignItems: "center",
              justifyContent: "center",
              paddingTop: "64px",
            },
          }}
        >
          <CircularProgress style={{ height: "128px", width: "128px" }} />
          <p
            style={{
              ...styles.text_dark,
              ...styles.text_L,
            }}
          >
            Loading
          </p>
        </div>
      </div>
    );
  }
  return (
    <div style={styles.background}>
      <Header label={"New Transaction"} />
      <div
        style={{
          ...styles.flex_row,
          ...{
            alignItems: "center",
            justifyContent: "center",
            overflowY: "scroll",
          },
        }}
      >
        <AddToQueueIcon
          style={{
            height: 64,
            width: 64,
            fill: colors.font_dark,
            marginLeft: "1rem",
            marginRight: "1rem",
          }}
        />
        <p style={{ ...styles.text_dark, ...styles.text_L }}>Borrowing Form</p>
      </div>

      <div style={{...styles.flex_column, marginLeft: "1rem", marginRight: "1rem"}}>
        <FormControl style={{ marginTop: "8px" }}>
          <FormLabel style={{...styles.text_dark, ...styles.bform_label2}}>Items Requested</FormLabel>
          <Select
            multiple
            value={transaction.equipments}
            onChange={(event) =>
              SetTransaction({
                ...transaction,
                equipments: event.target.value as number[],
              })
            }
            input={<OutlinedInput />}
          >
            {equipments.data
              ?.filter((equipment) => equipment.status == "Available")
              .map((equipment) => (
                <MenuItem key={equipment.id} value={equipment.id}>
                  {`${equipment.equipment_name} (ID:${equipment.id})`}
                </MenuItem>
              ))}
          </Select>
        </FormControl>
        <FormControl style={{ marginTop: "8px" }}>
          <FormLabel style={{...styles.text_dark, ...styles.bform_label2}}>Assigned Teacher</FormLabel>
          <Select
            value={transaction.teacher}
            onChange={(event) =>
              SetTransaction({
                ...transaction,
                teacher: event.target.value as number,
              })
            }
            label={"Assigned Teacher"}
            input={<OutlinedInput />}

          >
            {teachers.data?.map((teacher) => (
              <MenuItem key={teacher.id} value={teacher.id}>
                {`${teacher.first_name} ${teacher.last_name}`}
              </MenuItem>
            ))}
          </Select>
        </FormControl>
        <FormControl style={{ marginTop: "8px" }}>
          <FormLabel style={{...styles.text_dark, ...styles.bform_label}}>Subject</FormLabel>
          <TextField
            style={styles.input_form}
            onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
              SetTransaction({ ...transaction, subject: e.target.value });
              setError("");
            }}
            value={transaction.subject}
            placeholder={"The subject requiring the equipments"}
          />
        </FormControl>
        <FormControl style={{ marginTop: "8px" }}>
          <FormLabel style={{...styles.text_dark, ...styles.bform_label}}>Remarks</FormLabel>
          <TextField
            multiline
            style={styles.input_form}
            onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
              SetTransaction({ ...transaction, remarks: e.target.value });
              setError("");
            }}
            value={transaction.remarks}
            placeholder={"Optionally add a brief description of the request"}
          />
        </FormControl>
        <FormControl style={{ marginTop: "8px" }}>
          <FormLabel style={{...styles.text_dark, ...styles.bform_label}}>Consumables</FormLabel>
          <TextField
            multiline
            style={styles.input_form}
            onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
              SetTransaction({ ...transaction, consumables: e.target.value });
              setError("");
            }}
            value={transaction.consumables}
            placeholder={"Write down any consumables here"}
          />
        </FormControl>
        <FormControl style={{ marginTop: "8px" }}>
          <FormLabel style={{...styles.text_dark, ...styles.bform_label}}>Additional Members</FormLabel>
          <TextField
            multiline
            style={styles.input_form}
            onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
              SetTransaction({
                ...transaction,
                additional_members: e.target.value,
              });
              setError("");
            }}
            value={transaction.additional_members}
            placeholder={
              "Write down any additional members borrowing on behalf of this transaction"
            }
          />
        </FormControl>
      </div>
      <p style={{ ...styles.text_dark, ...styles.text_M }}>{error}</p>
      <div
        style={{
          backgroundColor: colors.button_border,
          marginTop: "16px",
          width: "100%",
          height: "2px",
          marginBottom: 8,
        }}
      />
      <Button
        type={"dark"}
        label={"Create Transaction"}
        onClick={async () => {
          console.log(JSON.stringify(transaction));
          const data = await TransactionCreateAPI(transaction);
          if (data[0]) {
            setError("Created successfully");
            toast(
              `New transaction created successfuly,  ${
                typeof data[1] == "object" ? "ID:" + data[1].id : ""
              }`,
              {
                position: "top-right",
                autoClose: 2000,
                hideProgressBar: false,
                closeOnClick: true,
                pauseOnHover: true,
                draggable: true,
                progress: undefined,
                theme: "light",
              }
            );
            queryClient.invalidateQueries({
              queryKey: ["equipment_instances"],
            });
            queryClient.invalidateQueries({
              queryKey: ["transactions"],
            });
            navigate("/dashboard");
          } else {
            setError(JSON.stringify(data[1]));
          }
        }}
      />
    </div>
  );
}
