import { useEffect, useState } from "react";
import styles from "./styles.module.css";
import { sleep } from "@/services/date";
import { useTranslations } from "@/hooks/translations";
import { ELocalesPlacement } from "@/locales";

interface IChatHeaderProps {
  name: string;
  avatar: string;
  classNameContainer?: string;
  hasBackButton?: boolean;
  isTimerGoing?: boolean;
  clickBackButton: () => void;
}

function ChatHeader({
  name,
  avatar,
  classNameContainer = "",
  hasBackButton = true,
  isTimerGoing = false,
  clickBackButton,
}: IChatHeaderProps) {
  const { translate } = useTranslations(ELocalesPlacement.Chats);
  const [timer, setTimer] = useState(0);

  useEffect(() => {
    (async () => {
      await sleep(1000);
      if (isTimerGoing) {
        setTimer(timer + 1);
      }
    })();
  }, [isTimerGoing, timer]);

  function formatSecondsToHHMMSS(seconds: number) {
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    const secs = seconds % 60;

    return [
      String(hours).padStart(2, "0"),
      String(minutes).padStart(2, "0"),
      String(secs).padStart(2, "0"),
    ].join(":");
  }

  return (
    <div className={`${styles.container} ${classNameContainer}`}>
      {hasBackButton && (
        <div className={styles["back-button"]} onClick={clickBackButton}>
          <div className={styles["arrow"]} /> Advisors
        </div>
      )}
      <div className={styles["name-wrapper"]}>
        <img className={styles.avatar} src={avatar} alt={name} />
        <div className={styles.name}>
          {name}
          <span className={styles["online-status"]} />
        </div>
      </div>
      <div className={styles["info-wrapper"]}>
        <button
          type="button"
          className={styles.button}
          onClick={clickBackButton}
        >
          {translate("/expert.end_chat")}
        </button>
        <span className={styles.timer}>{formatSecondsToHHMMSS(timer)}</span>
      </div>
    </div>
  );
}

export default ChatHeader;
