import React, { useState } from "react";
import ReactPlayer from "react-player";
import styles from "./styles.module.css";
import Loader from "@/components/Loader";
import PlayButton from "../../../../ui/PlayButton";
import PlayPauseButton from "../../../../ui/PlayPauseButton";
import { useDispatch, useSelector } from "react-redux";
import { actions, selectors } from "@/store";
import metricService, { EGoals, EMetrics } from "@/services/metric/metricService";

interface IPersonalVideoProps {
  gender: string;
  url: string;
  classNameContainer?: string;
  isVisibleControllers?: boolean;
  containerRef?: React.RefObject<HTMLDivElement>;
  isAutoPlay?: boolean;
  onVideoStart?: () => void;
}

const PersonalVideo = React.memo<IPersonalVideoProps>(
  ({
    url,
    gender,
    classNameContainer = "",
    isVisibleControllers = true,
    containerRef,
    isAutoPlay = true,
    onVideoStart,
  }) => {
    const dispatch = useDispatch();
    const { isVideoPlaying } = useSelector(selectors.selectPersonalVideo);
    const [isStarted, setIsStarted] = useState(false);
    const [isError, setIsError] = useState(false);

    const setIsPlaying = (isPlaying: boolean) => {
      dispatch(actions.personalVideo.updateIsVideoPlaying(isPlaying));
    };

    const onError = (error: unknown) => {
      if (!error) return;
      setIsError(true);
      setIsPlaying(false);
    };

    const onStart = () => {
      setIsStarted(true);
      setIsError(false);
      if (onVideoStart) onVideoStart();
      metricService.reachGoal(EGoals.ROSE_VIDEO_PLAY_START, [EMetrics.YANDEX, EMetrics.KLAVIYO]);
    };

    const onEnded = () => {
      metricService.reachGoal(EGoals.ROSE_VIDEO_PLAY_END, [EMetrics.YANDEX, EMetrics.KLAVIYO]);
    };

    const handlePlayPause = () => {
      setIsPlaying(!isVideoPlaying);
      if (isVideoPlaying)
        metricService.reachGoal(EGoals.ROSE_VIDEO_PLAY_USER_PLAY, [EMetrics.YANDEX, EMetrics.KLAVIYO]);
      if (!isVideoPlaying)
        metricService.reachGoal(EGoals.ROSE_VIDEO_PLAY_USER_STOP, [EMetrics.YANDEX, EMetrics.KLAVIYO]);
    };

    return (
      <div
        className={`${styles.container} ${classNameContainer}`}
        ref={containerRef}
      >
        {!isVideoPlaying && !isError && !isStarted && (
          <Loader className={styles.loader} />
        )}
        {isError && (
          <PlayButton
            backgroundFill={gender === "male" ? "#85B6FF" : "#D1ACF2"}
            className={styles["play-button"]}
            onClick={() => {
              setIsError(false);
              setIsPlaying(true);
            }}
          />
        )}
        <ReactPlayer
          url={url}
          controls={false}
          light={false}
          muted={false}
          playing={isVideoPlaying}
          stopOnUnmount={true}
          width="100%"
          onStart={onStart}
          onReady={() => setIsPlaying(isAutoPlay)}
          onEnded={onEnded}
          onError={onError}
          playsinline={true}
          height={"auto"}
          style={{
            aspectRatio: "16 / 9",
            position: "relative",
            zIndex: 1,
          }}
        />
        {!isError && isStarted && isVisibleControllers && (
          <PlayPauseButton
            state={isVideoPlaying ? "pause" : "play"}
            onClick={handlePlayPause}
            className={styles["play-pause-button"]}
          />
        )}
      </div>
    );
  }
);

export default PersonalVideo;
