import { useQuery } from "@tanstack/react-query";
import Header from "../../Components/Header/Header";
import styles from "../../styles";
import { EquipmentInstancesAPI } from "../../Components/API/API";
import { 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 EditItemModal from "../../Components/EditItemInstanceModal/EditItemInstanceModal";
import { useState } from "react";
import Popup from "reactjs-popup";
import Autocomplete from "@mui/material/Autocomplete";
import SearchIcon from "@mui/icons-material/Search";




export default function EquipmentInstancesListPage() {
  const [editmodalOpen, SetEditModalOpen] = useState(false);
  const [selectedItem, SetSelectedItem] = useState(0);


  const equipment_instances = useQuery({
    queryKey: ["equipment_instances"],
    queryFn: EquipmentInstancesAPI,
  });
  const [filter, setFilter] = useState<string | null>(null);
  if (equipment_instances.isLoading) {
    return (
      <div style={styles.background}>
        <Header label={"Dashboard"} />
        <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={"Items List"} />
      <div
        style={{
          ...styles.flex_column,
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          height: "100%",
          width: "100%",
          minHeight: "100%",
          minWidth: "100%",
          marginTop: "7rem"
        }}
      >
       
       

     
   

        <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={["Available", "Broken", "Glassware", "Miscellaneous"]}
            renderInput={(params) => (
              <div ref={params.InputProps.ref}>
                <input type="text" {...params.inputProps} />
              </div>
            )}
          />
          <p
            style={{
              ...styles.text_M,
              ...styles.text_dark,
              ...{ marginLeft: "4px" },
            }}
          >
            Results Found:{" "}
            {
              equipment_instances?.data?.filter((equipment) =>
                filter !== null
                  ? // If filter is not null, we filter if it matches any criteria
                    equipment.equipment_name
                      .toLowerCase()
                      .includes(filter.toLowerCase()) ||
                    equipment.category
                      .toLowerCase()
                      .includes(filter.toLowerCase()) ||
                    equipment.last_updated
                      .toLowerCase()
                      .includes(filter?.toLowerCase()) ||
                    equipment.status.toLowerCase() == filter.toLowerCase()
                  : // If filter keyword is null then we just pass through everything as if we did not filter at all
                    true
              ).length
            }
          </p>
        </div>
        <div style={{ alignSelf: "flex-start", paddingLeft: "32px" }}></div>
        <TableContainer
          style={{ width: "90%", overflowY: "scroll", marginTop: "2rem" }}
          component={Paper}
        >
          <Table sx={{ 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}>
                  Name
                </TableCell>
                <TableCell align="center" style={styles.text_light}>
                  Status
                </TableCell>
                <TableCell align="center" style={styles.text_light}>
                  Category
                </TableCell>
                <TableCell align="center" style={styles.text_light}>
                  Last Modified
                </TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {equipment_instances.data ? (
                equipment_instances.data
                  .filter((equipment) =>
                    filter !== null
                      ? // If filter is not null, we filter if it matches any criteria
                        equipment.equipment_name
                          .toLowerCase()
                          .includes(filter.toLowerCase()) ||
                        equipment.category
                          .toLowerCase()
                          .includes(filter.toLowerCase()) ||
                        equipment.last_updated
                          .toLowerCase()
                          .includes(filter?.toLowerCase()) ||
                        equipment.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((equipment) => (
                    <TableRow
                      key={equipment.id}
                      sx={{ "&:last-child td, &:last-child th": { border: 0 } }}
                      onClick={() => {
                        SetSelectedItem(equipment.id);
                        SetEditModalOpen(true);
                      }}
                    >
                      <TableCell align="center" component="th" scope="row">
                        {equipment.id}
                      </TableCell>
                      <TableCell align="center" component="th" scope="row">
                        {equipment.equipment_name}
                      </TableCell>

                      <TableCell align="center" component="th" scope="row">
                        {equipment.status}
                      </TableCell>
                      <TableCell align="center" component="th" scope="row">
                        {equipment.category}
                      </TableCell>
                      <TableCell align="right">
                        <div
                          style={{
                            ...styles.flex_column,
                            ...{ alignItems: "center" },
                          }}
                        >
                          <div>{equipment.last_updated}</div>
                          <div>
                            {equipment.last_updated_by
                              ? "by " + equipment.last_updated_by
                              : ""}
                          </div>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))
              ) : (
                <></>
              )}
            </TableBody>
          </Table>
        </TableContainer>
      </div>
      <Popup
        open={editmodalOpen}
        onClose={() => SetEditModalOpen(false)}
        modal
        position={"top center"}
        contentStyle={styles.popup_center}
      >
        <EditItemModal id={selectedItem} setOpen={SetEditModalOpen} />
      </Popup>
    </div>
  );
}
