"use client";

import { useEffect, useState } from "react";
import { Card, CardContent } from "@/components/ui/card";
import { useLanguage } from "@/src/hooks/LanguageContext";
import { getTranslation } from "@/src/hooks/useTranslation";

interface TimeLeft {
  days: number;
  hours: number;
  minutes: number;
  seconds: number;
}

interface CountdownTimerProps {
  targetDate: Date;
  label: string;
  endDate?: Date;
  examStartTime?: string;
}

export default function CountdownTimer({
  targetDate,
  label,
  endDate,
  examStartTime,
}: CountdownTimerProps) {
  const { language } = useLanguage();
  const t = getTranslation(language).countdownTimer;

  const [timeLeft, setTimeLeft] = useState<TimeLeft>({
    days: 0,
    hours: 0,
    minutes: 0,
    seconds: 0,
  });

  const [isExpired, setIsExpired] = useState(false);
  const hasValidEndDate =
    endDate instanceof Date && !Number.isNaN(endDate.getTime());

  useEffect(() => {
    const calculateTimeLeft = () => {
      const difference = +targetDate - +new Date();

      if (difference <= 0) {
        setIsExpired(true);
        setTimeLeft({
          days: 0,
          hours: 0,
          minutes: 0,
          seconds: 0,
        });
        return;
      }

      setIsExpired(false);
      setTimeLeft({
        days: Math.floor(difference / (1000 * 60 * 60 * 24)),
        hours: Math.floor((difference / (1000 * 60 * 60)) % 24),
        minutes: Math.floor((difference / 1000 / 60) % 60),
        seconds: Math.floor((difference / 1000) % 60),
      });
    };

    calculateTimeLeft();
    const timer = setInterval(calculateTimeLeft, 1000);

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

  const formatDateTime = (input?: number | Date) => {
    if (!input) return "";

    const date = input instanceof Date ? input : new Date(input);

    if (isNaN(date.getTime())) {
      console.error("Invalid countdown date:", input);
      return "";
    }

    return new Intl.DateTimeFormat(language === "hindi" ? "hi-IN" : "en-IN", {
      dateStyle: "medium",
      timeStyle: "short",
    }).format(date);
  };

  function TimerBox({ value, boxLabel }: { value: number; boxLabel: string }) {
    return (
      <div className="text-center min-w-[56px] sm:min-w-[72px]">
        <div className="text-2xl sm:text-4xl font-bold leading-none">
          {value.toString().padStart(2, "0")}
        </div>
        <div className="text-xs sm:text-sm text-orange-100">{boxLabel}</div>
      </div>
    );
  }

  function Colon() {
    return (
      <div className="hidden sm:block text-4xl font-bold text-white leading-none mt-1">
        :
      </div>
    );
  }

  return (
    <Card className="bg-gradient-to-br from-orange-300 to-orange-400 text-white border-none">
      <CardContent className="pt-6">
        {isExpired ? (
          <div className="text-center py-6">
            <>
              <div className="inline-flex items-center gap-2 bg-white/20 text-white text-sm sm:text-base font-semibold px-4 py-1.5 rounded-full mb-4 animate-pulse">
                <span className="w-2 h-2 rounded-full bg-white"></span>
                {t.examStarted}
              </div>

              {hasValidEndDate && (
                <>
                  <div className="text-lg sm:text-xl font-semibold mb-3">
                    {t.finalExamEndsOn}
                  </div>
                  <div className="text-2xl sm:text-3xl font-bold">
                    {formatDateTime(endDate)}
                  </div>
                </>
              )}
            </>
          </div>
        ) : (
          <>
            <h3 className="text-lg sm:text-xl font-semibold mb-4 text-center">
              {label}
            </h3>

            <div className="flex justify-center gap-3 sm:gap-4 items-start">
              <TimerBox value={timeLeft.days} boxLabel={t.days} />
              <Colon />
              <TimerBox value={timeLeft.hours} boxLabel={t.hours} />
              <Colon />
              <TimerBox value={timeLeft.minutes} boxLabel={t.minutes} />
              <Colon />
              <TimerBox value={timeLeft.seconds} boxLabel={t.seconds} />
            </div>
          </>
        )}
      </CardContent>
    </Card>
  );
}
