import { Typography } from "@material-tailwind/react";
import { useEffect, useRef, useState } from "react";

import { _useScopedI18n } from "../i18n/client";

export type ServerTimeProps = {
  className?: string;
  overrideClass?: boolean;
};

export type TimerType = {
  hours: string;
  minutes: string;
  seconds: string;
};

export default function ServerTime({
  className,
  overrideClass,
}: ServerTimeProps) {
  //
  const scopeT = _useScopedI18n("sharedComponents.serverTime");

  const timerInterval = useRef<NodeJS.Timeout | undefined>(undefined);

  const [time, setTime] = useState<TimerType>({
    hours: `00`,
    minutes: `00`,
    seconds: `00`,
  });

  useEffect(() => {
    timerInterval.current = setInterval(async () => {
      const now = new Date();
      const hours = now.getUTCHours().toString().padStart(2, "0");
      const minutes = now.getUTCMinutes().toString().padStart(2, "0");
      const seconds = now.getUTCSeconds().toString().padStart(2, "0");
      setTime({
        hours,
        minutes,
        seconds,
      });
    }, 1000);

    return () => timerInterval.current && clearInterval(timerInterval.current);
  }, []);

  return (
    <>
      <Typography
        variant="h6"
        className={
          !overrideClass
            ? `flex flex-row text-xs font-medium text-center text-black-400 bg-gray-50 py-3 md:py-2.5 px-4 rounded-xl justify-center whitespace-nowrap ${className}`
            : className
        }
      >
        {scopeT("title")} :
        <div className="flex">
          <span className="w-5 text-center">{time.hours}</span>:
          <span className="w-5 text-center">{time.minutes}</span>:
          <span className="w-5 text-center mr-1">{time.seconds}</span>
        </div>{" "}
        UTC
      </Typography>
    </>
  );
}
