import * as React from "react";
import Box from "@mui/material/Box";
import Grid from "@mui/material/Grid2";
import Typography from "@mui/material/Typography";
import Slider, { SliderThumb } from "@mui/material/Slider";
import { inputProps } from "../interface/inputfieldProps";
import { DataContext } from "../context/Context";
import { TextField } from "@mui/material";
import { useEffect } from "react";

const CustomThumb = ({ children, theme, ...rest }) => (
  <SliderThumb {...rest}>
    {children}
    <Box
      className="circleRing"
      sx={{
        width: "24px",
        height: "24px",
        backgroundColor: "transparent",
        border: `3.5px solid ${theme.palette.primary.dark}`,
        borderRadius: "50%",
      }}
    />
  </SliderThumb>
);

export default function InputSlider(props: inputProps) {
  const {
    required,
    errors,
    data,
    uischema,
    handleChange,
    path,
    schema,
    rootSchema,
  } = props;

  const uischemaData = uischema?.config?.main;

  const min = Number(uischemaData.min);
  const max = Number(uischemaData.max);
  const step = Number(uischemaData.step);

  const [sliderValue, setSliderValue] = React.useState<number>(
    Number(data) || min
  );
  const [textValue, setTextValue] = React.useState<string>(
    data?.toString() || min?.toString()
  );

  useEffect(() => {
    if(data)
    setSliderValue(Number(data));
    setTextValue(data?.toString());
  }, [data]);

  const { theme } = React.useContext(DataContext);

  const onTextFieldChange = (event: any, newValue: string) => {
    if (+event.target.value <= +uischemaData.max) {
      setTextValue(newValue);
      throttledFunction(Number(newValue));
    }
  };
  function throttle(fn: any, delay: any) {
    let timer: any;
    return function (...args) {
      clearTimeout(timer);
      timer = setTimeout(() => fn(...args), delay);
    };
  }
  const throttledFunction = throttle((value: number) => {
    handleChange(path, value);
  }, 100);

  const marks = [
    {
      value: min,
      label: min,
    },
    {
      value: max,
      label: max,
    },
  ];

  return (
    <Box sx={{}}>
      <Grid
        container
        sx={{
          flexDirection: "row",
          justifyContent: "space-between",
          padding: "0px 12px",
        }}
      >
        <Typography
          sx={{
            fontWeight: 500,
            marginBottom: 0,
            fontFamily: "calibri",
          }}
          id="input-slider"
          gutterBottom
        >
          {uischemaData.label}
        </Typography>
        <Grid flexDirection={"row"} display={"flex"}>
          <Grid
            sx={{
              padding: "4px",
              lineHeight: 1,
              color: theme.myTheme.palette.primary.dark,
              fontWeight: 500,
            }}
          >
            Value:{" "}
          </Grid>
          <Grid
            sx={{
              padding: "0px 2px 0px 2px",
              borderRadius: "5px",
              border: `1px solid ${theme.myTheme.palette.grey[400]}`,
              backgroundColor: theme.myTheme.palette.grey[200],
              lineHeight: 1,
              color: theme.myTheme.palette.primary.dark,
              fontWeight: 500,
            }}
          >
            <TextField
              value={textValue}
              onChange={(e) => {
                onTextFieldChange(e, e.target.value);
              }}
              type="number"
              variant="outlined"
              size="small"
              sx={{
                width: `${(textValue || '').length + 3}ch`,
                backgroundColor: "transparent",
                borderRadius: "5px",
                "& input": {
                  color: theme.myTheme.palette.primary.dark,
                  padding: "0px 0px 0px 4px",
                },
                "& .MuiOutlinedInput-root": {
                  "& fieldset": {
                    border: "none",
                  },
                },
              }}
            />
          </Grid>
        </Grid>
      </Grid>
      <Grid
        container
        sx={{
          gap: 3,
          alignItems: "center",
          justifyContent: "center",
          paddingLeft: "12px",
          paddingRight: "10px",
        }}
      >
        <Grid size="grow">
          <Slider
            sx={{
              "& .MuiSlider-rail": {
                height: "3px",
                color: theme.myTheme.palette.grey[300],
                opacity: 1,
              },
              "& .MuiSlider-track": {
                height: "3px",
                color: theme.myTheme.palette.primary.dark,
              },
              "& .MuiSlider-mark": {
                width: "12px",
                height: "12px",
                backgroundColor: theme.myTheme.palette.grey[300],
                borderRadius: "50%",
                transform: "translate(-50%, -50%)",
              },
              "& .MuiSlider-markLabel": {
                fontSize: "14px",
                fontWeight: "medium",
                color: theme.myTheme.palette.grey[600],
                opacity: 1,
              },
              "& .MuiSlider-markActive": {
                backgroundColor: theme.myTheme.palette.primary.dark,
                opacity: 1,
              },
              "& .MuiSlider-thumb": {
                width: "32px",
                height: "32px",
                backgroundColor: theme.myTheme.palette.grey[200],
                boxShadow: "none",
                "&:hover, &:focus-visible": {
                  boxShadow: "none",
                  "& .circleRing": {
                    width: "25px",
                    height: "25px",
                  },
                },
                "&.Mui-active": {
                  boxShadow: "none",
                  "& .circleRing": {
                    width: "25px",
                    height: "25px",
                  },
                },
                "&.Mui-focusVisible": {
                  boxShadow: "none",
                  "& .circleRing": {
                    width: "25px",
                    height: "25px",
                  },
                },
              },
              "& .Mui-focusVisible": {
                boxShadow: "none",
              },
              ...uischemaData?.style,
            }}
            step={step || 50}
            min={min || 0}
            max={max || 1000}
            value={Math.min(
              Math.max(sliderValue, min || 0),
              max || 10000
            )}
            onChange={(e, newValue ) => {
              setSliderValue(newValue as number);
              setTextValue(newValue.toString());
            }}
            onChangeCommitted={() => throttledFunction(sliderValue)} 
            aria-labelledby="input-slider"
            marks={marks}
            slots={{
              thumb: (props) => (
                <CustomThumb {...props} theme={theme.myTheme} />
              ),
            }}
          ></Slider>
        </Grid>
      </Grid>
    </Box>
  );
}
