import React, { FC, useState, useEffect, useContext } from "react";
import axios from "axios";
import classNames from "classnames";
import Button from "./bootstrap/Button";
import AuthContext, { useAuth } from "../contexts/authContext";
import { Apis } from "../constants/Apis";
import showNotificationCustom from "./extras/showNotificationCustom";

interface IStopWatcherProps {
  vsUser: any;
}

const Stopwatch =  ({ vsUser }: IStopWatcherProps) => {

  const {userData} = useContext(AuthContext);
  
  // state to store time
  const [time, setTime] = useState(0);

  // state to check stopwatch running or not
  const [isRunning, setIsRunning] = useState(false);

  // State to change the stop and start text
  const stopWatchText = isRunning ? 'Stop timer and save prayer count' : 'Start a prayer session (minimum 15 minutes)';

  useEffect(() => {
    let intervalId: string | number | NodeJS.Timeout | undefined;
    if (isRunning) {
      // setting time from 0 to 1 every 10 milisecond using javascript setInterval method
      intervalId = setInterval(() => setTime(time + 1), 10);
    }

    return () => clearInterval(intervalId);
  }, [isRunning, time]);

  // Hours calculation
  const hours = Math.floor(time / 360000);

  // Minutes calculation
  const minutes = Math.floor((time % 360000) / 6000);

  // Seconds calculation
  const seconds = Math.floor((time % 6000) / 100);

  // Milliseconds calculation
  const milliseconds = time % 100;

  // Method to start and stop timer
  const startAndStopPraying = () => {
    if (!isRunning && time === 0) {
      setIsRunning(!isRunning);
      return;
    }

    if (isRunning && minutes < 2) {
      showNotificationCustom('Notice', 'Each prayer session has a minimum of 15 minutes', 'info', 'center');
      return;
    }

    if (isRunning && minutes >= 2) {
      setIsRunning(!isRunning)
      reset();
      savePrayerTime()
      console.log(time)
      console.log(minutes)
      return;
    }
     
  };
  
  // Method to reset timer back to 0
  const reset = () => {
    setTime(0);
  };

  // Save Prayed minutes to database
  const savePrayerTime = async () => {
		const payload = {
			firstname: userData?.firstname,
			lastname: userData?.lastname,
			email: userData?.email,
			minutes: minutes,
			virtual_space: vsUser.username
		}

		try {
      const response = await axios.post(`${Apis.BASE_URL}/onebillion_minutes`, payload);

			if (response.data.success) {
				console.log(response.data.data)
				showNotificationCustom('Success', response.data.message.text, 'success', 'center')

			} else {}
      
    } catch (error) {
      console.error(error);
    } finally {
    }
	}


  return (
    <>
      <Button
        className={classNames('fle-text-white fle-width-350', {'fle-bg-pink': !isRunning, 'fle-teal-coral-gradient': isRunning,})}
        rounded={2}
        type='button'onClick={() => startAndStopPraying()}
      >
        {stopWatchText}
      </Button>

      {isRunning && (
        <div className="stopwatch-container">
          <p className="stopwatch-time">
            {minutes.toString().padStart(2, "0")}: {seconds.toString().padStart(2, "0")}: {milliseconds.toString().padStart(2, "0")}
          </p>
        </div>
      )}
      
      
    </>
  );
};

export default Stopwatch;