"use client";

import { useCallback, useEffect, useRef, useState } from "react";
import { useSession } from "@/auth/session-provider";
import { useAppToast, useNumberFormatter } from "@/app/[lang]/providers";
import { useTranslations, useLocale } from "next-intl";
import { useQueryClient } from "@tanstack/react-query";
import { playStartGroupAuctionSound } from "@/lib/utils/soundPlayer";
import { useYearlyAuctionSocket } from "@/lib/socket/useYearlyAuctionSocket";
import {
  coerceYearlyBidsArray,
  mapYearlyStateBidsToUiBidders,
  mergeYearlyHighestBidderPreservingPaddle,
  mergeYearlyUiBiddersPreservingPaddles,
} from "@/lib/socket/yearlyGroupStateNormalize";
import { useMyYearlyAuctionGroups } from "@/lib/clientQueries";
import DynamicButton from "@/components/button";
import { Card, CardBody } from "@heroui/react";
import { getGroupSingleAuctions } from "@/actions/group-auctions";
import { BaseModal } from "@/components/modal";
import YearlyLiveConnectionBanner from "@/components/yearly/YearlyLiveConnectionBanner";

interface OwnerYearlyAuctionGroupLiveClientProps {
  auctionGroupId: string;
}

export default function OwnerYearlyAuctionGroupLiveClient({
  auctionGroupId,
}: OwnerYearlyAuctionGroupLiveClientProps) {
  const session = useSession();
  const toast = useAppToast();
  const t = useTranslations("YEARLY_AUCTION_LIVE");
  const tToast = useTranslations("TOAST");
  const locale = useLocale();
  const { toLatinDigits } = useNumberFormatter();
  const token = session?.access_token;
  const queryClient = useQueryClient();

  // Fetch auction group data from the list
  const { data: listData } = useMyYearlyAuctionGroups();
  const allItems = listData?.pages.flatMap((p) => p.data) ?? [];
  const auctionGroupData = allItems.find(
    (item: any) => item.id === auctionGroupId || item.auction_group_id === auctionGroupId
  );

  const groupAuctionId = auctionGroupData?.group_auction_id || auctionGroupData?.groupAuctionId || auctionGroupData?.group_auction?.id;
  const marketEntryPrice = auctionGroupData?.market_entry_price || null;
  const label = auctionGroupData?.label || auctionGroupData?.name || null;

  // Auction state
  // Don't initialize with auctionGroupId - wait for socket confirmation
  const [currentAuctionGroupId, setCurrentAuctionGroupId] = useState<string | null>(null);
  const [currentPrice, setCurrentPrice] = useState<number>(0);
  const [startingPrice, setStartingPrice] = useState<number>(0);
  const [highestBidder, setHighestBidder] = useState<{ id: string; name: string; paddleNumber?: number; paddleUniqueId?: string } | null>(null);
  const [bidders, setBidders] = useState<Array<{
    name: string;
    paddle: number;
    paddleUniqueId?: string | null;
    amount: number;
    timestamp?: string;
    userId?: string;
  }>>([]);
  const [reserveTriggered, setReserveTriggered] = useState<boolean>(false);
  // Start with "upcoming" - only change when we get socket confirmation
  const [auctionStatus, setAuctionStatus] = useState<
    "active" | "closed" | "upcoming" | "paused" | "skipped"
  >("upcoming");
  const [auctionGroupLabel, setAuctionGroupLabel] = useState<string | null>(label);
  
  // Timer state (from server)
  const [timerEndMs, setTimerEndMs] = useState<number | null>(null);
  const [timerRemaining, setTimerRemaining] = useState<string | null>(null);
  
  // Single auction state
  const [singleAuction, setSingleAuction] = useState<any>(null);
  const [loadingSingleAuction, setLoadingSingleAuction] = useState(false);

  // Withdrawal confirmation modal state
  const [withdrawModalOpen, setWithdrawModalOpen] = useState(false);
  const [isWithdrawing, setIsWithdrawing] = useState(false);


  // Mark loading flag as intentionally reactive (used by future spinner).
  void loadingSingleAuction;

  /**
   * Refresh the auction-group payload from REST. Called once on mount and
   * again on every silent recovery cycle (visibilitychange / online /
   * reconnect / stale-watchdog) so a long-stale tab catches up without a
   * manual refresh.
   */
  const refreshSingleAuction = useCallback(async () => {
    if (!groupAuctionId || !auctionGroupId) return;

    setLoadingSingleAuction(true);
    try {
      const response = await getGroupSingleAuctions(
        groupAuctionId,
        undefined,
        auctionGroupId,
      );
      const auctions = response?.data?.data || [];
      if (auctions.length > 0) {
        setSingleAuction(auctions[0]);
      }
    } catch (error) {
      console.error("Error fetching single auction:", error);
    } finally {
      setLoadingSingleAuction(false);
    }
  }, [groupAuctionId, auctionGroupId]);

  useEffect(() => {
    refreshSingleAuction();
  }, [refreshSingleAuction]);

  /**
   * Stale-watchdog flag: keep the watchdog aggressive while the auction is
   * known to be active. On an "upcoming" / "closed" page we still recover on
   * visibility / online events, just without the periodic stale check.
   */
  const watchdogEnabledRef = useRef<boolean>(false);
  useEffect(() => {
    watchdogEnabledRef.current =
      currentAuctionGroupId != null &&
      (auctionStatus === "active" || auctionStatus === "paused");
  }, [currentAuctionGroupId, auctionStatus]);

  /**
   * Resync handler triggered by the socket hook when realtime activity
   * stalls. Re-fetches the latest single-auction payload and invalidates the
   * owner's auction-groups list query so data on related screens stays fresh.
   */
  const handleSocketRecover = useCallback(async () => {
    queryClient.invalidateQueries({ queryKey: ["my-yearly-auction-groups"] });
    await refreshSingleAuction();
  }, [queryClient, refreshSingleAuction]);

  const handleSocketRecoverRef = useRef(handleSocketRecover);
  useEffect(() => {
    handleSocketRecoverRef.current = handleSocketRecover;
  }, [handleSocketRecover]);

  // Calculate and update timer display every second when we have timerEndMs
  useEffect(() => {
    if (!timerEndMs || auctionStatus !== "active") {
      return;
    }

    const updateTimer = () => {
      const now = Date.now();
      const remaining = Math.max(0, timerEndMs - now);
      
      if (remaining <= 0) {
        setTimerRemaining("00:00");
        return;
      }

      const totalSeconds = Math.floor(remaining / 1000);
      const minutes = Math.floor(totalSeconds / 60);
      const seconds = totalSeconds % 60;
      setTimerRemaining(`${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}`);
    };

    // Update immediately
    updateTimer();

    // Update every second
    const interval = setInterval(updateTimer, 1000);

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

  // Socket integration
  const {
    socket,
    enterMarket,
    withdrawAuctionGroup,
    requestRecovery,
    connectionStatus,
    recoveryFailureCount,
  } = useYearlyAuctionSocket({
    auctionGroupId: currentAuctionGroupId,
    groupAuctionId: groupAuctionId || "",
    token,
    watchdogEnabledRef,
    onRecover: () => {
      void handleSocketRecoverRef.current();
    },

    onStarted: (payload) => {
      playStartGroupAuctionSound();
      console.log("🎬 Auction group started:", payload);
      setCurrentAuctionGroupId(payload.auctionGroupId);
      
      const startPrice = payload.snapshot?.currentPrice ?? payload.snapshot?.startingPrice ?? payload.startingPrice ?? 0;
      const marketPrice = payload.snapshot?.marketEntryPrice ?? payload.marketEntryPrice;
      const label = payload.snapshot?.label ?? payload.label;
      
      setStartingPrice(startPrice);
      setCurrentPrice(startPrice);
      setAuctionGroupLabel(label ?? null);
      setAuctionStatus("active");
      setBidders([]);
      setHighestBidder(null);
      setReserveTriggered(false);
      
      if (payload.snapshot) {
        setAuctionStatus(payload.snapshot.status);
        setCurrentPrice(payload.snapshot.currentPrice);
        setHighestBidder(payload.snapshot.highestBidder);
        setReserveTriggered(payload.snapshot.reserveTriggered);
        
        // Set timer data from snapshot - check all possible locations
        const timerEndMs = payload.snapshot.timerEndMs;
        const timerRemaining = payload.snapshot.timerRemaining;
        
        console.log("⏰ Timer data in snapshot:", { timerEndMs, timerRemaining, snapshot: payload.snapshot });
        
        // Always set timer values if they exist in snapshot
        if (timerEndMs != null) {
          console.log("⏰ Setting timerEndMs:", timerEndMs);
          setTimerEndMs(timerEndMs);
        }
        if (timerRemaining != null && timerRemaining !== "") {
          console.log("⏰ Setting timerRemaining:", timerRemaining);
          setTimerRemaining(timerRemaining);
        } else if (timerEndMs != null && !timerRemaining) {
          // If we have timerEndMs but no timerRemaining, calculate it
          const now = Date.now();
          const remaining = Math.max(0, timerEndMs - now);
          const totalSeconds = Math.floor(remaining / 1000);
          const minutes = Math.floor(totalSeconds / 60);
          const seconds = totalSeconds % 60;
          const calculated = `${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}`;
          console.log("⏰ Calculating timerRemaining:", calculated);
          setTimerRemaining(calculated);
        }
        
        const snapshotBids = coerceYearlyBidsArray(
          payload.snapshot.bids ??
            (payload.snapshot as Record<string, unknown>).bid_history,
        );
        setBidders(mapYearlyStateBidsToUiBidders(snapshotBids));
      }
      
      toast.info(tToast("yearly_auction_started", { label: label || "" }));
    },

    onState: (payload) => {
      setAuctionStatus(payload.status);
      setCurrentPrice(payload.currentPrice);
      setHighestBidder((prev) =>
        mergeYearlyHighestBidderPreservingPaddle(prev, payload.highestBidder),
      );
      setReserveTriggered(payload.reserveTriggered);
      if (payload.label) setAuctionGroupLabel(payload.label);

      // Update timer data from payload
      if (payload.timerEndMs !== undefined && payload.timerEndMs !== null) {
        console.log("⏰ Setting timerEndMs from state:", payload.timerEndMs);
        setTimerEndMs(payload.timerEndMs);
      }
      if (payload.timerRemaining !== undefined && payload.timerRemaining !== null) {
        console.log("⏰ Setting timerRemaining from state:", payload.timerRemaining);
        setTimerRemaining(payload.timerRemaining);
      }

      setBidders((prev) =>
        mergeYearlyUiBiddersPreservingPaddles(
          prev,
          mapYearlyStateBidsToUiBidders(payload.bids),
        ),
      );
    },

    onBidCreated: (payload) => {
      setCurrentPrice(payload.amount);
      setHighestBidder(payload.bidder);

      const newBidder = {
        name: payload.bidder.name,
        paddle: payload.bidder.paddleNumber || 0,
        paddleUniqueId: (payload.bidder as any).paddleUniqueId || null,
        amount: payload.amount,
        timestamp: payload.timestamp,
        userId: payload.bidder.id,
      };
      setBidders((prev) => {
        if (
          prev.length === 1 &&
          prev[0].userId != null &&
          String(prev[0].userId) === String(payload.bidder.id)
        ) {
          return [newBidder];
        }
        return [newBidder, ...prev];
      });
    },

    onReserveTriggered: (payload) => {
      setReserveTriggered(true);
      // toast.warning(`تم تفعيل السعر الاحتياطي: ${payload.label || ""}`);
    },

    onClosed: (payload) => {
      console.log("🏁 Auction group closed:", payload);
      setAuctionStatus("closed");
      setWithdrawModalOpen(false);
      setIsWithdrawing(false);
      toast.info(
        tToast("yearly_auction_closed", { reason: payload.reason || "" }),
      );
    },

    onBidRejected: (payload) => {
      toast.error(
        payload.message || payload.reason || tToast("bid_rejected"),
      );
    },

    onError: (payload) => {
      toast.error(payload.message || tToast("connection_error"));
    },
  });

  // Owner action handlers
  const handleEnterMarket = () => {
    if (!currentAuctionGroupId) {
      toast.error(tToast("no_active_auction"));
      return;
    }
    if (!marketEntryPrice) {
      toast.error(tToast("market_entry_unavailable"));
      return;
    }
    enterMarket(currentAuctionGroupId);
    toast.info(tToast("entering_market"));
  };

  const handleWithdraw = () => {
    if (!currentAuctionGroupId) {
      toast.error(tToast("no_active_auction"));
      return;
    }
    setWithdrawModalOpen(true);
  };

  const confirmWithdraw = () => {
    if (!currentAuctionGroupId) {
      toast.error(tToast("no_active_auction"));
      setWithdrawModalOpen(false);
      return;
    }
    setIsWithdrawing(true);
    withdrawAuctionGroup(currentAuctionGroupId);
    toast.info(tToast("withdrawing_auction"));
    // Modal will close when onClosed event is received
  };

  // Error if missing groupAuctionId
  if (!groupAuctionId) {
    return (
      <Card className="border rounded-2xl shadow-soft">
        <CardBody>
          <div className="text-center p-8">
            <div className="text-red-500 text-6xl mb-4">⚠️</div>
            <h3 className="text-lg font-bold text-red-600 mb-2">
              خطأ في البيانات
            </h3>
            <p className="text-gray-600">
              لم يتم العثور على معرف جلسة المزاد. يرجى التحقق من البيانات.
            </p>
          </div>
        </CardBody>
      </Card>
    );
  }

  const isActive = auctionStatus === "active";
  const canEnterMarket = isActive && marketEntryPrice !== null && currentAuctionGroupId !== null;
  const canWithdraw = isActive && currentAuctionGroupId !== null;

  // Debug: Log timer state
  useEffect(() => {
    console.log("🔍 Timer state:", { 
      timerRemaining, 
      timerEndMs, 
      auctionStatus, 
      isActive,
      shouldShow: auctionStatus === "active" && (timerRemaining || timerEndMs)
    });
  }, [timerRemaining, timerEndMs, auctionStatus, isActive]);

  return (
    <div className="max-w-7xl mx-auto px-4 py-6 space-y-6">
      <YearlyLiveConnectionBanner
        connectionStatus={connectionStatus}
        recoveryFailureCount={recoveryFailureCount}
        onRequestRecovery={requestRecovery}
      />

      {/* Header */}
      <div className="bg-white rounded-2xl p-6 shadow-md border border-slate-100">
        <h1 className="text-2xl font-extrabold text-primary mb-2">
          التحكم المباشر - {auctionGroupLabel || auctionGroupId}
        </h1>
        <p className="text-slate-600">
          حالة المزاد:{" "}
          <span className={`font-bold ${
            auctionStatus === "active" ? "text-green-600" :
            auctionStatus === "closed" ? "text-gray-600" :
            auctionStatus === "skipped" ? "text-violet-600" :
            "text-yellow-600"
          }`}>
            {auctionStatus === "active" ? "نشط" :
             auctionStatus === "closed" ? "مغلق" :
             auctionStatus === "skipped" ? "متخطى" :
             "قادم"}
          </span>
        </p>
      </div>

      {/* Single Auction Details - Moved Above Timer Card */}
      {singleAuction && (
        <Card className="border rounded-2xl shadow-soft">
          <CardBody>
            <h2 className="text-xl font-bold mb-4">تفاصيل المزاد الفردي</h2>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {singleAuction.main_image?.url && (
                <div className="col-span-1">
                  <img
                    src={singleAuction.main_image.url}
                    alt={singleAuction.title || "صورة المزاد"}
                    className="w-full h-64 object-cover rounded-lg"
                  />
                </div>
              )}
              <div className="col-span-1 space-y-3">
                <div>
                  <span className="text-slate-600 font-medium">العنوان:</span>
                  <p className="text-lg font-bold text-slate-900 mt-1">
                    {singleAuction.title || "—"}
                  </p>
                </div>
                {singleAuction.description && (
                  <div>
                    <span className="text-slate-600 font-medium">الوصف:</span>
                    <p className="text-slate-700 mt-1">{singleAuction.description}</p>
                  </div>
                )}
                <div className="grid grid-cols-2 gap-3">
                  {singleAuction.breed && (
                    <div>
                      <span className="text-slate-600 text-sm">السلالة:</span>
                      <p className="font-medium">{singleAuction.breed}</p>
                    </div>
                  )}
                  {singleAuction.animal_color && (
                    <div>
                      <span className="text-slate-600 text-sm">اللون:</span>
                      <p className="font-medium">{singleAuction.animal_color}</p>
                    </div>
                  )}
                  {singleAuction.country && (
                    <div>
                      <span className="text-slate-600 text-sm">الدولة:</span>
                      <p className="font-medium">{singleAuction.country}</p>
                    </div>
                  )}
                  {singleAuction.state && (
                    <div>
                      <span className="text-slate-600 text-sm">المدينة:</span>
                      <p className="font-medium">{singleAuction.state}</p>
                    </div>
                  )}
                </div>
                {singleAuction.unique_id && (
                  <div>
                    <span className="text-slate-600 text-sm">المعرف الفريد:</span>
                    <p className="font-mono text-sm">{singleAuction.unique_id}</p>
                  </div>
                )}
              </div>
            </div>
          </CardBody>
        </Card>
      )}

      {/* Timer and Current Price */}
      <Card className="border rounded-2xl shadow-soft">
        <CardBody>
          <div className="flex flex-col md:flex-row items-center justify-between gap-6">
            {/* Timer Display */}
            <div className="flex flex-col items-center">
              <div className="text-sm text-slate-600 mb-2">الوقت المتبقي</div>
              <div className="rounded-lg px-6 py-4 text-center bg-slate-100">
                <div className="text-4xl font-extrabold font-mono text-[#0F5132]">
                  {timerRemaining || (timerEndMs ? "حساب..." : "00:00")}
                </div>
              </div>
              {/* Debug info */}
              <div className="text-xs text-gray-400 mt-1">
                Status: {auctionStatus} | EndMs: {timerEndMs ? "Yes" : "No"} | Remaining: {timerRemaining || "No"}
              </div>
            </div>

            {/* Current Price */}
            <div className="flex flex-col items-center">
              <div className="text-sm text-slate-600 mb-2">السعر الحالي</div>
              <div className="text-3xl font-extrabold text-[#0F5132]">
                {toLatinDigits(currentPrice.toLocaleString())} ر.س
              </div>
              {marketEntryPrice && (
                <div className="text-sm text-slate-500 mt-1">
                  سعر دخول السوق: {toLatinDigits(marketEntryPrice.toLocaleString())} ر.س
                </div>
              )}
            </div>
          </div>
        </CardBody>
      </Card>

      {/* Owner Controls */}
      {isActive && (
        <Card className="border rounded-2xl shadow-soft">
          <CardBody>
            <h2 className="text-xl font-bold mb-4">أدوات التحكم</h2>
            <div className="flex flex-wrap gap-4">
              <DynamicButton
                onClick={handleEnterMarket}
                isDisabled={!canEnterMarket}
                variant="solid"
                color="primary"
              >
                إدخال السوق
              </DynamicButton>
              <DynamicButton
                onClick={handleWithdraw}
                isDisabled={!canWithdraw}
                variant="bordered"
                color="danger"
              >
                سحب المزاد
              </DynamicButton>
            </div>
          </CardBody>
        </Card>
      )}

      {/* Bidders List */}
      {bidders.length > 0 && (
        <Card className="border rounded-2xl shadow-soft">
          <CardBody>
            <h2 className="text-xl font-bold mb-4">قائمة المزايدات</h2>
            <div className="overflow-auto">
              <table className="w-full text-sm">
                <thead>
                  <tr className="bg-slate-50">
                    <th className="p-3 text-right border">المزايد</th>
                    <th className="p-3 text-right border">المضرب</th>
                    <th className="p-3 text-right border">المبلغ</th>
                    <th className="p-3 text-right border">الوقت</th>
                  </tr>
                </thead>
                <tbody>
                  {bidders.map((bidder, index) => (
                    <tr key={index} className="border-b hover:bg-slate-50">
                      <td className="p-3 border">{bidder.name}</td>
                      <td className="p-3 border">
                        {bidder.paddleUniqueId || (bidder.paddle ? `#${bidder.paddle}` : "—")}
                      </td>
                      <td className="p-3 border font-bold text-[#0F5132]">
                        {toLatinDigits(bidder.amount.toLocaleString())} ر.س
                      </td>
                      <td className="p-3 border text-slate-500">
                        {bidder.timestamp 
                          ? new Date(bidder.timestamp).toLocaleTimeString(locale)
                          : "—"}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </CardBody>
        </Card>
      )}

      {/* Withdrawal Confirmation Modal */}
      <BaseModal
        isOpen={withdrawModalOpen}
        onOpenChange={(open) => {
          if (!open && !isWithdrawing) {
            setWithdrawModalOpen(false);
          }
        }}
        placement="center"
        title="تأكيد سحب المزاد"
        contentClassName="w-full max-w-[420px] rounded-xl text-primary"
        footer={
          <div className="flex w-full justify-end gap-2">
            <DynamicButton
              className="bg-gray-200 text-gray-800 py-2 px-4 rounded-lg hover:bg-gray-300"
              onClick={() => setWithdrawModalOpen(false)}
              isDisabled={isWithdrawing}
            >
              إلغاء
            </DynamicButton>
            <DynamicButton
              className="bg-red-600 hover:bg-red-700 text-white py-2 px-4 rounded-lg"
              onClick={confirmWithdraw}
              isDisabled={isWithdrawing}
            >
              {isWithdrawing ? "جارٍ السحب..." : "تأكيد السحب"}
            </DynamicButton>
          </div>
        }
      >
        <div className="flex flex-col gap-4 py-2">
          <div className="flex items-center justify-center mb-2">
            <div className="text-red-500 text-5xl">⚠️</div>
          </div>
          <p className="text-sm text-gray-700 text-center leading-relaxed">
            هل أنت متأكد أنك تريد <strong className="text-red-600">سحب المزاد</strong>؟
          </p>
          <p className="text-xs text-gray-500 text-center">
            سيتم إغلاق المزاد فوراً ولن يتمكن المزايدون من المزايدة بعد ذلك.
          </p>
        </div>
      </BaseModal>
    </div>
  );
}

