"use client";

import { useEffect, useState } from "react";
import { Clock, AlertCircle } from "lucide-react";

interface ContractCountdownProps {
  endDate?: string | null;
  className?: string;
}

export function ContractCountdown({
  endDate,
  className = "",
}: ContractCountdownProps) {
  const [daysLeft, setDaysLeft] = useState<number | null>(null);
  const [isExpired, setIsExpired] = useState(false);

  useEffect(() => {
    if (!endDate) {
      setDaysLeft(null);
      return;
    }

    const calculateDaysLeft = () => {
      const end = new Date(endDate);
      const today = new Date();

      // Reset time for comparison
      end.setHours(0, 0, 0, 0);
      today.setHours(0, 0, 0, 0);

      const timeDiff = end.getTime() - today.getTime();
      const days = Math.ceil(timeDiff / (1000 * 3600 * 24));

      setIsExpired(days < 0);
      setDaysLeft(days);
    };

    calculateDaysLeft();

    // Update every minute to keep countdown fresh
    const interval = setInterval(calculateDaysLeft, 60000);

    return () => clearInterval(interval);
  }, [endDate]);

  if (daysLeft === null) {
    return null;
  }

  // Determine colors based on urgency
  const getUrgencyStyle = () => {
    if (isExpired) {
      return {
        bg: "bg-red-500/15",
        border: "border-red-500/40",
        text: "text-red-700 dark:text-red-300",
        icon: "text-red-500",
        label: "Expired",
      };
    }

    if (daysLeft < 7) {
      return {
        bg: "bg-red-500/15",
        border: "border-red-500/40",
        text: "text-red-700 dark:text-red-300",
        icon: "text-red-500",
        label: `${daysLeft} day${daysLeft !== 1 ? "s" : ""} left`,
      };
    }

    if (daysLeft < 14) {
      return {
        bg: "bg-orange-500/15",
        border: "border-orange-500/40",
        text: "text-orange-700 dark:text-orange-300",
        icon: "text-orange-500",
        label: `${daysLeft} days left`,
      };
    }

    if (daysLeft < 30) {
      return {
        bg: "bg-amber-500/15",
        border: "border-amber-500/40",
        text: "text-amber-700 dark:text-amber-300",
        icon: "text-amber-500",
        label: `${daysLeft} days left`,
      };
    }

    return {
      bg: "bg-green-500/15",
      border: "border-green-500/40",
      text: "text-green-700 dark:text-green-300",
      icon: "text-green-500",
      label: `${daysLeft} days left`,
    };
  };

  const urgency = getUrgencyStyle();

  return (
    <div
      className={`inline-flex items-center gap-2 rounded-full border ${urgency.bg} ${urgency.border} px-3 py-1.5 text-[11px] font-bold uppercase tracking-wider ${urgency.text} ${className}`}
    >
      {isExpired ? (
        <AlertCircle className={`h-3.5 w-3.5 ${urgency.icon}`} />
      ) : (
        <Clock className={`h-3.5 w-3.5 ${urgency.icon} animate-pulse`} />
      )}
      {urgency.label}
    </div>
  );
}
