import { useRef, useState } from "react";
import style from "./LearningResources.module.css";
import ContentWrapper from "../ContentWrapper/ContentWrapper";

const Card = ({
  item,
  handleChangeLeft,
  handleChangeRight,
  color1,
  color2,
}) => {
  const videoRef = useRef(null);
  const [isPlay, setIsPlay] = useState(false);

  const handlePlayPause = () => {
    if (videoRef.current) {
      if (isPlay) {
        videoRef.current.pause(); // Pause the video
        setIsPlay(false);
      } else {
        videoRef.current.play(); // Play the video
        setIsPlay(true);
      }
    }
  };

  return (
    <div className={style.flex}>
      <div style={{ flex: 1 }}>
        <div className={style.audio}>
          {item.type === "video" ? (
            <video
              ref={videoRef}
              width={"100%"}
              poster={item.poster}
              height="auto"
              controls
              controlsList="nodownload"
            >
              <source src={item.source} type="video/mp4" />
            </video>
          ) : (
            <img src={item.source} width={"100%"} alt={item.title} />
          )}
        </div>
      </div>
      <div className={style.ml}>
        <div className={style.button_main} style={{ color: color1 }}>
          <button onClick={handleChangeLeft}>
            <i class="fa fa-chevron-left" style={{ color: color1 }} />
          </button>
          <strong>0{item.index + 1}</strong>/04
          <button onClick={handleChangeRight}>
            <i class="fa fa-chevron-right" style={{ color: color1 }} />
          </button>
        </div>
        <h4 className={style.heading4} style={{ color: color1 }}>
          {item.title}
        </h4>
        <p style={{ color: color1, marginTop: "-6px" }}>{item.description}</p>
        <button
          style={{
            background: color1 === "#e0ffdf" ? "rgb(22, 60, 20)" : color1,
            color: color2,
            fontSize: "14px",
            borderRadius: "10px",
            margin: "20px 0px",
          }}
          onClick={handlePlayPause}
        >
          Watch Now &nbsp;
          <i class="fa fa-arrow-right" />
        </button>
      </div>
    </div>
  );
};

export default function LearningResources({ data, color1, color2 }) {
  const [number, setNumber] = useState(0);
  const handleChangeLeft = () => {
    if (number < 1) {
      setNumber(3);
    } else {
      setNumber(number - 1);
    }
  };
  const handleChangeRight = () => {
    if (number > 2) {
      setNumber(0);
    } else {
      setNumber(number + 1);
    }
  };
  return (
    <ContentWrapper>
      {data.map((item) => (
        <div>
          {item.index === number ? (
            <Card
              item={item}
              handleChangeLeft={handleChangeLeft}
              handleChangeRight={handleChangeRight}
              color1={color1}
              color2={color2}
            />
          ) : null}
        </div>
      ))}
    </ContentWrapper>
  );
}
