"use client";

import React, { useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { BaseModal } from "@/components/modal";
import DynamicButton from "@/components/button";
import LiveRoomsTable from "@/components/annaulMazad/LiveRoomsTable";
import BookletDownloadCard from "@/components/annaulMazad/BookletDownloadCard";
import type { GroupAuction, SingleAuction } from "@/actions/group-auctions";
import { useSession } from "@/auth/session-provider";
import { useSetAtom } from "jotai";
import { useAtomCallback } from "jotai/utils";
import { loginModalAtom } from "@/components/state/loginAtom";
import AnnualAuctionSingleForm from "@/components/annaulMazad/AnnualAuctionSingleForm";
import {
  formAtom,
  stepAtom,
  defaultForm,
  auctionConfigAtom,
  auctionConfigLoadingAtom,
  resetAuctionAtoms,
} from "@/components/state/autionAtoms";
import { getAuctionConfig } from "@/actions/config-mazad";
import { useTranslations, useLocale } from "next-intl";
import { useAvailablePaddlesForAuction } from "@/lib/clientQueries";
import YearlyPaddleModal from "@/components/paddles/YearlyPaddleModal";
import { getPrefetchedGroupAuctionTerms } from "@/lib/groupAuctionShowTerms";
import { motion } from "framer-motion";
import RiyalIcon from "@/components/ui/RiyalIcon";
import { useRouter } from "next/navigation";
import AuctionUnifiedTimer from "@/components/count/AuctionUnifiedTimer";
import GroupAuctionLocationMapSection from "@/components/annaulMazad/GroupAuctionLocationMapSection";

interface AuctionGroupRoom {
  id: string;
  first_single_auction_id?: string | null;
  name?: string | null;
  day_order?: string | number | null;
  single_auctions_count?: string | number | null;
  main_image?: { id?: number | null; url?: string };
  status?: string | null;
}

interface CamelGroupAuctionClientProps {
  auction: GroupAuction;
  initialInnerAuctions?: SingleAuction[];
  initialNextCursor?: string | null;
  initialRooms?: AuctionGroupRoom[];
  maxDays?: number;
}

export default function CamelGroupAuctionClient({
  auction,
  initialInnerAuctions,
  initialNextCursor,
  initialRooms = [],
  maxDays = 0,
}: CamelGroupAuctionClientProps) {
  const t = useTranslations("ANNUAL_GROUP_AUCTION");
  const tPaddle = useTranslations("YEARLY_PADDLE_MODAL");
  const locale = useLocale();
  const isRtl = (locale || "").toLowerCase().startsWith("ar");
  const router = useRouter();

  const toIsoDateTime = (value?: string | null): string | null => {
    if (!value) return null;
    const v = String(value).trim();
    if (!v) return null;
    if (v.includes("T")) return v;

    const m = v.match(/^(\d{4}-\d{2}-\d{2})\s+(\d{2}:\d{2})(?::(\d{2}))?$/);
    if (m) {
      const datePart = m[1];
      const timePart = m[2];
      const seconds = m[3] ?? "00";
      return `${datePart}T${timePart}:${seconds}`;
    }

    return v;
  };

  const parseDateSafe = (value?: string | null): Date | null => {
    const iso = toIsoDateTime(value);
    if (!iso) return null;
    const d = new Date(iso);
    return Number.isNaN(d.getTime()) ? null : d;
  };

  const isUpcoming =
    String((auction as any)?.auction_state || "").toLowerCase() === "upcoming";
  const isHorseAuction =
    String((auction as any)?.animal_type || "camel").toLowerCase() === "horse";

  const catalogUrl = (auction as any)?.catalog?.url as string | undefined;

  const getLocalizedText = (text: string) => {
    try {
      const parsed = JSON.parse(text);
      return parsed[locale] || parsed["en"] || text;
    } catch {
      return text;
    }
  };

  const session = useSession();
  const setLoginModal = useSetAtom(loginModalAtom);
  const setFormAtom = useSetAtom(formAtom);
  const setStepAtom = useSetAtom(stepAtom);
  const setAuctionConfig = useSetAtom(auctionConfigAtom);
  const setAuctionConfigLoading = useSetAtom(auctionConfigLoadingAtom);
  const resetAll = useAtomCallback((get, set) => {
    resetAuctionAtoms(set);
  });
  const [isOpen, setIsOpen] = useState(false);
  const [agree, setAgree] = useState(false);
  const [ownerOther, setOwnerOther] = useState(false);
  const [payMethod, setPayMethod] = useState<"wallet" | "card">("wallet");
  const [submitted, setSubmitted] = useState(false);
  const [paddleModalOpen, setPaddleModalOpen] = useState(false);
  const [successOpen, setSuccessOpen] = useState(false);
  const [successSeconds, setSuccessSeconds] = useState(4);

  const auctionId = auction?.id ? String(auction.id) : "";
  const prices = {
    normalPrice: Number((auction as any)?.normal_paddle_price ?? 0) || 0,
    premiumPrice: Number((auction as any)?.premium_paddle_price ?? 0) || 0,
    premiumUseTimes: Number((auction as any)?.premium_use_times ?? 0) || 0,
  };
  const { data: availablePaddles = [] } = useAvailablePaddlesForAuction(
    auctionId,
    "annual",
  );

  const goToMyGroupAuctions = () => {
    const langPrefix = locale ? `/${locale}` : "";
    router.push(`${langPrefix}/dashboard?tab=mazayadaty`);
  };

  useEffect(() => {
    if (!successOpen) return;
    setSuccessSeconds(4);
    const timer = setInterval(() => {
      setSuccessSeconds((s) => {
        const next = Math.max(0, Number(s) - 1);
        if (next === 0) {
          clearInterval(timer);
          setSuccessOpen(false);
          goToMyGroupAuctions();
        }
        return next;
      });
    }, 1000);

    return () => clearInterval(timer);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [successOpen]);

  // يُستدعى بعد إتمام الدفع بنجاح - يغلق الـ Modal ويحدث البيانات
  const handlePaymentSuccess = async () => {
    setIsOpen(false);
    resetAll();
    if (typeof window !== "undefined") {
      window.localStorage.removeItem("ataya_auction_form");
    }
    setSuccessOpen(true);
  };

  const participationFee = auction.participation_fee || 1500;
  const timerDisplay = useMemo(() => {
    if (!auction.timer) return "";

    const parts = [
      auction.timer.days ? `${auction.timer.days} ${isRtl ? "يوم" : "d"}` : null,
      auction.timer.hours
        ? `${auction.timer.hours} ${isRtl ? "ساعة" : "h"}`
        : null,
      auction.timer.minutes
        ? `${auction.timer.minutes} ${isRtl ? "دقيقة" : "m"}`
        : null,
      auction.timer.seconds
        ? `${auction.timer.seconds} ${isRtl ? "ثانية" : "s"}`
        : null,
    ].filter((value): value is string => Boolean(value));

    return parts.join(" ");
  }, [auction.timer, isRtl]);

  const videoUrl = (auction as any)?.video_url as string | undefined;

  const getEmbedUrl = (url: string) => {
    const trimmed = url.trim();
    if (!trimmed) return null;

    if (trimmed.includes("youtube.com/embed/")) return trimmed;
    if (trimmed.includes("youtu.be/")) {
      const id = trimmed.split("youtu.be/")[1]?.split(/[?&]/)[0];
      return id ? `https://www.youtube.com/embed/${id}` : null;
    }
    if (trimmed.includes("youtube.com/watch")) {
      const id = trimmed.split("v=")[1]?.split(/[?&]/)[0];
      return id ? `https://www.youtube.com/embed/${id}` : null;
    }

    return null;
  };

  const embedUrl = videoUrl ? getEmbedUrl(videoUrl) : null;

  const availabilityStatus = (auction as any).availability_status as
    | string
    | undefined;

  // Memoize date strings to prevent infinite re-renders
  const subscriptionStartStr =
    (auction as any).subscription_start_datetime ||
    (auction as any).subscription_start_date ||
    null;
  const subscriptionEndStr =
    (auction as any).subscription_end_datetime ||
    (auction as any).subscription_end_date ||
    null;
  const auctionStartStr =
    (auction as any).auction_start_datetime ||
    auction.auction_start_date ||
    null;
  const auctionEndStr =
    (auction as any).auction_end_datetime ||
    (auction as any).auction_end_date ||
    null;
  const workStartTime = (auction as any)?.work_start_time || "00";
  const workEndTime = (auction as any)?.work_end_time || "00";

  const subscriptionStartDate = useMemo(
    () => parseDateSafe(subscriptionStartStr),
    [subscriptionStartStr],
  );
  const subscriptionEndDate = useMemo(
    () => parseDateSafe(subscriptionEndStr),
    [subscriptionEndStr],
  );
  const auctionStartDate = useMemo(
    () => parseDateSafe(auctionStartStr),
    [auctionStartStr],
  );
  const auctionEndDate = useMemo(
    () => parseDateSafe(auctionEndStr),
    [auctionEndStr],
  );

  const formatAuctionDate = (value: Date | null, time?: string | null) => {
    if (!value) return "--";
    const localeForDate = locale?.startsWith("ar") ? "ar-SA" : "en-GB";
    const dateText = value.toLocaleDateString(localeForDate, {
      year: "numeric",
      month: "long",
      day: "numeric",
    });
    const timeText = String(time || "").trim();
    if (!timeText || /^0{1,2}(:0{1,2}){0,2}$/.test(timeText)) {
      return dateText;
    }
    return `${dateText} ${timeText}`;
  };

  const { countdownTarget, countdownLabel } = useMemo(() => {
    const now = new Date();

    if (availabilityStatus === "available_for_sellers") {
      if (subscriptionStartDate && now < subscriptionStartDate) {
        return {
          countdownTarget: subscriptionStartDate,
          countdownLabel: t("countdown.label_seller_start"),
        };
      }
      if (subscriptionEndDate) {
        return {
          countdownTarget: subscriptionEndDate,
          countdownLabel: t("countdown.label_seller_end"),
        };
      }
    }

    if (availabilityStatus === "available_for_buyers") {
      if (auctionStartDate && now < auctionStartDate) {
        return {
          countdownTarget: auctionStartDate,
          countdownLabel: t("countdown.label_auction_start"),
        };
      }
      if (
        auctionEndDate &&
        auctionStartDate &&
        now >= auctionStartDate &&
        now < auctionEndDate
      ) {
        return {
          countdownTarget: auctionEndDate,
          countdownLabel: t("countdown.label_auction_end"),
        };
      }
    }

    return { countdownTarget: null, countdownLabel: null };
  }, [
    availabilityStatus,
    subscriptionStartDate,
    subscriptionEndDate,
    auctionStartDate,
    auctionEndDate,
    t,
  ]);

  const handleOpenParticipation = () => {
    if (!session) {
      setLoginModal(true);
      return;
    }

    const animalType = ((auction as any).animal_type || "camel") as
      | "horse"
      | "camel";
    setStepAtom(1);
    setFormAtom({
      ...defaultForm,
      platform: animalType,
      animal_type: animalType,
      offer: "auction",
      auction_type: "annual",
      camelMode: "individual",
      is_group: false,
      group_auction_id: auction.id,
    });

    (async () => {
      try {
        setAuctionConfigLoading(true);
        const data = await getAuctionConfig(animalType);
        setAuctionConfig(data);
      } catch (error) {
        console.error("Error loading auction data (group context):", error);
      } finally {
        setAuctionConfigLoading(false);
      }
    })();
    setIsOpen(true);
  };

  const handleOpenPaddleModal = () => {
    if (!session) {
      setLoginModal(true);
      return;
    }
    setPaddleModalOpen(true);
  };

  return (
    <div className="bg-[#FBF9F6] text-slate-800 overflow-hidden">
      <section
        className=" text-white py-16"
        style={{ background: "linear-gradient(135deg, #0F5132, #1B7A50)" }}
      >
        <div className="max-w-7xl mx-auto px-6 grid lg:grid-cols-2 gap-8 items-center">
          <motion.div
            initial={{ opacity: 0, x: -50 }}
            animate={{ opacity: 1, x: 0 }}
            transition={{ duration: 0.7 }}
          >
            <motion.div
              className="pill mb-3 bg-[#F4EFE9] text-primary inline-block px-3 py-1 rounded-full text-sm"
              initial={{ opacity: 0, scale: 0.8 }}
              animate={{ opacity: 1, scale: 1 }}
              transition={{ duration: 0.5, delay: 0.1 }}
            >
              {t("hero.pill")}
            </motion.div>
            <motion.h1
              className="text-3xl md:text-5xl font-extrabold leading-tight"
              initial={{ opacity: 0, y: 30, filter: "blur(10px)" }}
              animate={{ opacity: 1, y: 0, filter: "blur(0px)" }}
              transition={{ duration: 0.8, delay: 0.2 }}
            >
              {getLocalizedText(auction.title) || t("hero.title_fallback")}
            </motion.h1>
            <motion.p
              className="mt-3 text-white/90"
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.6, delay: 0.3 }}
            >
              {getLocalizedText(auction.description) || (
                <>
                  {t.rich("hero.description_fallback", {
                    b: (chunks) => <b>{chunks}</b>,
                  })}
                </>
              )}
            </motion.p>

            <motion.div
              className="mt-5 flex flex-wrap gap-3"
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.5, delay: 0.4 }}
            >
              <motion.div
                whileHover={{ scale: 1.05 }}
                whileTap={{ scale: 0.95 }}
              >
                <DynamicButton onClick={handleOpenParticipation}>
                  {t("hero.participate_now")}
                </DynamicButton>
              </motion.div>
              <motion.div
                whileHover={{ scale: 1.05 }}
                whileTap={{ scale: 0.95 }}
              >
                {/* <DynamicButton onClick={handleOpenPaddleModal}>
                  {tPaddle("buy_paddle_button")}
                </DynamicButton> */}
              </motion.div>
            </motion.div>

            <div className="grid grid-cols-2 md:grid-cols-4 gap-3 mt-8">
              {[
                [
                  ((auction as any)?.animal_type || "camel") === "horse"
                    ? t("stats.expected_animals_horse")
                    : t("stats.expected_animals_camel"),
                  auction?.total_participating_animals || "120+",
                ],
                [
                  t("stats.auction_duration"),
                  t("stats.auction_duration_value"),
                ],
                [
                  ((auction as any)?.animal_type || "camel") === "horse"
                    ? t("stats.each_animal_duration_horse")
                    : t("stats.each_animal_duration_camel"),
                  timerDisplay,
                ],
                [
                  t("stats.participation_fee"),
                  <span
                    className="inline-flex items-center justify-center gap-1"
                    key="fee"
                  >
                    <span>{participationFee || 1500}</span>
                    <RiyalIcon className="w-4 h-4" />
                  </span>,
                ],
              ].map(([label, val], i) => (
                <motion.div
                  key={i}
                  className="stat text-center min-h-30 bg-white rounded-2xl p-3 flex flex-col"
                  initial={{ opacity: 0, scale: 0.8, y: 20 }}
                  animate={{ opacity: 1, scale: 1, y: 0 }}
                  transition={{ duration: 0.5, delay: 0.5 + i * 0.1 }}
                  whileHover={{ scale: 1.05, y: -5 }}
                >
                  <div className="text-xs text-slate-500">{label}</div>
                  <div className="flex-1 flex items-center justify-center">
                    <div className="text-2xl font-extrabold text-primary">
                      {val}
                    </div>
                  </div>
                </motion.div>
              ))}
            </div>
          </motion.div>
          <motion.div
            initial={{ opacity: 0, x: 50 }}
            animate={{ opacity: 1, x: 0 }}
            transition={{ duration: 0.7, delay: 0.3 }}
          >
            <motion.div
              className="glass rounded-2xl p-6 backdrop-blur bg-white/95 border border-[#d4e0d9] shadow-[0_16px_35px_rgba(15,81,50,0.12)]"
              initial={{ opacity: 0, scale: 0.9 }}
              animate={{ opacity: 1, scale: 1 }}
              transition={{ duration: 0.5, delay: 0.4 }}
              whileHover={{ scale: 1.01 }}
            >
              <motion.h3
                className="font-extrabold text-lg text-[#0f5132]"
                initial={{ opacity: 0, y: -10 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ duration: 0.3, delay: 0.5 }}
              >
                {t("countdown.title")}
              </motion.h3>
              {countdownTarget && (
                <motion.div
                  className="mt-3"
                  initial={{ opacity: 0, y: 8 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ duration: 0.35, delay: 0.6 }}
                >
                  <AuctionUnifiedTimer
                    targetDate={countdownTarget}
                    label={countdownLabel || t("countdown.title")}
                    variant="surface"
                    className="!border-[#d9e6df] !bg-[#f8fcf9]"
                  />
                </motion.div>
              )}

              <div className="mt-4 grid grid-cols-1 gap-2">
                <div className="flex items-center justify-between gap-3 rounded-xl border border-slate-200 bg-white px-3 py-2">
                  <span className="text-sm text-slate-600">
                    {t("countdown.auction_starts")}
                  </span>
                  <span className="text-sm font-semibold text-slate-900">
                    {formatAuctionDate(auctionStartDate, workStartTime)}
                  </span>
                </div>
                <div className="flex items-center justify-between gap-3 rounded-xl border border-slate-200 bg-white px-3 py-2">
                  <span className="text-sm text-slate-600">
                    {t("countdown.auction_ends")}
                  </span>
                  <span className="text-sm font-semibold text-slate-900">
                    {formatAuctionDate(auctionEndDate, workEndTime)}
                  </span>
                </div>

                {availabilityStatus === "available_for_sellers" &&
                  subscriptionEndDate && (
                    <div className="flex items-center justify-between gap-3 rounded-xl border border-slate-200 bg-white px-3 py-2">
                      <span className="text-sm text-slate-600">
                        {t("countdown.label_seller_end")}
                      </span>
                      <span className="text-sm font-semibold text-slate-900">
                        {formatAuctionDate(subscriptionEndDate)}
                      </span>
                    </div>
                  )}
              </div>
            </motion.div>

            <motion.div
              className="mt-4 bg-white/80 rounded-2xl shadow-md p-4 flex flex-row items-center justify-between gap-3"
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.5, delay: 0.6 }}
              whileHover={{ scale: 1.02 }}
            >
              <div className="w-28 h-28 rounded-xl overflow-hidden flex items-center justify-center bg-[#F4EFE9]">
                <img
                  src={(auction as any)?.logo?.url || "/logo.png"}
                  alt={t("sponsor.alt")}
                  className="object-contain w-full h-full"
                />
              </div>
              <p className="mt-2 font-bold text-lg text-black">
                {(auction as any)?.sponsor || t("sponsor.text")}
              </p>
            </motion.div>

            {/*      {videoUrl && (
              <div className="mt-4 bg-white/80 rounded-2xl shadow-md p-4">
                <div className="font-extrabold text-lg text-black mb-2">
                  الفيديو
                </div>
                {embedUrl ? (
                  <div className="rounded-2xl overflow-hidden bg-black aspect-video">
                    <iframe
                      src={embedUrl}
                      className="w-full h-full"
                      allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
                      allowFullScreen
                      title={(auction as any)?.title || "video"}
                    />
                  </div>
                ) : (
                  <Link href={videoUrl} target="_blank" rel="noreferrer">
                    <DynamicButton fullWidth>فتح الفيديو</DynamicButton>
                  </Link>
                )}
              </div>
            )} */}
          </motion.div>
        </div>
      </section>

      <div className="max-w-7xl mx-auto px-6 py-8 space-y-8">
        {catalogUrl ? (
          <BookletDownloadCard
            catalogUrl={catalogUrl}
            className="bg-white shadow-[0_18px_40px_rgba(2,6,23,0.08)]"
            title={
              (((auction as any).animal_type || "camel") as any) === "horse"
                ? t("download_brochure_horse")
                : t("download_brochure_camel")
            }
            description={t("download_brochure_description")}
          />
        ) : null}

        {/* Rooms Section */}
        {initialRooms.length > 0 && (
          <section className="space-y-4">
            <div className="flex items-center justify-between flex-wrap gap-2">
              <h2 className="text-xl md:text-2xl font-extrabold">
                {isHorseAuction
                  ? isRtl
                    ? "المجموعة"
                    : "Auction Group"
                  : t("rooms.camels_title")}
              </h2>
            </div>
            <LiveRoomsTable
              groupId={String(auction.id)}
              initialRooms={initialRooms}
              maxDays={maxDays}
              animalType={isHorseAuction ? "horse" : "camel"}
              auctionType={auction.auction_type}
              hideActions
              hidePriceAndWinner
            />
          </section>
        )}
      </div>

      <section id="apply" className="py-12">
        <div className="max-w-7xl mx-auto px-6">
          <div className="rounded-2xl border soft bg-white p-6 flex items-center justify-between flex-wrap gap-3">
            <div>
              <h2 className="text-2xl font-extrabold">{t("apply.title")}</h2>
              <p className="text-slate-600 mt-1">
                {t.rich("apply.description", {
                  fee: () => (
                    <b>
                      <span className="inline-flex items-center gap-1">
                        <span>{participationFee}</span>
                        <RiyalIcon className="w-4 h-4" />
                      </span>
                    </b>
                  ),
                })}
              </p>
            </div>
            <DynamicButton onClick={handleOpenParticipation}>
              {t("apply.button_participate")}
            </DynamicButton>
          </div>
        </div>
      </section>

      <div className="max-w-7xl mx-auto px-6 pb-10">
        <GroupAuctionLocationMapSection lat={auction.lat} lng={auction.lng} />
      </div>

      <BaseModal
        isOpen={isOpen}
        onOpenChange={(open) => {
          if (!open) {
            resetAll();
            if (typeof window !== "undefined") {
              window.localStorage.removeItem("ataya_auction_form");
            }
          }
          setIsOpen(open);
        }}
        title={t("modal.title")}
        contentClassName="w-[100vw] sm:max-w-[900px] h-dvh sm:h-auto sm:max-h-[85vh] overflow-hidden"
        headerClassName="hidden"
        bodyClassName="p-0"
      >
        <AnnualAuctionSingleForm
          participationFee={participationFee as any}
          onSuccess={handlePaymentSuccess}
        />
      </BaseModal>

      <BaseModal
        isOpen={successOpen}
        onOpenChange={(open: boolean) => {
          setSuccessOpen(open);
        }}
        placement="center"
        contentClassName="w-full max-w-md rounded-2xl p-4"
        title={t("participation.success.title")}
      >
        <div className="space-y-4">
          <div className="text-sm text-slate-700">
            {t("participation.success.description")}
          </div>
          <div className="text-sm text-slate-500">
            {t("participation.success.redirect_in", {
              seconds: successSeconds,
            })}
          </div>

          <div className="flex items-center justify-end gap-2 pt-2 border-t">
            <DynamicButton
              className="inline-flex items-center justify-center rounded-xl px-4 py-2 font-semibold bg-white border border-slate-200 text-slate-700"
              onClick={async () => {
                setSuccessOpen(false);
              }}
            >
              {t("participation.success.stay")}
            </DynamicButton>
            <DynamicButton
              className="inline-flex items-center justify-center rounded-xl px-4 py-2 font-semibold bg-[#0f5132] text-white"
              onClick={() => {
                setSuccessOpen(false);
                goToMyGroupAuctions();
              }}
            >
              {t("participation.success.go_to_dashboard")}
            </DynamicButton>
          </div>
        </div>
      </BaseModal>

      <YearlyPaddleModal
        open={paddleModalOpen}
        onClose={() => setPaddleModalOpen(false)}
        groupAuctionId={auctionId}
        yearlyAuctionId={auctionId}
        yearlyAuctionType="group"
        prices={prices}
        availablePaddles={availablePaddles}
        prefetchedAuctionTerms={getPrefetchedGroupAuctionTerms(auction)}
        twoStepAuctionTerms
        onJoined={() => {}}
      />
    </div>
  );
}
