"use client";

import { useEffect, useState, useRef } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { useTranslations } from "next-intl";

type CountdownTimerProps = {
  targetDate: string | Date;
  label?: string;
  variant?: "default" | "compact" | "large";
};

interface TimeDigitProps {
  value: string;
  label: string;
  variant?: "default" | "compact" | "large";
}

function TimeDigit({ value, label, variant = "default" }: TimeDigitProps) {
  const prevValue = useRef(value);
  const [isAnimating, setIsAnimating] = useState(false);
  const isCompact = variant === "compact";
  const isLarge = variant === "large";

  useEffect(() => {
    if (prevValue.current !== value) {
      setIsAnimating(true);
      prevValue.current = value;
      const timeout = setTimeout(() => setIsAnimating(false), 300);
      return () => clearTimeout(timeout);
    }
  }, [value]);

  return (
    <div className="relative group">
      <div
        className={`absolute inset-0 rounded-xl blur-sm transition-opacity duration-300 bg-[#0f5132]/20 ${
          isAnimating ? "opacity-100" : "opacity-0"
        }`}
      />

      <motion.div
        className="relative overflow-hidden rounded-xl border border-[#0f5132]/20 bg-gradient-to-b from-[#0f5132]/10 to-white shadow-[0_4px_12px_rgba(15,81,50,0.16)] transition-all duration-300"
        animate={
          isAnimating
            ? {
                scale: [1, 1.03, 1],
              }
            : {}
        }
        transition={{ duration: 0.3, ease: "easeOut" }}
      >
        <div className="absolute inset-0 bg-gradient-to-r from-transparent via-white/40 to-transparent -translate-x-full group-hover:translate-x-full transition-transform duration-700" />

        <div
          className={`relative ${isCompact ? "px-2 py-2" : isLarge ? "px-3 py-3.5" : "px-2 py-2.5 sm:px-3 sm:py-3"}`}
        >
          <div className="text-[10px] sm:text-[11px] font-semibold text-[#0f5132]/85 mb-1">
            {label}
          </div>

          <div
            className={`relative overflow-hidden ${isCompact ? "h-6" : isLarge ? "h-9" : "h-7 sm:h-8"}`}
          >
            <AnimatePresence mode="popLayout">
              <motion.div
                key={value}
                initial={{ y: 20, opacity: 0, rotateX: -90 }}
                animate={{ y: 0, opacity: 1, rotateX: 0 }}
                exit={{ y: -20, opacity: 0, rotateX: 90 }}
                transition={{
                  type: "spring",
                  stiffness: 300,
                  damping: 25,
                }}
                className={`font-extrabold tabular-nums text-[#0f5132] ${
                  isCompact
                    ? "text-base"
                    : isLarge
                      ? "text-2xl sm:text-3xl"
                      : "text-lg sm:text-xl"
                }`}
              >
                {value}
              </motion.div>
            </AnimatePresence>
          </div>
        </div>

        <motion.div
          className="h-0.5 bg-gradient-to-r from-[#0f5132]/0 via-[#0f5132]/70 to-[#0f5132]/0"
          animate={isAnimating ? { scaleX: [0, 1, 0] } : {}}
          transition={{ duration: 0.5 }}
        />
      </motion.div>
    </div>
  );
}

export default function CountdownTimer({
  targetDate,
  label,
  variant = "default",
}: CountdownTimerProps) {
  const t = useTranslations("COUNTDOWN");
  const [timeLeft, setTimeLeft] = useState({
    d: "--",
    h: "--",
    m: "--",
    s: "--",
  });
  const [isExpired, setIsExpired] = useState(false);

  useEffect(() => {
    const parseTargetDateMs = (value: string | Date) => {
      if (value instanceof Date) return value.getTime();

      const raw = String(value || "").trim();
      if (!raw) return Number.NaN;

      const normalized = raw.includes("T") ? raw : raw.replace(" ", "T");
      const parsed = new Date(normalized);
      return parsed.getTime();
    };

    const updateCountdown = () => {
      const now = Date.now();
      const target = parseTargetDateMs(targetDate);
      if (Number.isNaN(target)) {
        setIsExpired(true);
        setTimeLeft({ d: "--", h: "--", m: "--", s: "--" });
        return;
      }

      const diff = Math.max(0, target - now);
      setIsExpired(diff === 0);

      const d = Math.floor(diff / (1000 * 60 * 60 * 24));
      const h = Math.floor((diff / (1000 * 60 * 60)) % 24);
      const m = Math.floor((diff / (1000 * 60)) % 60);
      const s = Math.floor((diff / 1000) % 60);

      setTimeLeft({
        d: String(d).padStart(2, "0"),
        h: String(h).padStart(2, "0"),
        m: String(m).padStart(2, "0"),
        s: String(s).padStart(2, "0"),
      });
    };

    updateCountdown();
    const timer = setInterval(updateCountdown, 1000);
    return () => clearInterval(timer);
  }, [targetDate]);

  const timeUnits = [
    { label: t("days"), value: timeLeft.d },
    { label: t("hours"), value: timeLeft.h },
    { label: t("minutes"), value: timeLeft.m },
    { label: t("seconds"), value: timeLeft.s },
  ];

  return (
    <motion.div
      className={`w-full text-center border-t border-emerald-100 ${
        variant === "compact" ? "mt-2 pt-2.5" : "mt-3 pt-3"
      }`}
      style={{ borderTopColor: "rgba(15, 81, 50, 0.15)" }}
      initial={{ opacity: 0, y: 10 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.4 }}
    >
      {label && (
        <motion.div
          className="text-xs text-[#0f5132] mb-2 font-semibold flex items-center justify-center gap-1.5"
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ delay: 0.2 }}
        >
          <span className="w-1.5 h-1.5 rounded-full bg-[#0f5132] animate-pulse" />
          {label}
        </motion.div>
      )}

      {isExpired ? (
        <motion.div
          className="py-3 text-center"
          initial={{ scale: 0.9, opacity: 0 }}
          animate={{ scale: 1, opacity: 1 }}
        >
          <span className="inline-flex items-center rounded-lg border border-[#0f5132]/20 bg-[#0f5132]/10 px-3 py-1 text-[#0f5132] font-bold text-xs sm:text-sm">
            {t("expired")}
          </span>
        </motion.div>
      ) : (
        <div
          className={`grid grid-cols-4 ${
            variant === "compact" ? "gap-1" : "gap-1.5 sm:gap-2"
          }`}
        >
          {timeUnits.map((unit, i) => (
            <motion.div
              key={unit.label}
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: i * 0.1, duration: 0.4 }}
            >
              <TimeDigit value={unit.value} label={unit.label} variant={variant} />
            </motion.div>
          ))}
        </div>
      )}
    </motion.div>
  );
}
