"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { useTranslations } from "next-intl";

import {
  Badge,
  Icon,
  IconName,
  OnlineIndicator,
  Typography,
  UserAvatar,
} from "@/components/ui";
import { revalidateChatsPage } from "@/entities/chats/actions";
import { useChat } from "@/providers/chat-provider";
import { useChatStore } from "@/providers/chat-store-provider";
import { useChats } from "@/providers/chats-provider";
import { formatSecondsToHHMMSS } from "@/shared/utils/date";
import { delay } from "@/shared/utils/delay";

import styles from "./ChatHeader.module.scss";

export default function ChatHeader() {
  const t = useTranslations("Chat");
  const router = useRouter();
  const currentChat = useChatStore(state => state.currentChat);
  const { isLoadingAdvisorMessage, isAvailableChatting } = useChat();
  const { totalUnreadCount } = useChats();
  const [timer, setTimer] = useState(0);

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

  const handleBack = async () => {
    await revalidateChatsPage();
    router.back();
  };

  return (
    <header className={styles.header}>
      <div className={styles.back} onClick={handleBack}>
        <Icon
          name={IconName.ChevronLeft}
          size={{ height: 22, width: 22 }}
          color="#374151"
        />
        {!!totalUnreadCount && (
          <Badge className={styles.badge}>
            <Typography weight="semiBold" size="xs" color="black">
              {totalUnreadCount > 99 ? "99+" : totalUnreadCount}
            </Typography>
          </Badge>
        )}
      </div>
      <div className={styles.chatInfo}>
        {!!currentChat?.assistantAvatar ? (
          <UserAvatar
            src={currentChat.assistantAvatar}
            alt={`${currentChat.assistantName} avatar`}
          />
        ) : (
          <div className={styles.avatar} />
        )}
        <div className={styles.chatInfoContent}>
          <Typography weight="semiBold" className={styles.name}>
            {currentChat?.assistantName}
            <OnlineIndicator
              isOnline={currentChat?.assistantStatus === "online"}
              className={styles.onlineIndicator}
            />
          </Typography>
          <Typography size="sm" color="secondary">
            {isLoadingAdvisorMessage ? t("typing") : ""}
          </Typography>
        </div>
      </div>
      <div className={styles.time}>
        <Typography
          weight="medium"
          size="sm"
          color="secondary"
          className={styles.timeText}
        >
          {formatSecondsToHHMMSS(timer, { isHours: false })}
        </Typography>
        <Icon
          name={IconName.Clock}
          size={{ height: 12, width: 12 }}
          color="#374151"
        />
      </div>
    </header>
  );
}
