import React, { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import Image from "next/image";
import { ChevronLeft, Layers } from "lucide-react";
import { useTimer } from "@/context/TimerContext";
import styles from "@/css/Header.module.css";

const API_URL = process.env.NEXT_PUBLIC_API_URL || "http://localhost:3000/api";

// You'll need to implement getToken for Next.js - could use cookies, localStorage, etc.
const getToken = async () => {
  // Replace with your token retrieval logic
  if (typeof window !== "undefined") {
    return localStorage.getItem("token") || sessionStorage.getItem("token");
  }
  return null;
};

const Header = ({
  image,
  displayUser,
  displaySubject,
  displayTabTitle,
  examDuration,
}) => {
  const router = useRouter();
  const [totalSeconds, setTotalSeconds] = useState(
    examDuration ? parseInt(examDuration) * 60 : 0
  );
  const { timeRemaining, stopTimer } = useTimer();
  const [userData, setUserData] = useState(null);

  useEffect(() => {
    if (!examDuration) return;

    const timer = setInterval(() => {
      setTotalSeconds((prev) => {
        if (prev <= 0) {
          clearInterval(timer);
          return 0;
        }
        return prev - 1;
      });
    }, 1000);

    return () => clearInterval(timer);
  }, [examDuration]);

  useEffect(() => {
    async function fetchUser() {
      try {
        const token = await getToken();
        if (!token) return;

        const response = await fetch(`${API_URL}/me`, {
          method: "GET",
          headers: {
            Authorization: `Bearer ${token}`,
          },
        });

        if (response.ok) {
          const fetchedUserData = await response.json();
          setUserData(fetchedUserData);
        }
      } catch (error) {
        console.error("Error fetching user data:", error);
      }
    }

    if (displayUser) {
      fetchUser();
    }
  }, [displayUser]);

  const hours = Math.floor(totalSeconds / 3600);
  const minutes = Math.floor((totalSeconds % 3600) / 60);
  const seconds = totalSeconds % 60;

  const showExitDialog = () => {
    const confirmed = window.confirm("Are you sure you want to quit the exam?");

    if (confirmed) {
      if (stopTimer) {
        stopTimer();
      }
      router.push("/unit");
    }
  };

  const handleBackClick = () => {
    router.back();
  };

  return (
    <header className={styles.header}>
      {displayUser && (
        <div className={styles.profile}>
          {image && (
            <Image
              src={image}
              alt="Profile"
              width={40}
              height={40}
              className={styles.profileImg}
            />
          )}
          <span className={styles.text}>
            Hello {userData?.name ? userData.name.split(" ")[0] : ""}
          </span>
        </div>
      )}

      {displaySubject && (
        <div className={styles.profile}>
          <button onClick={handleBackClick} className={styles.iconButton}>
            <ChevronLeft size={24} color="white" />
          </button>
          <span className={styles.text}>{displaySubject}</span>
        </div>
      )}

      {displayTabTitle && (
        <div className={styles.profile}>
          <span className={styles.text}>{displayTabTitle}</span>
        </div>
      )}

      {examDuration && (
        <div className={styles.examHeader}>
          <button onClick={showExitDialog} className={styles.iconButton}>
            <ChevronLeft size={30} color="white" />
          </button>

          <div className={styles.timer}>
            <div className={styles.timeUnit}>
              <span className={styles.timeValue}>
                {String(hours).padStart(2, "0")}
              </span>
              <span className={styles.timeLabel}>Hrs</span>
            </div>
            <div className={styles.timeUnit}>
              <span className={styles.timeValue}>
                {String(minutes).padStart(2, "0")}
              </span>
              <span className={styles.timeLabel}>Mins</span>
            </div>
            <div className={styles.timeUnit}>
              <span className={styles.timeValue}>
                {String(seconds).padStart(2, "0")}
              </span>
              <span className={styles.timeLabel}>Secs</span>
            </div>
          </div>

          <button
            disabled
            onClick={() => router.push("/exam/modal")}
            className={`${styles.iconButton} ${styles.disabled}`}
          >
            <Layers size={30} color="white" />
          </button>
        </div>
      )}
    </header>
  );
};

export default Header;
