import { useQuery } from "@tanstack/react-query";
import Header from "../../Components/Header/Header";
import styles from "../../styles";
import { TransactionsAPI } from "../../Components/API/API";
import { Autocomplete, CircularProgress } from "@mui/material";
import Table from "@mui/material/Table";
import TableBody from "@mui/material/TableBody";
import TableCell from "@mui/material/TableCell";
import TableContainer from "@mui/material/TableContainer";
import TableHead from "@mui/material/TableHead";
import TableRow from "@mui/material/TableRow";
import Paper from "@mui/material/Paper";
import { colors } from "../../styles";
import Popup from "reactjs-popup";
import { useState } from "react";
import EditTransactionModal from "../../Components/EditTransactionModal/EditTransactionModal";
import EditItemInstanceModal from "../../Components/EditItemInstanceModal/EditItemInstanceModal";
import SearchIcon from "@mui/icons-material/Search";

export default function TransactionsListPage() {
  const [EditTransactionOpen, SetEditTransactionOpen] = useState(false);
  const [SelectedTransaction, SetSelectedTransaction] = useState(0);
  const [EditEquipmentsOpen, SetEditEquipmentsOpen] = useState(false);
  const [SelectedEquipment, SetSelectedEquipment] = useState(0);
  const [filter, setFilter] = useState<string | null>(null);
  const transactions = useQuery({
    queryKey: ["transactions"],
    queryFn: TransactionsAPI,
  });
  if (transactions.isLoading) {
    return (
      <div style={styles.background}>
        <Header label={"Transactions"} />
        <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={"Transactions"} />
      <div
        style={{
          ...{
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            height: "100%",
            width: "100%",
            minHeight: "100%",
            minWidth: "100%",
            flexWrap: "wrap",
          },
          ...styles.flex_column,
        }}
      >
        <TableContainer
          style={{ width: "90%", overflowY: "scroll", marginTop: "2rem" }}
          component={Paper}
        >
          <div
            style={{
              ...styles.flex_row,
              ...{ alignItems: "center", justifySelf: "flex-start" },
            }}
          >
            <SearchIcon
              style={{
                height: 32,
                width: 32,
                fill: colors.font_dark,
                marginLeft: "1rem",
                marginRight: "1rem",
              }}
            />
            <Autocomplete
              sx={{
                display: "inline-block",
                "& input": {
                  width: "256x",
                  bgcolor: "background.paper",
                  color: (theme) =>
                    theme.palette.getContrastText(
                      theme.palette.background.paper
                    ),
                },
              }}
              value={filter}
              onChange={(_event, newValue) => {
                setFilter(newValue);
              }}
              freeSolo
              id="custom-input-demo"
              options={[
                "Pending Approval",
                "Approved",
                "Rejected",
                "Cancelled",
                "Borrowed",
                "Returned: Pending Checking",
                "With Breakages: Pending Resolution",
                "Finalized",
              ]}
              renderInput={(params) => (
                <div ref={params.InputProps.ref}>
                  <input type="text" {...params.inputProps} />
                </div>
              )}
            />
          </div>
          <Table sx={{ marginTop: "8px", minWidth: "32rem" }} size="medium">
            <TableHead>
              <TableRow style={{ backgroundColor: colors.header_color }}>
                <TableCell align="center" style={styles.text_light}>
                  ID
                </TableCell>
                <TableCell align="center" style={styles.text_light}>
                  Borrower
                </TableCell>
                <TableCell align="center" style={styles.text_light}>
                  Teacher
                </TableCell>
                <TableCell align="center" style={styles.text_light}>
                  Status
                </TableCell>
                <TableCell align="center" style={styles.text_light}>
                  Remarks
                </TableCell>
                <TableCell align="center" style={styles.text_light}>
                  Equipments
                </TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {transactions.data ? (
                transactions.data
                  .filter((transaction) =>
                    filter !== null
                      ? // If filter is not null, we filter if it matches any criteria
                        transaction.borrower.name
                          .toLowerCase()
                          .includes(filter.toLowerCase()) ||
                        transaction.teacher.name
                          .toLowerCase()
                          .includes(filter.toLowerCase()) ||
                        transaction.remarks
                          .toLowerCase()
                          .includes(filter?.toLowerCase()) ||
                        transaction.transaction_status.toLowerCase() ==
                          filter.toLowerCase()
                      : // If filter keyword is null then we just pass through everything as if we did not filter at all
                        true
                  )
                  .map((transaction) => (
                    <TableRow
                      key={transaction.id}
                      sx={{ "&:last-child td, &:last-child th": { border: 0 } }}
                    >
                      <TableCell
                        align="center"
                        component="th"
                        scope="row"
                        onClick={() => {
                          if (
                            transaction.transaction_status != "Finalized" &&
                            transaction.transaction_status != "Rejected"
                          ) {
                            SetSelectedTransaction(transaction.id);
                            SetEditTransactionOpen(true);
                          }
                        }}
                      >
                        {transaction.id}
                      </TableCell>
                      <TableCell
                        align="center"
                        component="th"
                        scope="row"
                        onClick={() => {
                          if (
                            transaction.transaction_status != "Finalized" &&
                            transaction.transaction_status != "Rejected"
                          ) {
                            SetSelectedTransaction(transaction.id);
                            SetEditTransactionOpen(true);
                          }
                        }}
                      >
                        {transaction.borrower.name}
                      </TableCell>
                      <TableCell
                        align="center"
                        component="th"
                        scope="row"
                        onClick={() => {
                          if (
                            transaction.transaction_status != "Finalized" &&
                            transaction.transaction_status != "Rejected"
                          ) {
                            SetSelectedTransaction(transaction.id);
                            SetEditTransactionOpen(true);
                          }
                        }}
                      >
                        {transaction.teacher.name}
                      </TableCell>
                      <TableCell
                        align="center"
                        component="th"
                        scope="row"
                        onClick={() => {
                          if (
                            transaction.transaction_status != "Finalized" &&
                            transaction.transaction_status != "Rejected"
                          ) {
                            SetSelectedTransaction(transaction.id);
                            SetEditTransactionOpen(true);
                          }
                        }}
                      >
                        {transaction.transaction_status}
                      </TableCell>
                      <TableCell
                        align="center"
                        component="th"
                        scope="row"
                        style={{ ...styles.text_S }}
                        sx={{
                          maxWidth: "64px",
                          flexWrap: "wrap",
                          wordWrap: "break-word",
                        }}
                        onClick={() => {
                          if (
                            transaction.transaction_status != "Finalized" &&
                            transaction.transaction_status != "Rejected"
                          ) {
                            SetSelectedTransaction(transaction.id);
                            SetEditTransactionOpen(true);
                          }
                        }}
                      >
                        {transaction.remarks}
                      </TableCell>
                      <TableCell align="center">
                        <TableContainer
                          style={{
                            maxHeight: "256px",
                            overflowY: "scroll",
                          }}
                          component={Paper}
                        >
                          <Table
                            sx={{
                              minWidth: "4rem",
                            }}
                            size="medium"
                          >
                            <TableHead>
                              <TableRow
                                style={{ backgroundColor: colors.header_color }}
                              >
                                <TableCell
                                  align="center"
                                  style={styles.text_light}
                                >
                                  ID
                                </TableCell>
                                <TableCell
                                  align="center"
                                  style={styles.text_light}
                                >
                                  Name
                                </TableCell>
                                <TableCell
                                  align="center"
                                  style={styles.text_light}
                                >
                                  Status
                                </TableCell>
                              </TableRow>
                            </TableHead>
                            <TableBody
                              sx={{ height: "4px", overflowY: "scroll" }}
                            >
                              {transaction.equipments.map((equipment) => (
                                <TableRow
                                  key={equipment.id}
                                  sx={{
                                    "&:last-child td, &:last-child th": {
                                      border: 0,
                                    },
                                  }}
                                  onClick={() => {
                                    if (
                                      transaction.transaction_status ==
                                      "With Breakages: Pending Resolution"
                                    ) {
                                      SetSelectedEquipment(equipment.id);
                                      SetEditTransactionOpen(false);
                                      SetEditEquipmentsOpen(true);
                                    }
                                  }}
                                >
                                  <TableCell
                                    align="center"
                                    component="th"
                                    scope="row"
                                  >
                                    {equipment.id}
                                  </TableCell>
                                  <TableCell
                                    align="center"
                                    component="th"
                                    scope="row"
                                  >
                                    {equipment.name}
                                  </TableCell>
                                  <TableCell
                                    align="center"
                                    component="th"
                                    scope="row"
                                  >
                                    {equipment.status}
                                  </TableCell>
                                </TableRow>
                              ))}
                            </TableBody>
                          </Table>
                        </TableContainer>
                      </TableCell>
                    </TableRow>
                  ))
              ) : (
                <></>
              )}
            </TableBody>
          </Table>
        </TableContainer>
      </div>
      <Popup
        open={EditTransactionOpen}
        onClose={() => SetEditTransactionOpen(false)}
        modal
        position={"top center"}
        contentStyle={styles.popup_center}
      >
        <EditTransactionModal
          id={SelectedTransaction}
          setOpen={SetEditTransactionOpen}
        />
      </Popup>
      <Popup
        open={EditEquipmentsOpen}
        onClose={() => SetEditEquipmentsOpen(false)}
        modal
        position={"top center"}
        contentStyle={styles.popup_center}
      >
        <EditItemInstanceModal
          id={SelectedEquipment}
          setOpen={SetEditEquipmentsOpen}
        />
      </Popup>
    </div>
  );
}
