"use client";
import { blackOps } from "@/styels/fonts";
import { useTranslations } from "next-intl";
import React, { useCallback, useEffect, useState } from "react";

export default function CountdownTimer({ targetDate }) {
  const t = useTranslations();

  const calculateTimeLeft = useCallback(() => {
    const difference = new Date(targetDate) - new Date();
    const timeLeft = {
      day: 0,
      hour: 0,
      minute: 0,
      second: 0,
    };

    if (difference > 0) {
      timeLeft.day = Math.floor(difference / (1000 * 60 * 60 * 24));
      timeLeft.hour = Math.floor((difference / (1000 * 60 * 60)) % 24);
      timeLeft.minute = Math.floor((difference / 1000 / 60) % 60);
      timeLeft.second = Math.floor((difference / 1000) % 60);
    }

    return timeLeft;
  }, [targetDate]);

  const [timeLeft, setTimeLeft] = useState(calculateTimeLeft());

  useEffect(() => {
    const timer = setInterval(() => {
      setTimeLeft(calculateTimeLeft());
    }, 1000);
    return () => clearInterval(timer);
  }, [calculateTimeLeft]);

  const formatNumber = (num) => String(num).padStart(2, "0");

  return (
    <div className="flex justify-around gap-1" dir="ltr">
      {["day", "hour", "minute", "second"].map((unit, idx) => (
        <React.Fragment key={unit}>
          <div className="text-center">
            <div
              className={`${blackOps.className} bg-[#008ECC] text-white rounded-lg min-w-10 p-2 text-sm text-center`}
            >
              {formatNumber(timeLeft[unit])}
            </div>
            <span className="font-bold text-xs">{t(unit)}</span>
          </div>
          {idx < 3 && <Star className="mt-3" />}
        </React.Fragment>
      ))}
    </div>
  );
}

function Star({ className }) {
  return (
    <svg
      className={className}
      width={12}
      height={12}
      viewBox="0 0 12 12"
      fill="none"
      xmlns="http://www.w3.org/2000/svg"
    >
      <path
        d="M5.07247 0.892691C5.38503 0.0167071 6.62387 0.0167084 6.93643 0.892692L7.82824 3.39203C7.92526 3.66393 8.13618 3.8799 8.40571 3.98333L10.9154 4.94638C11.7621 5.27129 11.7621 6.46917 10.9154 6.79408L8.40571 7.75713C8.13618 7.86056 7.92526 8.07653 7.82824 8.34843L6.93643 10.8478C6.62387 11.7238 5.38503 11.7238 5.07247 10.8478L4.18066 8.34843C4.08364 8.07653 3.87272 7.86056 3.60319 7.75713L1.09354 6.79408C0.246845 6.46917 0.246843 5.27129 1.09354 4.94638L3.60319 3.98333C3.87272 3.8799 4.08364 3.66393 4.18066 3.39203L5.07247 0.892691Z"
        fill="#DA8B48"
      />
    </svg>
  );
}
