import React, { useState, useRef, useEffect } from "react";
import { ExitIcon, PlayStopIcon, ResetIcon } from "../../icons/SimulationIcons";
import {
  useActiveTool,
  useProcessBar,
  useViewSceneStore,
} from "../../../store/builder/store";
import {
  useAnimationPlaySpeed,
  usePauseButtonStore,
  usePlayButtonStore,
  useResetButtonStore,
} from "../../../store/usePlayButtonStore";
import {
  DailyProductionIcon,
  EndIcon,
  ExpandIcon,
  EyeCloseIcon,
  HourlySimulationIcon,
  InfoIcon,
  MonthlyROI,
  SpeedIcon,
  StartIcon,
} from "../../icons/ExportCommonIcons";
import { getAvatarColor } from "../../../modules/collaboration/functions/getAvatarColor";
import useModuleStore, {
  useSubModuleStore,
} from "../../../store/useModuleStore";
import ProductionCapacity from "../analysis/ThroughputSummary";
import ThroughputSummary from "../analysis/ProductionCapacity";
import ROISummary from "../analysis/ROISummary";
import { usePlayerStore } from "../../../store/useUIToggleStore";
import { useComparisonProduct } from "../../../store/simulation/useSimulationStore";
import InputToggle from "../inputs/InputToggle";

const SimulationPlayer: React.FC = () => {
  const MAX_SPEED = 8; // Maximum speed

  const isDragging = useRef(false);
  const sliderRef = useRef<HTMLDivElement>(null);
  const [expand, setExpand] = useState(true);
  const { hidePlayer, setHidePlayer } = usePlayerStore();

  const { speed, setSpeed } = useAnimationPlaySpeed();
  const { setIsPlaying } = usePlayButtonStore();
  const { setActiveTool } = useActiveTool();
  const { isPaused, setIsPaused } = usePauseButtonStore();
  const { isReset, setReset } = useResetButtonStore();
  const { subModule } = useSubModuleStore();
  const { clearComparisonProduct } = useComparisonProduct();
  const { viewSceneLabels, setViewSceneLabels } = useViewSceneStore();

  const { isPlaying } = usePlayButtonStore();
  const { activeModule } = useModuleStore();
  useEffect(() => {
    if (isReset) {
      setTimeout(() => {
        setReset(false);
      }, 0);
    }
  }, [isReset, setReset]);

  // Button functions
  const handleReset = () => {
    setReset(true);
    setIsPaused(false);
    setSpeed(1);
    echo.info("Simulation RESET.....");
  };
  const handlePlayStop = () => {
    setIsPaused(!isPaused);
    if (isPaused) {
      setIsPlaying(true);
    }
    echo.warn(`Simulation is ${isPaused ? "Resumed" : "Paused"}`);
  };
  const handleExit = () => {
    setIsPlaying(false);
    setIsPaused(false);
    clearComparisonProduct();
    setActiveTool("cursor");
    echo.info("Exit Simulation");
  };

  // Slider functions starts
  const handleSpeedChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setSpeed(parseFloat(event.target.value));
  };

  const calculateHandlePosition = () => {
    return ((speed - 0.5) / (MAX_SPEED - 0.5)) * 100;
  };

  const handleMouseDown = () => {
    isDragging.current = true;
  };

  const handleMouseMove = (e: MouseEvent) => {
    if (!isDragging.current || !sliderRef.current) return;

    const sliderRect = sliderRef.current.getBoundingClientRect();
    const offsetX = e.clientX - sliderRect.left;
    const percentage = Math.min(Math.max(offsetX / sliderRect.width, 0), 1);
    const newValue = 0.5 + percentage * (50 - 0.5);
    setSpeed(parseFloat(newValue.toFixed(1)));
  };

  const handleMouseUp = () => {
    isDragging.current = false;
  };

  const handleVisibility = () => {
    if (document.visibilityState !== 'visible' && isPlaying) {
      setIsPaused(!isPaused);
      if (isPaused) {
        setIsPlaying(true);
      }
      echo.warn(`Simulation is ${isPaused ? "Resumed" : "Paused"}`);
    }
  }

  useEffect(() => {
    document.addEventListener("mousemove", handleMouseMove);
    document.addEventListener("mouseup", handleMouseUp);
    document.addEventListener('visibilitychange', handleVisibility);
    return () => {
      document.removeEventListener("mousemove", handleMouseMove);
      document.removeEventListener("mouseup", handleMouseUp);
      document.removeEventListener('visibilitychange', handleVisibility);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  // Slider function ends

  // UI-Part
  const hourlySimulation = 25;
  const dailyProduction = 75;
  const monthlyROI = 10;
  const { processBar } = useProcessBar();

  useEffect(() => { }, [processBar]);

  const intervals = [50, 20, 30, 40, 50, 60]; // in minutes
  const totalSegments = intervals.length;
  const progress = 20; // percent (example)

  const processPlayerRef = useRef<HTMLDivElement>(null);
  const processWrapperRef = useRef<HTMLDivElement>(null);
  const [playerPosition, setPlayerPosition] = useState(20); // initial position

  const handleProcessMouseDown = (e: React.MouseEvent) => {
    if (!processWrapperRef.current) return;

    const rect = processWrapperRef.current.getBoundingClientRect();
    let x = e.clientX - rect.left;
    x = Math.max(0, Math.min(x, rect.width));
    setPlayerPosition(x);

    const onMouseMove = (e: MouseEvent) => {
      if (!processWrapperRef.current) return;
      const newRect = processWrapperRef.current.getBoundingClientRect();
      let newX = e.clientX - newRect.left;
      newX = Math.max(0, Math.min(newX, newRect.width));
      setPlayerPosition(newX);

      const progressPercent = (newX / newRect.width) * 100;
      console.log(`Dragging at progress: ${progressPercent.toFixed(1)}%`);
    };

    const onMouseUp = () => {
      document.removeEventListener("mousemove", onMouseMove);
      document.removeEventListener("mouseup", onMouseUp);
    };

    document.addEventListener("mousemove", onMouseMove);
    document.addEventListener("mouseup", onMouseUp);
  };

  return (
    <>
      {isPlaying && activeModule === "simulation" && (
        <div className="label-toogler "> {/* bottom */}
          <InputToggle
            value={viewSceneLabels}
            inputKey="1"
            label="Enable View Labels"
            onClick={() => setViewSceneLabels(!viewSceneLabels)}
          />
        </div>
      )}
      <div className={`simulation-player-wrapper${hidePlayer ? " hide" : ""}`}>
        <div className={`simulation-player-container ${expand ? "open" : ""}`}>
          <div className="controls-container">
            {!hidePlayer && subModule === "analysis" && (
              <div className="production-details">
                {/* hourlySimulation */}
                <div className="hourly-wrapper production-wrapper">
                  <div className="header">
                    <div className="icon">
                      <HourlySimulationIcon />
                    </div>
                    <h4 className="label">ThroughPut</h4>
                  </div>
                  <div className="progress-wrapper">
                    <div
                      className="progress"
                      style={{ width: hourlySimulation }}
                    ></div>
                  </div>
                </div>
                {/* dailyProduction */}
                <div className="dailyProduction-wrapper production-wrapper">
                  <div className="header">
                    <div className="icon">
                      <DailyProductionIcon />
                    </div>
                    <div className="label">Production Capacity</div>
                  </div>
                  <div className="progress-wrapper">
                    <div
                      className="progress"
                      style={{ width: dailyProduction }}
                    ></div>
                  </div>
                </div>
                {/* monthlyROI */}
                <div className="monthlyROI-wrapper production-wrapper">
                  <div className="header">
                    <div className="icon">
                      <MonthlyROI />
                    </div>
                    <div className="label">ROI</div>
                  </div>
                  <div className="progress-wrapper">
                    <div
                      className="progress"
                      style={{ width: `${monthlyROI}%` }}
                    ></div>
                  </div>{" "}
                </div>
              </div>
            )}
            {!hidePlayer && subModule !== "analysis" && (
              <div className="header">
                <InfoIcon />
                {isPaused ? "Paused - system idle." : "Running simulation..."}
              </div>
            )}
            <div className="controls-wrapper">
              {!hidePlayer && (
                <button
                  id="simulation-reset-button"
                  className="simulation-button-container"
                  onClick={() => {
                    handleReset();
                  }}
                >
                  <ResetIcon />
                  Reset
                </button>
              )}
              {!hidePlayer && (
                <button
                  id="simulation-play-button"
                  className="simulation-button-container"
                  onClick={() => {
                    handlePlayStop();
                  }}
                >
                  <PlayStopIcon />
                  {isPaused ? "Play" : "Stop"}
                </button>
              )}
              <button
                id="simulation-reset-button"
                className="simulation-button-container"
                onClick={() => {
                  handleExit();
                }}
              >
                <ExitIcon />
                {!hidePlayer && "Exit"}
              </button>
              <button
                id="simulation-reset-button"
                className="simulation-button-container"
                onClick={() => {
                  setHidePlayer(!hidePlayer);
                }}
              >
                <EyeCloseIcon />
                {!hidePlayer && "Hide"}
              </button>
              {subModule === "analysis" && (
                <button
                  id="simulation-expand-button"
                  className="expand-icon-container"
                  onClick={() => setExpand(!expand)}
                >
                  <ExpandIcon isActive={!expand} />
                </button>
              )}
            </div>
          </div>
          {!hidePlayer && (
            <div className="progresser-wrapper">
              <div className="time-displayer">
                <div className="start-time-wrappper">
                  <div className="icon">
                    <StartIcon />
                  </div>
                  <div className="time-wrapper">
                    <div className="date">23 April ,25</div>
                    <div className="time">04:41 PM</div>
                  </div>
                </div>
                <div className="time-progresser">
                  <div className="timeline">
                    {intervals.map((label, index) => {
                      const segmentProgress = (index / totalSegments) * 100;
                      const isFilled = progress >= segmentProgress;
                      return (
                        <React.Fragment key={`${index}-${label}`}>
                          <div className="label-dot-wrapper">
                            <div className="label">{label} mins</div>
                            <div
                              className={`dot ${isFilled ? "filled" : ""}`}
                            ></div>
                          </div>
                          {index < intervals.length - 1 && (
                            <div
                              className={`line ${progress >= ((index + 1) / totalSegments) * 100
                                ? "filled"
                                : ""
                                }`}
                            ></div>
                          )}
                        </React.Fragment>
                      );
                    })}
                  </div>
                </div>

                <div className="end-time-wrappper">
                  <div className="time-wrapper">
                    <div className="time">00:10:20</div>
                  </div>
                  <div className="icon">
                    <EndIcon />
                  </div>
                </div>
              </div>
              <div className="speed-control-container">
                <div className="min-value">
                  <div className="icon">
                    <SpeedIcon />
                  </div>
                  Speed
                </div>
                <div className="slider-container" ref={sliderRef}>
                  <div className="speed-label mix-value">0.5X</div>
                  <div className="marker marker-10"></div>
                  <div className="marker marker-20"></div>
                  <div className="marker marker-30"></div>
                  <div className="marker marker-40"></div>
                  <div className="marker marker-50"></div>
                  <div className="marker marker-60"></div>
                  <div className="marker marker-70"></div>
                  <div className="marker marker-80"></div>
                  <div className="marker marker-90"></div>
                  <div className="custom-slider-wrapper">
                    <div className="custom-slider">
                      <button
                        id="slider-handle"
                        className={`slider-handle ${isDragging ? "dragging" : ""
                          }`}
                        style={{ left: `${calculateHandlePosition()}%` }}
                        onMouseDown={handleMouseDown}
                      >
                        {speed.toFixed(1)}x
                      </button>
                      <input
                        type="range"
                        min="0.5"
                        max={MAX_SPEED}
                        step="0.1"
                        value={speed}
                        onChange={handleSpeedChange}
                        className="slider-input"
                      />
                    </div>
                    <div className="speed-label max-value">{MAX_SPEED}x</div>
                  </div>
                </div>
              </div>
            </div>
          )}
          {!hidePlayer && subModule === "analysis" && (
            <div className="processDisplayer">
              <div className="start-displayer timmer">00:00</div>
              <div className="end-displayer timmer">24:00</div>
              <div
                className="process-wrapper"
                style={{ padding: expand ? "0px" : "5px 35px" }}
              >
                {/* eslint-disable-next-line */}
                <div
                  className="process-container"
                  ref={processWrapperRef}
                  onMouseDown={handleProcessMouseDown}
                >
                  {processBar?.length > 0 ? (
                    processBar.map((item: any, index: any) => (
                      <div
                        key={`${index}-${item.name}`}
                        className="process"
                        style={{
                          width: `${item.completed}%`,
                          backgroundColor: getAvatarColor(index),
                        }}
                      >
                        <div
                          className="process-player"
                          ref={processPlayerRef}
                          style={{ left: playerPosition, position: "absolute" }}
                        ></div>
                      </div>
                    ))
                  ) : (
                    <div>No process data available</div>
                  )}
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
      {/* {subModule === "analysis" && ( */}
      {subModule === "analysis" && (
        <div className="analysis">
          <div className="analysis-wrapper">
            <ProductionCapacity />
            <ThroughputSummary />
          </div>
          <ROISummary />
        </div>
      )}
      {/* )} */}
    </>
  );
};

export default SimulationPlayer;
