"use client";

import { useMemo, useState, useEffect, useRef } from "react";
import { useAtom } from "jotai";
import {
  stepAtom,
  maxStep,
  formAtom,
  computedFeeAtom,
  resetAuctionAtoms,
  auctionConfigAtom,
  auctionConfigLoadingAtom,
  formDirtyAtom,
  videoUploadingAtom,
} from "@/components/state/autionAtoms";
import { getAuctionConfig } from "@/actions/config-mazad";
import { Button, Input as HeroInput, Select, SelectItem } from "@heroui/react";
import { clsx } from "clsx";
import { Step1 } from "./steps/step-1";
import { Step2 } from "./steps/step-2";
import { Step3 } from "./steps/step-3";
import { Step4 } from "./steps/step-4";
import { Step5 } from "./steps/step-5";
import { Step6 } from "./steps/step-6";
import { Step7 } from "./steps/step-7";
import { Step8 } from "./steps/step-8";
import { Step9 } from "./steps/step-9";
import { useTranslations } from "next-intl";
import { useAppToast } from "@/app/[lang]/providers";
import { submitListing } from "@/actions/add-mazad-offer/mutation";
import { buildAnimalPayload } from "./payload";
import { usePathname, useRouter } from "next/navigation";
import { useAtomCallback } from "jotai/utils";
import { BaseModal } from "@/components/modal";
import { PhoneNumber } from "@/components";
import { useRefundMethod, useUpdateRefundMethods } from "@/lib/clientQueries";
import { useLocale } from "next-intl";
import { useQueryClient } from "@tanstack/react-query";

export default function AddListingWizard() {
  const t = useTranslations("ADD_LISTING");
  const lang = useLocale();
  const [step, setStep] = useAtom(stepAtom);
  const [form, setForm] = useAtom(formAtom);
  const [fee] = useAtom(computedFeeAtom);
  const [step1Loading, setStep1Loading] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [step1Valid, setStep1Valid] = useState(false);
  const [step2Valid, setStep2Valid] = useState(false);
  const [step4Valid, setStep4Valid] = useState(false);
  const [attemptedNext, setAttemptedNext] = useState(false);
  const [successModalOpen, setSuccessModalOpen] = useState(false);
  const [refundGateOpen, setRefundGateOpen] = useState(false);
  const [refundSetupType, setRefundSetupType] = useState<"stc" | "bank">(
    "bank",
  );
  const [refundStcName, setRefundStcName] = useState("");
  const [refundStcPhone, setRefundStcPhone] = useState("");
  const [bankType, setBankType] = useState<"local" | "worldwide">("local");
  const [bankNameInput, setBankNameInput] = useState("");
  const [bankUserName, setBankUserName] = useState("");
  const [bankIban, setBankIban] = useState("");
  const [bankSwift, setBankSwift] = useState("");
  const toast = useAppToast();
  const pathname = usePathname();
  const router = useRouter();
  const queryClient = useQueryClient();
  const lastPathRef = useRef<string | null>(null);
  const { data: refundMethod, isLoading: refundLoading } = useRefundMethod();
  const { mutateAsync: updateRefundMethods, isPending: isSavingRefund } =
    useUpdateRefundMethods();
  const [config, setConfig] = useAtom(auctionConfigAtom);
  console.log("🚀 ~ AddListingWizard ~ config:", config);
  const [configLoading, setConfigLoading] = useAtom(auctionConfigLoadingAtom);
  const [formDirty, setFormDirty] = useAtom(formDirtyAtom);
  const [videoUploading] = useAtom(videoUploadingAtom);
  const [showLeaveWarning, setShowLeaveWarning] = useState(false);
  const [pendingNavigation, setPendingNavigation] = useState<string | null>(
    null,
  );

  const resetAll = useAtomCallback((get, set) => {
    resetAuctionAtoms(set);
  });

  // Reload config on mount if form has animal_type but config is missing (e.g., after page refresh)
  useEffect(() => {
    if (form.animal_type && !config && !configLoading) {
      (async () => {
        try {
          setConfigLoading(true);
          const data = await getAuctionConfig(
            form.animal_type as "horse" | "camel",
          );
          setConfig(data);
        } catch (error) {
          console.error("Error reloading auction config:", error);
        } finally {
          setConfigLoading(false);
        }
      })();
    }
  }, [form.animal_type, config, configLoading]);

  // Mark form as dirty when user makes changes (after step 1)
  useEffect(() => {
    if (step > 1 && form.animal_type) {
      setFormDirty(true);
    }
  }, [step, form]);

  // Handle confirmed navigation
  const handleConfirmLeave = () => {
    setFormDirty(false);
    setShowLeaveWarning(false);
    resetAll();
    if (pendingNavigation) {
      router.push(pendingNavigation);
      setPendingNavigation(null);
    }
  };

  const handleCancelLeave = () => {
    setShowLeaveWarning(false);
    setPendingNavigation(null);
  };

  // إذا تغيّر المسار أثناء وجود الويزارد، صفّر الفورم واحذف localStorage
  useEffect(() => {
    if (lastPathRef.current === null) {
      lastPathRef.current = pathname;
      return;
    }
    if (pathname !== lastPathRef.current) {
      // Only reset if navigating away from add form
      if (!pathname.includes("tab=add")) {
        resetAll();
        if (typeof window !== "undefined") {
          window.localStorage.removeItem("ataya_auction_form");
          window.localStorage.removeItem("ataya_auction_config");
        }
      }
      lastPathRef.current = pathname;
    }
  }, [pathname, resetAll]);

  const minDate = useMemo(() => {
    const d = new Date();
    d.setDate(d.getDate() + 3);
    return d.toISOString().slice(0, 10);
  }, []);

  const offerListingFee =
    config?.fees_setting?.offer_listing_fee != null
      ? Number(config.fees_setting.offer_listing_fee) || 0
      : 500;
  console.log("🚀 ~ AddListingWizard ~ offerListingFee:", offerListingFee);

  const auctionListingFee =
    config?.fees_setting?.auction_listing_fee != null
      ? Number(config.fees_setting.auction_listing_fee) || 0
      : 1500;
  console.log("🚀 ~ AddListingWizard ~ auctionListingFee:", auctionListingFee);

  function goto(n: number) {
    setAttemptedNext(false);
    setStep(Math.max(1, Math.min(maxStep, n)));
  }

  async function next() {
    setAttemptedNext(true);

    if (step === 1) {
      if (refundLoading) {
        toast.info(t("alerts.checking"));
        return;
      }

      if (!refundMethod?.method) {
        setRefundGateOpen(true);
        return;
      }
    }

    if (step === 1 && !step1Valid) return;
    if (step === 2 && !step2Valid) return;
    if (step === 4 && !step4Valid) return;

    if (
      (step === 5 || step === 7) &&
      form.files?.some((f: any) => f.uploading)
    ) {
      toast.info(t("alerts.upload_in_progress"));
      return;
    }

    if (!validate(step)) return;
    if (step === 2 && form.offer === "fixed") {
      goto(4);
      return;
    }
    // في المزاد الجماعي: لا توجد جدولة، تخطَّ الخطوة 3
    if (
      step === 2 &&
      form.offer === "auction" &&
      form.auction_type === "annual"
    ) {
      goto(4);
      return;
    }
    if (step === 7) {
      if (submitting) return;
      (async () => {
        try {
          setSubmitting(true);
          const payload = buildAnimalPayload(form);
          const res = await submitListing(payload, form.offer);
          console.log("🚀 ~ next ~ res:", res);
          const rawData = (res as any)?.data;
          const createdId =
            rawData && typeof rawData === "object" ? rawData.id : rawData;
          if (createdId) {
            setForm((p) => ({ ...p, createdId: String(createdId) }));
            goto(8);
          } else {
            toast.error(t("alerts.missing_id"));
          }
        } catch (e: any) {
          const msg =
            e?.info?.message || e?.message || t("alerts.create_failed");
          toast.error(msg);
        } finally {
          setSubmitting(false);
        }
      })();
      return;
    }
    // في الخطوة 8 (مراجعة الإعلان)، ننتقل مباشرة إلى خطوة الدفع 9
    if (step === 8) {
      goto(9);
      return;
    }
    goto(step + 1);
  }

  function prev() {
    if (step === 4 && form.offer === "fixed") goto(2);
    else if (
      step === 4 &&
      form.offer === "auction" &&
      form.auction_type === "annual"
    )
      goto(2);
    else goto(step - 1);
  }

  function validate(n: number) {
    if (n === 2) {
      if (!form.terms) {
        toast.error(t("alerts.accept_terms"));
        return false;
      }
      if (form.offer === "auction" && !form.auction_type) {
        toast.error(t("alerts.auction_type_required_hardcoded"));
        return false;
      }
      if (form.offer === "fixed" && !form.fixedPrice) {
        toast.error(t("alerts.set_price"));
        return false;
      }
    }
    if (n === 3) {
      // لا نتحقق من التواريخ في المزاد الجماعي لأنه لا يستخدم الجدولة
      if (form.offer === "auction" && form.auction_type !== "annual") {
        if (!form.startDate || !form.startTime) {
          toast.error(t("alerts.select_date_time"));
          return false;
        }
        if (form.startDate < minDate) {
          toast.error(t("alerts.date_too_soon"));
          return false;
        }

        if (form.auction_type === "electronic" && form.startTime) {
          const [h, m] = form.startTime.split(":").map((v) => Number(v));
          if (!Number.isNaN(h) && !Number.isNaN(m) && form.unavailableTimes) {
            const selectedMinutes = h * 60 + m;
            const hasConflict = form.unavailableTimes.some((t) => {
              const [bh, bm] = String(t)
                .split(":")
                .map((v) => Number(v));
              if (Number.isNaN(bh) || Number.isNaN(bm)) return false;
              const blockedStart = bh * 60 + bm;
              const blockedEnd = blockedStart + 15;
              return (
                selectedMinutes >= blockedStart && selectedMinutes < blockedEnd
              );
            });

            if (hasConflict) {
              toast.error(t("alerts.time_unavailable"));
              return false;
            }
          }
        }
      }
    }
    if (n === 6) {
      if (!form.country_id) {
        toast.error(t("alerts.select_country"));
        return false;
      }
      if (!form.state_id) {
        toast.error(t("alerts.select_city"));
        return false;
      }
      const la = Number(form.lat);
      const ln = Number(form.lng);
      if (
        !Number.isFinite(la) ||
        !Number.isFinite(ln) ||
        la < -90 ||
        la > 90 ||
        ln < -180 ||
        ln > 180
      ) {
        toast.error(t("alerts.invalid_coordinates"));
        return false;
      }
    }
    if (n === 7) {
      if (!form.files?.some((f) => f.collection_name === "main_image")) {
        toast.error(t("alerts.main_image_required"));
        return false;
      }
    }
    return true;
  }

  const visibleSteps = useMemo(() => {
    const items: { id: number; label: string }[] = [];

    for (let n = 1; n <= maxStep; n++) {
      if (n === 3 && form.offer === "fixed") continue;
      if (n === 3 && form.offer === "auction" && form.auction_type === "annual")
        continue;

      let label = "";
      if (n === 1) label = t("steps.platform");
      else if (n === 2) label = t("steps.category");
      else if (n === 3) label = t("steps.schedule");
      else if (n === 4) label = t("steps.basic_info");
      else if (n === 5) label = t("steps.documents");
      else if (n === 6) label = t("steps.location");
      else if (n === 7) label = t("steps.media");
      else if (n === 8) label = t("steps.review");
      else if (n === 9) label = t("steps.payment");

      items.push({ id: n, label });
    }

    return items;
  }, [form.offer, form.auction_type, t]);

  const Stepper = (
    <div className="flex gap-2 overflow-x-auto pb-2 hide-scrollbar">
      {visibleSteps.map((item, index) => {
        const displayIndex = index + 1;
        const active = item.id <= step;

        return (
          <div
            key={item.id}
            className={clsx(
              "flex items-center gap-2 text-sm whitespace-nowrap",
              active && "font-bold text-g1",
            )}
          >
            <span
              className={clsx(
                "w-7 h-7 grid place-items-center rounded-full bg-slate-200",
                active && "bg-primary! text-white",
              )}
            >
              {displayIndex}
            </span>
            {item.label}
          </div>
        );
      })}
    </div>
  );

  return (
    <>
      <div className="space-y-4 overflow-auto">
        <div className="flex items-center justify-between pb-3 border-b border-gray-100">
          <div className="text-xl font-extrabold text-g1">{t("title")}</div>
          <div className="text-xs text-slate-500">
            {t("fees", {
              offerFee: offerListingFee,
              auctionFee: auctionListingFee,
            })}
          </div>
        </div>

        <div>
          {Stepper}

          <div className="mt-4 text-start!">
            {step === 1 && (
              <Step1
                onValidChange={setStep1Valid}
                onLoadingChange={setStep1Loading}
              />
            )}
            {step === 2 && (
              <Step2
                onValidChange={setStep2Valid}
                showErrors={attemptedNext}
              />
            )}
            {step === 3 && <Step3 showErrors={attemptedNext} />}
            {step === 4 && (
              <Step4
                onValidChange={setStep4Valid}
                showErrors={attemptedNext}
              />
            )}
            {step === 5 && <Step5 />}
            {step === 6 && <Step6 showErrors={attemptedNext} />}
            {step === 7 && <Step7 />}
            {step === 8 && <Step9 />}
            {step === 9 && (
              <Step8
                onSuccess={() => {
                  resetAll();
                  goto(1);
                  router.push(
                    form.offer === "fixed"
                      ? "/dashboard?tab=listings"
                      : "/dashboard?tab=auctions",
                  );
                }}
              />
            )}
          </div>
        </div>
      </div>
      <div className="flex items-center justify-between gap-3 pt-6">
        <Button variant="flat" isDisabled={step === 1} onPress={prev}>
          {t("buttons.back")}
        </Button>
        <div className="flex items-center gap-3">
          {step < 9 && (
            <Button
              color="primary"
              onPress={() => void next()}
              isDisabled={step1Loading || (step === 1 && !step1Valid)}
              isLoading={step1Loading || submitting}
            >
              {t("buttons.next")}
            </Button>
          )}
        </div>
      </div>

      <BaseModal
        isOpen={successModalOpen}
        onOpenChange={setSuccessModalOpen}
        placement="center"
        contentClassName="max-w-md rounded-2xl p-4 text-center"
        title={t("alerts.submitted")}
      >
        <div className="space-y-4">
          <p className="text-sm text-slate-600">{t("alerts.submitted_desc")}</p>

          <div className="grid grid-cols-1 gap-3">
            <Button
              fullWidth
              variant="flat"
              onPress={() => {
                setSuccessModalOpen(false);
              }}
            >
              {t("success_modal.new_listing")}
            </Button>
            <Button
              fullWidth
              color="primary"
              onPress={() => {
                setSuccessModalOpen(false);
                router.push(
                  form.offer === "fixed"
                    ? "/dashboard?tab=listings"
                    : "/dashboard?tab=auctions",
                );
              }}
            >
              {t("success_modal.go_to_dashboard")}
            </Button>
          </div>
        </div>
      </BaseModal>

      <BaseModal
        isOpen={refundGateOpen}
        onOpenChange={setRefundGateOpen}
        placement="center"
        isDismissable={false}
        isKeyboardDismissDisabled
        contentClassName="w-full max-w-[560px] rounded-2xl p-0 overflow-hidden"
        title={t("refund_modal.title")}
      >
        <div className="px-5 py-4">
          <div className="text-xs text-slate-500 text-start">
            {t("refund_modal.description")}
          </div>

          <div className="mt-4 rounded-2xl bg-slate-100 p-1 flex gap-1">
            <Button
              fullWidth
              className={
                refundSetupType === "stc"
                  ? "bg-primary text-white rounded-xl font-semibold shadow-sm"
                  : "bg-transparent rounded-xl font-semibold text-slate-700"
              }
              variant={refundSetupType === "stc" ? "solid" : "light"}
              onPress={() => setRefundSetupType("stc")}
            >
              {t("refund_modal.stc_pay")}
            </Button>
            <Button
              fullWidth
              className={
                refundSetupType === "bank"
                  ? "bg-primary text-white rounded-xl font-semibold shadow-sm"
                  : "bg-transparent rounded-xl font-semibold text-slate-700"
              }
              variant={refundSetupType === "bank" ? "solid" : "light"}
              onPress={() => setRefundSetupType("bank")}
            >
              {t("refund_modal.bank_account")}
            </Button>
          </div>

          <div className="mt-4">
            {refundSetupType === "stc" ? (
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                <HeroInput
                  label={t("refund_modal.full_name")}
                  placeholder={t("refund_modal.full_name_placeholder")}
                  value={refundStcName}
                  onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
                    setRefundStcName(e.target.value)
                  }
                />
                <PhoneNumber
                  label={t("refund_modal.stc_phone_label")}
                  phoneValue={refundStcPhone}
                  setPhoneValue={setRefundStcPhone}
                />
              </div>
            ) : (
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                <Select
                  label={t("refund_modal.account_type_label")}
                  selectedKeys={new Set([bankType])}
                  onSelectionChange={(keys) => {
                    const val = Array.from(keys).at(0) as string | undefined;
                    setBankType(val === "worldwide" ? "worldwide" : "local");
                  }}
                >
                  <SelectItem key="local">{t("refund_modal.local")}</SelectItem>
                  <SelectItem key="worldwide">
                    {t("refund_modal.worldwide")}
                  </SelectItem>
                </Select>

                <HeroInput
                  label={t("refund_modal.full_name")}
                  placeholder={t("refund_modal.full_name_placeholder")}
                  value={bankUserName}
                  onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
                    setBankUserName(e.target.value)
                  }
                />

                <HeroInput
                  label={t("refund_modal.bank_name_label")}
                  placeholder={t("refund_modal.bank_name_placeholder")}
                  value={bankNameInput}
                  onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
                    setBankNameInput(e.target.value)
                  }
                />

                <HeroInput
                  label={t("refund_modal.iban_label")}
                  placeholder={t("refund_modal.iban_placeholder")}
                  value={bankIban}
                  onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
                    setBankIban(e.target.value)
                  }
                />

                {bankType === "worldwide" && (
                  <HeroInput
                    label={t("refund_modal.swift_label")}
                    placeholder={t("refund_modal.swift_placeholder")}
                    value={bankSwift}
                    onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
                      setBankSwift(e.target.value)
                    }
                  />
                )}
              </div>
            )}
          </div>
        </div>

        <div className="border-t border-slate-100 px-5 py-4 flex flex-col sm:flex-row gap-3">
          <Button
            fullWidth
            variant="flat"
            onPress={() => setRefundGateOpen(false)}
            isDisabled={isSavingRefund}
          >
            {t("refund_modal.cancel")}
          </Button>
          <Button
            fullWidth
            color="primary"
            isLoading={isSavingRefund}
            isDisabled={
              isSavingRefund ||
              (refundSetupType === "stc" &&
                (!refundStcName || !refundStcPhone)) ||
              (refundSetupType === "bank" &&
                (!bankNameInput ||
                  !bankUserName ||
                  !bankIban ||
                  (bankType === "worldwide" && !bankSwift)))
            }
            onPress={() => {
              (async () => {
                try {
                  if (refundSetupType === "stc") {
                    await updateRefundMethods({
                      method: "stcp",
                      details: { name: refundStcName, phone: refundStcPhone },
                    });
                  } else {
                    await updateRefundMethods({
                      method: "bank_transfer",
                      details: {
                        bank_type: bankType,
                        bank_name: bankNameInput,
                        user_name: bankUserName,
                        iban: bankIban,
                        ...(bankType === "worldwide" && bankSwift
                          ? { swift: bankSwift }
                          : {}),
                      },
                    });
                  }

                  await queryClient.invalidateQueries({
                    queryKey: ["refund-method"],
                  });

                  toast.success(t("refund_modal.refund_saved_success"));
                  setRefundGateOpen(false);
                  goto(2);
                } catch (error: any) {
                  const msg =
                    error?.response?.data?.message ||
                    error?.message ||
                    t("refund_modal.refund_save_failed_hardcoded");
                  toast.error(msg);
                }
              })();
            }}
          >
            {t("refund_modal.save_and_continue")}
          </Button>
        </div>
      </BaseModal>

      {/* Navigation Warning Modal */}
      <BaseModal
        isOpen={showLeaveWarning}
        onOpenChange={setShowLeaveWarning}
        placement="center"
        isDismissable={false}
        isKeyboardDismissDisabled
        contentClassName="max-w-md rounded-2xl p-0 overflow-hidden"
        title="تنبيه"
      >
        <div className="p-5">
          <div className="text-center">
            <div className="w-16 h-16 mx-auto mb-4 rounded-full bg-amber-100 flex items-center justify-center">
              <span className="text-3xl">⚠️</span>
            </div>
            <h3 className="text-lg font-bold text-slate-900 mb-2">
              {t("navigation_modal.leave_title")}
            </h3>
            <p className="text-sm text-slate-600">
              {t("navigation_modal.leave_description")}
            </p>
            {videoUploading && (
              <p className="text-sm text-amber-600 mt-2 font-medium">
                {t("navigation_modal.video_uploading")}
              </p>
            )}
          </div>
        </div>
        <div className="border-t border-slate-100 px-5 py-4 flex gap-3">
          <Button fullWidth variant="flat" onPress={handleCancelLeave}>
            {t("navigation_modal.continue_editing")}
          </Button>
          <Button
            fullWidth
            color="danger"
            onPress={handleConfirmLeave}
            isDisabled={videoUploading}
          >
            {t("navigation_modal.leave")}
          </Button>
        </div>
      </BaseModal>
    </>
  );
}
