"use client";

import { useCallback, useEffect, useMemo, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import api from "@/api/axios";
import ProductPageContent, {
  ProductOfferContext,
} from "@/app/products/[id]/[slug]/ProductPageContent";
import { useLanguage } from "@/context/LanguageContext";
import { Offer, OfferItem } from "@/types/offer";
import { getGuestUuid } from "@/utils/guestUuid";
import { getCountryCode } from "@/utils/countryCode";
import { toast } from "sonner";

function getOffer(payload: any): Offer | null {
  const data = payload?.data;
  if (!data) return null;
  if (data?.data && !Array.isArray(data.data)) return data.data;
  return data;
}

function formatPrice(value: number | string) {
  const numericValue = Number(value || 0);
  return Number.isInteger(numericValue) ? numericValue.toString() : numericValue.toFixed(2);
}

export default function OfferCustomizePage({ params }: { params: { id: string } }) {
  const router = useRouter();
  const searchParams = useSearchParams();
  const editOfferInstance = searchParams.get("edit_offer_instance");
  const isOfferEditMode = Boolean(editOfferInstance);
  const { lang } = useLanguage();
  const isAr = lang === "ar";

  const [offer, setOffer] = useState<Offer | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(false);
  const [activeStep, setActiveStep] = useState(0);
  const [completedSteps, setCompletedSteps] = useState<number[]>([]);
  const [stepPayloads, setStepPayloads] = useState<Record<number, any>>({});
  const [finished, setFinished] = useState(false);
  const [addingOfferToCart, setAddingOfferToCart] = useState(false);
  const [editGroupMap, setEditGroupMap] = useState<Record<number, number>>({});

  useEffect(() => {
    const load = async () => {
      try {
        setLoading(true);
        setError(false);

        const response = await api.get(`/offers/${params.id}`, {
          headers: { "Accept-Language": lang },
        });

        const offerData = getOffer(response.data);
        if (!offerData) {
          setError(true);
          return;
        }

        const sortedItems = [...(offerData.items || [])].sort(
          (a, b) => Number(a.sort_order || 0) - Number(b.sort_order || 0)
        );

        setOffer({ ...offerData, items: sortedItems });

        if (editOfferInstance) {
          try {
            const editRaw = sessionStorage.getItem(`offer-edit-${editOfferInstance}`);
            if (!editRaw) {
              setError(true);
              return;
            }

            const editData = JSON.parse(editRaw);
            if (Number(editData?.offer_id) !== Number(offerData.id)) {
              setError(true);
              return;
            }

            const map: Record<number, number> = {};
            (editData?.item_groups || []).forEach((entry: any) => {
              const offerItemId = Number(entry?.offer_item_id || 0);
              const cartGroupId = Number(entry?.cart_group_id || 0);
              if (offerItemId && cartGroupId) map[offerItemId] = cartGroupId;
            });

            setEditGroupMap(map);
            setCompletedSteps(sortedItems.map((_: any, index: number) => index));
            setStepPayloads({});
          } catch {
            setError(true);
            return;
          }
        } else try {
          const saved = sessionStorage.getItem(`offer-wizard-${offerData.id}`);
          if (saved) {
            const parsed = JSON.parse(saved);
            setCompletedSteps(Array.isArray(parsed.completedSteps) ? parsed.completedSteps : []);
            setStepPayloads(parsed.stepPayloads || {});
          }
        } catch {
          // Ignore invalid session data.
        }
      } catch (e) {
        console.error("Error loading offer wizard:", e);
        setError(true);
      } finally {
        setLoading(false);
      }
    };

    load();
  }, [params.id, lang, editOfferInstance]);

  const items = offer?.items || [];
  const currentItem: OfferItem | null = items[activeStep] || null;

  const persistWizardState = useCallback(
    (nextCompleted: number[], nextPayloads: Record<number, any>) => {
      if (!offer || isOfferEditMode) return;
      sessionStorage.setItem(
        `offer-wizard-${offer.id}`,
        JSON.stringify({ completedSteps: nextCompleted, stepPayloads: nextPayloads })
      );
    },
    [offer, isOfferEditMode]
  );

  const submitOfferToCart = useCallback(async (payloads: Record<number, any>) => {
    if (!offer || addingOfferToCart) return;

    try {
      setAddingOfferToCart(true);
      const guestUuid = getGuestUuid();
      const steps = (offer.items || []).map((item) => {
        const payload = payloads[item.id];
        return {
          offer_item_id: item.id,
          product_id: item.product_id,
          variation_id: payload?.variation_id ?? null,
          items: payload?.items || [],
        };
      });

      const response = await api.post(
        "/cart/offers/add",
        {
          offer_id: offer.id,
          country_code: getCountryCode(),
          guest_uuid: guestUuid,
          steps,
        },
        {
          headers: { "X-Guest-Uuid": guestUuid },
        }
      );

      if (!response.data?.success) {
        throw new Error(response.data?.message || "Unable to add offer to cart");
      }

      sessionStorage.removeItem(`offer-wizard-${offer.id}`);
      setFinished(true);
      window.dispatchEvent(new Event("cart-updated"));
      window.dispatchEvent(new Event("open-cart"));
      toast.success(isAr ? "تمت إضافة العرض إلى السلة" : "Offer added to cart");
    } catch (error) {
      console.error("Error adding offer to cart:", error);
      toast.error(isAr ? "حدث خطأ أثناء إضافة العرض إلى السلة" : "Could not add the offer to cart");
    } finally {
      setAddingOfferToCart(false);
    }
  }, [offer, addingOfferToCart, isAr]);

  useEffect(() => {
    const handleStepCompleted = (event: Event) => {
      const customEvent = event as CustomEvent<any>;
      const detail = customEvent.detail;

      if (!offer || !currentItem) return;
      if (Number(detail?.offer_id) !== Number(offer.id)) return;
      if (Number(detail?.offer_item_id) !== Number(currentItem.id)) return;

      const nextCompleted = Array.from(new Set([...completedSteps, activeStep])).sort(
        (a, b) => a - b
      );
      const nextPayloads = { ...stepPayloads, [currentItem.id]: detail };

      setCompletedSteps(nextCompleted);
      setStepPayloads(nextPayloads);
      persistWizardState(nextCompleted, nextPayloads);

      if (activeStep < items.length - 1) {
        setActiveStep((step) => step + 1);
        window.scrollTo({ top: 0, behavior: "smooth" });
      } else if (isOfferEditMode) {
        window.dispatchEvent(new Event("cart-updated"));
        window.dispatchEvent(new Event("open-cart"));
        toast.success(isAr ? "تم حفظ تعديلات العرض" : "Offer changes saved");
        if (editOfferInstance) {
          sessionStorage.removeItem(`offer-edit-${editOfferInstance}`);
        }
        router.push("/");
      } else {
        submitOfferToCart(nextPayloads);
        window.scrollTo({ top: 0, behavior: "smooth" });
      }
    };

    window.addEventListener("offer-wizard-step-completed", handleStepCompleted);
    return () => window.removeEventListener("offer-wizard-step-completed", handleStepCompleted);
  }, [
    activeStep,
    completedSteps,
    currentItem,
    items.length,
    offer,
    persistWizardState,
    stepPayloads,
    submitOfferToCart,
    isOfferEditMode,
    editOfferInstance,
    isAr,
    router,
  ]);

  const productContext: ProductOfferContext | null = useMemo(() => {
    if (!offer || !currentItem) return null;

    return {
      offerId: offer.id,
      offerItemId: currentItem.id,
      requiredQuantity: Number(currentItem.quantity || 1),
      fixedVariationId: currentItem.variation_is_fixed
        ? Number(currentItem.variation_id || currentItem.fixed_variation?.variation_id || 0) || null
        : null,
      step: activeStep,
      totalSteps: items.length,
      onPrevious: activeStep > 0 ? () => setActiveStep((step) => Math.max(0, step - 1)) : undefined,
      isRtl: isAr,
      editCartGroupId: isOfferEditMode ? editGroupMap[currentItem.id] || null : null,
    };
  }, [offer, currentItem, activeStep, items.length, isAr, isOfferEditMode, editGroupMap]);

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-[#F7F7F8] text-primary">
        <div className="flex flex-col items-center gap-4">
          <div className="w-10 h-10 rounded-full border-4 border-pink-200 border-t-primary animate-spin" />
          <span>{isAr ? "جاري تحميل العرض..." : "Loading offer..."}</span>
        </div>
      </div>
    );
  }

  if (error || !offer || items.length === 0) {
    return (
      <div className="min-h-screen flex flex-col items-center justify-center gap-5 bg-white px-6 text-center">
        <h1 className="text-2xl font-bold text-secondary">
          {isAr ? "تعذر تحميل العرض" : "Unable to load this offer"}
        </h1>
        <button
          onClick={() => router.push("/offers")}
          className="rounded-full bg-primary px-7 py-3 font-bold text-white"
        >
          {isAr ? "العودة للعروض" : "Back to offers"}
        </button>
      </div>
    );
  }

  if (finished) {
    return (
      <div className="min-h-screen bg-[#F7F7F8] pt-[110px] px-4 pb-12" dir={isAr ? "rtl" : "ltr"}>
        <div className="mx-auto max-w-2xl rounded-[24px] bg-white p-8 md:p-10 text-center shadow-sm border border-[#F0E6EB]">
          <div className="mx-auto mb-5 flex h-16 w-16 items-center justify-center rounded-full bg-[#FFE3EE] text-3xl text-primary">✓</div>
          <h1 className="mb-3 text-2xl md:text-3xl font-bold text-secondary">
            {isAr ? "تم إكمال تخصيص العرض" : "Offer customization completed"}
          </h1>
          <p className="mb-6 leading-7 text-gray-600">
            {isAr
              ? "تمت إضافة العرض إلى السلة كوحدة واحدة وبسعر العرض المحدد."
              : "The offer has been added to the cart as one package using the offer price."}
          </p>

          <div className="mb-7 rounded-2xl bg-[#FFF6F9] p-4 text-secondary">
            <span className="font-semibold">{offer.name}</span>
            <span className="mx-2">—</span>
            <span className="font-bold text-primary">
              {formatPrice(offer.price)} {offer.currency?.symbol || offer.currency?.main_symbol || ""}
            </span>
          </div>

          <div className="flex flex-col sm:flex-row justify-center gap-3">
            <button
              onClick={() => {
                setFinished(false);
                setActiveStep(Math.max(items.length - 1, 0));
              }}
              className="rounded-full border border-primary px-6 py-3 font-bold text-primary"
            >
              {isAr ? "مراجعة الخطوات" : "Review steps"}
            </button>
            <button
              onClick={() => router.push("/offers")}
              className="rounded-full bg-primary px-6 py-3 font-bold text-white"
            >
              {isAr ? "العودة للعروض" : "Back to offers"}
            </button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-[#F4F4F4]" dir={isAr ? "rtl" : "ltr"}>
      {addingOfferToCart && (
        <div className="fixed inset-0 z-[9999] flex items-center justify-center bg-black/35">
          <div className="rounded-2xl bg-white px-7 py-5 text-center shadow-xl">
            <div className="mx-auto mb-3 h-9 w-9 animate-spin rounded-full border-4 border-pink-200 border-t-primary" />
            <p className="font-semibold text-secondary">
              {isAr ? "جاري إضافة العرض إلى السلة..." : "Adding offer to cart..."}
            </p>
          </div>
        </div>
      )}
      <div className="flex min-h-screen flex-col md:flex-row" dir="ltr">
        <main className={`min-w-0 flex-1 ${isAr ? "md:order-1" : "md:order-2"}`} dir={isAr ? "rtl" : "ltr"}>
          {currentItem?.product && productContext && (
              <ProductPageContent
                  key={`${offer.id}-${currentItem.id}-${activeStep}`}
                  params={{
                    id: String(currentItem.product.id),
                    slug: currentItem.product.slug || `product-${currentItem.product.id}`,
                  }}
                  offerContext={productContext}
              />
          )}
        </main>

        <aside
          dir={isAr ? "rtl" : "ltr"}
          className={`w-full shrink-0 bg-[#FFF0F5] md:sticky md:top-0 md:h-screen md:w-[300px] pt-[96px] md:pt-[115px] px-5 pb-8 border-[#F7D9E5] ${isAr ? "md:order-2 md:border-l" : "md:order-1 md:border-r"}`}
        >
          <div className="mb-5 border-b border-[#F3D2DE] pb-4">
            <h2 className="text-xl font-bold text-secondary">
              {isOfferEditMode
                ? (isAr ? "تعديل العرض" : "Edit offer")
                : (isAr ? "خطوات تخصيص العرض" : "Offer customization steps")}
            </h2>
            <div className="mt-2 flex items-center justify-between text-xs text-gray-600">
              <span>{offer.name}</span>
              <span className="font-bold text-primary">
                {formatPrice(offer.price)} {offer.currency?.symbol || offer.currency?.main_symbol || ""}
              </span>
            </div>
          </div>

          <div className="flex gap-3 overflow-x-auto pb-2 md:block md:space-y-1 md:overflow-visible">
            {items.map((item, index) => {
              const active = index === activeStep;
              const completed = completedSteps.includes(index);
              const canOpen = isOfferEditMode || completed || index <= activeStep;

              return (
                <button
                  key={item.id}
                  type="button"
                  disabled={!canOpen}
                  onClick={() => canOpen && setActiveStep(index)}
                  className={`relative flex min-w-[210px] items-start gap-3 rounded-xl px-3 py-4 text-start transition md:min-w-0 md:w-full ${
                    active ? "bg-white shadow-sm" : "bg-transparent"
                  } ${canOpen ? "cursor-pointer" : "cursor-not-allowed opacity-55"}`}
                >
                  <span
                    className={`flex h-8 w-8 shrink-0 items-center justify-center rounded-full border text-sm font-bold ${
                      active
                        ? "border-primary bg-primary text-white"
                        : completed
                          ? "border-primary bg-[#FFE0EC] text-primary"
                          : "border-[#E3DCE0] bg-white text-gray-500"
                    }`}
                  >
                    {completed && !active ? "✓" : index + 1}
                  </span>

                  <span className="min-w-0 pt-0.5">
                    <span className="block font-semibold text-secondary line-clamp-1">
                      {item.product?.name || (isAr ? "منتج" : "Product")}
                    </span>
                    <span className="mt-1 block text-xs leading-5 text-gray-500">
                      {item.variation_is_fixed && item.fixed_variation?.name
                        ? `${item.fixed_variation.name} • `
                        : ""}
                      {isAr ? `الكمية ${item.quantity}` : `Qty ${item.quantity}`}
                    </span>
                  </span>

                  {index < items.length - 1 && (
                    <span className="absolute bottom-[-8px] start-[27px] hidden h-4 w-px bg-[#FF8EB8] md:block" />
                  )}
                </button>
              );
            })}
          </div>

        </aside>
      </div>
    </div>
  );
}
