import { Box, Grid2, Theme, Tooltip, Typography } from "@mui/material";
import { blue, deepOrange, teal } from "@mui/material/colors";
import { makeStyles } from "@mui/styles";
import { Device } from "models";
import PulseBox from "./PulseBox";
import { or } from "utils";
import { useEffect, useState } from "react";

interface Props {
  device: Device
  // noDust?: boolean;
  gasType: "co2" | "co" | "no2" | "o2" | "all"
}

const useStyles = makeStyles((theme: Theme) => {
  const lightMode = theme.palette?.mode === "light";
  return ({
    box: {
      display: "inline-block",
      borderRadius: "6px",
      backgroundColor: lightMode ? "rgb(210, 210, 210)" : "rgb(50, 50, 50)",
      padding: theme.spacing(0.75),
      marginRight: "auto",
      margin: theme.spacing(1),
      width: theme.spacing(14),
      height: theme.spacing(6),
    },
    boxTall: {
      display: "inline-block",
      borderRadius: "6px",
      backgroundColor: lightMode ? "rgb(210, 210, 210)" : "rgb(50, 50, 50)",
      padding: theme.spacing(0.75),
      marginRight: "auto",
      margin: theme.spacing(1),
      width: theme.spacing(14),
      height: theme.spacing(8.5),
    },
    carouselContainer: {
      position: 'relative',
      height: '40px',
      overflow: 'hidden',
      textAlign: "center",
    },
    carouselItem: {
      opacity: 0,
      transform: 'translateX(100%)',
      transition: 'opacity 0.5s ease, transform 0.5s ease',
      position: 'absolute',
      width: '100%',
      overflow: "hidden",
      // height: '100%',
    },
    active: {
      opacity: 1,
      transform: 'translateX(0)',
    },
    inactive: {
      transform: 'translateX(-100%)',
    },
  })
})

export default function StatusGas(props: Props) {
  const { device, gasType } = props;
  const classes = useStyles()
  // console.log(noDust)
  let colors: string[] = []
  let messages: string[] = []
  if (gasType === "all") {
    colors = or(device.status.o2?.overlays.map(overlay => overlay.color), []);
    colors.push(...or(device.status.co2?.overlays.map(overlay => overlay.color), []));
    colors.push(...or(device.status.no2?.overlays.map(overlay => overlay.color), []));
    colors.push(...or(device.status.co?.overlays.map(overlay => overlay.color), []));
    messages = or(device.status.o2?.overlays.map(overlay => overlay.message), []);
    messages.push(...or(device.status.co2?.overlays.map(overlay => overlay.message), []));
    messages.push(...or(device.status.no2?.overlays.map(overlay => overlay.message), []));
    messages.push(...or(device.status.co?.overlays.map(overlay => overlay.message), []));
  } else {
    colors = or(device.status[gasType]?.overlays.map(overlay => overlay.color), []);
    messages = or(device.status[gasType]?.overlays.map(overlay => overlay.message), []);
  }

  const [color, setColor] = useState(colors.length > 0 ? colors[0] : "");
  const [, setColorIndex] = useState(0)

  const gasTypes: ("o2" | "no2" | "co2" | "co")[] = ["o2", "no2", "co2", "co"]

  useEffect(() => {
    const interval = setInterval(() => {
      setColorIndex(prevIndex => {
        const newIndex = prevIndex >= colors.length - 1 ? 0 : prevIndex + 1;
        setColor(colors[newIndex]); // Use the new index here
        return newIndex;
      });
    }, 7500);
    
    return () => clearInterval(interval);
  }, []);

  const [currentIndex, setCurrentIndex] = useState(0);

  // Auto-cycle through measurements every 5 seconds
  useEffect(() => {
    if (gasType !== "all") {
      setCurrentIndex(0)
      return
    }
    const interval = setInterval(() => {
      if (gasType === "all") setCurrentIndex((prevIndex) => (prevIndex + 1) % 4);
      else setCurrentIndex((prevIndex) => (prevIndex + 1) % 4);
    }, 6000); 

    return () => clearInterval(interval); // Cleanup on unmount
  }, [gasType]);

  const tooltip = () => {
    if (messages.length === 0) return null
    if (messages.length < 2) return (
      messages[0]
    )
    return (
      <Grid2 container direction={"column"}>
        <Grid2 container direction="row">
          <Typography fontWeight={"bold"} variant="caption">
            Overlay Messages
          </Typography>
        </Grid2>
        {messages.map((message, index) => {
          return (
            <Grid2 key={"tooltip-overly-message-" + message} container direction="row" alignContent={"center"}>
              <Grid2 size={{xs: 1}} alignContent={"center"}>
                <Box
                  sx={{
                    width: 12, // Size of the square
                    height: 12,
                    backgroundColor: colors[index], // Passed color prop
                    borderRadius: 3, // Optional: slight rounding, remove for sharp square
                    border: "1px solid black",
                    marginBottom: 0.4
                  }}
                />
              </Grid2>
              <Grid2 size={{ xs: 11 }} alignContent={"center"}>
                <Typography variant="caption">
                  {message}
                </Typography>
              </Grid2>
            </Grid2>
          )
        })}
      </Grid2>
    )
  }

  const gasDisplay = () => {
    const gas = gasType === "all" ? gasTypes[currentIndex] : gasType
    // if (gasType !== "all") {
    return (
      <Tooltip title={tooltip()}>
        <PulseBox color={color} className={gasType === "all" ? classes.boxTall : classes.box}>
          <Grid2 container direction="column" >
            { gasType === "all" &&
              <Typography variant="body2">
                {gas.toUpperCase()}
              </Typography>
            }
            <Grid2 container direction="column">
              <Grid2>
                {gas !== "o2" ? 
                  <Typography variant="body2" style={{ color: teal[500]}}>
                    Gas: {device.status[gas]?.ppm.toFixed(1)}ppm
                  </Typography>
                :
                  <Typography variant="body2" style={{ color: blue[500]}}>
                    Gas: {(device.status[gas]?.ppm!/10000).toFixed(1)}%
                  </Typography>
                }
              </Grid2>
              <Grid2>
                <Typography variant="body2" style={{ color: deepOrange[800]}}>
                  Volt: {device.status[gas]?.millivolts.toFixed(1)}mV
                </Typography>
              </Grid2>
            </Grid2>
          </Grid2>
        </PulseBox>
      </Tooltip>
    )
      
    // }
  }

  return (
    <>
      {gasDisplay()}
    </>
  )
}