import React, { useEffect, useRef, useState } from "react";
import { useSelector } from "react-redux";
import { RootState } from "@/src/store";

interface AuctionTimerProps {
  onAuctionEnd?: () => void;
  useParentProps?: boolean; // ✅ keep this
  className?: string;
  auctionEndsAt?: string; // ISO string (optional)
  currentServerTime?: string; // ISO string (optional)
}

const pad = (n: number) => n.toString().padStart(2, "0");

const AuctionTimer: React.FC<AuctionTimerProps> = ({
  onAuctionEnd,
  useParentProps = true,
  auctionEndsAt,
  currentServerTime,
  className = "",
}) => {
  const { data: listingData } = useSelector(
    (state: RootState) => state.viewListingReducer
  );
  const viewListingData = listingData?.data?.listing;
  // Decide which props to use
  const serverTime = useParentProps
    ? currentServerTime
    : viewListingData?.current_time_formatted;

  const auctionEndTime = useParentProps
    ? auctionEndsAt
    : viewListingData?.auction_ends_at;

  // Get start datetime for "coming soon" check
  const startDateTime = useParentProps
    ? undefined
    : viewListingData?.start_datetime;

  const [display, setDisplay] = useState("Loading...");
  const [ended, setEnded] = useState(false);
  // const [isComingSoon, setIsComingSoon] = useState(false);

  const onAuctionEndRef = useRef(onAuctionEnd);
  const targetTimeRef = useRef<string | undefined>(undefined);
  const comingSoonRef = useRef(false);
  const nowMsRef = useRef(0);

  useEffect(() => {
    onAuctionEndRef.current = onAuctionEnd;
  }, [onAuctionEnd]);

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

    // Parse ISO string to milliseconds
    const parseTime = (isoString: string) => {
      // Handle both ISO format and "yyyy-MM-dd HH:mm:ss" format
      const formatted = isoString.includes("T")
        ? isoString
        : isoString.replace(" ", "T");
      return new Date(formatted).getTime();
    };

    nowMsRef.current = parseTime(serverTime);

    // Check if auction is coming soon (hasn't started yet)
    if (startDateTime && !useParentProps) {
      const startMs = parseTime(startDateTime);
      if (nowMsRef.current < startMs) {
        // Auction hasn't started yet - countdown to start
        targetTimeRef.current = startDateTime;
        comingSoonRef.current = true;
        // setIsComingSoon(true);
      } else {
        // Auction has started - countdown to end
        targetTimeRef.current = auctionEndTime;
        comingSoonRef.current = false;
        // setIsComingSoon(false);
      }
    } else {
      // Use auction end time as default
      targetTimeRef.current = auctionEndTime;
      comingSoonRef.current = false;
      // setIsComingSoon(false);
    }

    if (!targetTimeRef.current) return;

    const updateTimer = () => {
      if (!targetTimeRef.current) return;

      const targetMs = parseTime(targetTimeRef.current);
      const distance = targetMs - nowMsRef.current;

      if (distance <= 0) {
        // If coming soon ended, switch to auction end timer
        if (comingSoonRef.current && startDateTime && auctionEndTime) {
          const endMs = parseTime(auctionEndTime);
          const newDistance = endMs - nowMsRef.current;
          if (newDistance > 0) {
            // Switch to auction end timer
            targetTimeRef.current = auctionEndTime;
            comingSoonRef.current = false;
            // setIsComingSoon(false);
            const totalSeconds = Math.floor(newDistance / 1000);
            const totalHours = Math.floor(totalSeconds / 3600);
            const minutes = Math.floor((totalSeconds % 3600) / 60);
            const seconds = totalSeconds % 60;
            setDisplay(`${totalHours}h : ${pad(minutes)}m : ${pad(seconds)}s`);
            setEnded(false);
            nowMsRef.current += 1000;
            return;
          }
        }

        // Timer ended
        setDisplay("00h : 00m : 00s");
        setEnded(true);
        if (onAuctionEndRef.current) onAuctionEndRef.current();
        return;
      }

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

      setDisplay(`${totalHours}h : ${pad(minutes)}m : ${pad(seconds)}s`);

      nowMsRef.current += 1000; // increment simulated server time
    };

    updateTimer(); // initial call
    const interval = setInterval(updateTimer, 1000);
    return () => clearInterval(interval);
  }, [auctionEndTime, serverTime, startDateTime, useParentProps]);

  return (
    <div className={`auction-timer ${className} ${ended ? "ended" : ""}`}>
      {display}
    </div>
  );
};

export default React.memo(AuctionTimer);
