import Box from "@mui/material/Box";
import { EditableValue } from "./EditableValue";
import {
  strikePercentageFromUnderlyingPrice,
  strikePercentageFromUnderlyingPriceRadius,
} from "./state";
import Slider from "@mui/material/Slider";
import { refreshSimilarCalendarPriceChartData } from "./actions";

function StrikePercentageFromUnderlyingPriceChooser() {
  return (
    <Slider
      fullWidth
      label="Strike % From Underlying Price"
      value={strikePercentageFromUnderlyingPrice.value}
      valueLabelDisplay="on"
      min={0}
      max={10}
      step={1}
      onChange={(e, value) => {
        strikePercentageFromUnderlyingPrice.value = value as number;
      }}
      onChangeCommitted={(e, value) => {
        refreshSimilarCalendarPriceChartData();
      }}
      InputProps={{ endAdornment: "%" }}
    />
  );
}

function StrikePercentageFromUnderlyingPriceRadiusChooser() {
  return (
    <Slider
      fullWidth
      label="Strike % Radius"
      value={strikePercentageFromUnderlyingPriceRadius.value}
      valueLabelDisplay="on"
      min={0}
      max={10}
      step={1}
      onChange={(e, value) => {
        strikePercentageFromUnderlyingPriceRadius.value = value as number;
      }}
      onChangeCommitted={(e, value) => {
        refreshSimilarCalendarPriceChartData();
      }}
      InputProps={{ endAdornment: "%" }}
    />
  );
}

/** This is its own component so that sliding the slider with the mouse is
 * smoother. Preact detects reads from the "slider" signal values, and
 * associates them with the component that read them and redraws that component.
 * If this was not its own component, it would redraw the entire UI. It was very
 * slow. */
export function EditableStrike() {
  return (
    <EditableValue
      text={`${strikePercentageFromUnderlyingPrice.value.toFixed(
        1
      )}±${strikePercentageFromUnderlyingPriceRadius.value.toFixed(2)}`}
    >
      <Box sx={{ minWidth: "20em" }}>
        <StrikePercentageFromUnderlyingPriceChooser />
        <StrikePercentageFromUnderlyingPriceRadiusChooser />
      </Box>
    </EditableValue>
  );
}
