"use client";

import React, { useState } from "react";
import { useAtom } from "jotai";
import { Button, Checkbox } from "@heroui/react";
import { useTranslations } from "next-intl";
import { useLocale } from "next-intl";
import { useAppToast } from "@/app/[lang]/providers";
import { formAtom } from "@/components/state/autionAtoms";
import { buildAnimalPayload } from "@/(pages)/add-mazad/payload";
import { submitListing } from "@/actions/add-mazad-offer/mutation";
import { Step2 } from "@/(pages)/add-mazad/steps/step-2";
import { Step4 } from "@/(pages)/add-mazad/steps/step-4";
import { Step5 } from "@/(pages)/add-mazad/steps/step-5";
import { Step6 } from "@/(pages)/add-mazad/steps/step-6";
import { Step7 } from "@/(pages)/add-mazad/steps/step-7";
import RiyalIcon from "@/components/ui/RiyalIcon";
import PaymentMethodSelector from "@/components/payment/PaymentMethodSelector";
import { usePaymentSuccess } from "@/hooks/usePaymentSuccess";
import { usePaymentFailure } from "@/hooks/usePaymentFailure";
import { usePaymentCancelled } from "@/hooks/usePaymentCancelled";

interface AnnualAuctionSingleFormProps {
  participationFee: number;
  onSuccess?: (createdId?: string) => void;
}

export default function AnnualAuctionSingleForm({
  participationFee,
  onSuccess,
}: AnnualAuctionSingleFormProps) {
  const t = useTranslations("ANNUAL_GROUP_AUCTION");
  const locale = useLocale();
  const toast = useAppToast();

  usePaymentSuccess();
  usePaymentFailure();
  usePaymentCancelled();
  const [form, setForm] = useAtom(formAtom);
  const [submitting, setSubmitting] = useState(false);
  const [paying, setPaying] = useState(false);
  const [showPayment, setShowPayment] = useState(false);

  const [attemptedNext, setAttemptedNext] = useState(false);
  const [step2Valid, setStep2Valid] = useState(false);
  const [step4Valid, setStep4Valid] = useState(false);

  const steps = React.useMemo(
    () =>
      [
        { key: 1, label: t("participation.steps.conditions") },
        { key: 2, label: t("participation.steps.basic_info") },
        { key: 3, label: t("participation.steps.attachments") },
        { key: 4, label: t("participation.steps.details") },
        { key: 5, label: t("participation.steps.additional_info") },
        { key: 6, label: t("participation.steps.review") },
        { key: 7, label: t("participation.steps.payment") },
      ] as const,
    [t],
  );

  const lastDataStep = 6;
  const paymentStep = 7;

  const [uiStep, setUiStep] = useState<number>(1);

  const currentStepMeta = steps.find((s) => s.key === uiStep);
  const progressPercent = Math.max(
    0,
    Math.min(100, ((uiStep - 1) / (steps.length - 1)) * 100),
  );

  React.useEffect(() => {
    if (showPayment) {
      setUiStep(paymentStep);
    }
  }, [showPayment, paymentStep]);

  const gotoStep = (n: number) => {
    setAttemptedNext(false);
    setUiStep(n);
  };

  const validateAndNext = () => {
    setAttemptedNext(true);

    if (uiStep === 1) {
      if (!form.terms) {
        toast.error(t("alerts.accept_terms"));
        return;
      }
      gotoStep(2);
      return;
    }

    // Step 2 → Step2 component (classification / offer type)
    if (uiStep === 2) {
      if (!step2Valid) return;
      gotoStep(3);
      return;
    }

    // Step 3 → Step4 component (basic animal info)
    if (uiStep === 3) {
      if (!step4Valid) return;
      gotoStep(4);
      return;
    }

    // Step 4 → Step5 component (documents) - check uploads
    if (uiStep === 4) {
      if (form.files?.some((f: any) => f.uploading)) {
        toast.info(t("participation.alerts.upload_in_progress"));
        return;
      }
      gotoStep(5);
      return;
    }

    // Step 5 → Step6 component (location)
    if (uiStep === 5) {
      if (!form.country_id) {
        toast.error(t("participation.alerts.select_country"));
        return;
      }
      if (!form.state_id) {
        toast.error(t("participation.alerts.select_city"));
        return;
      }
      gotoStep(6);
      return;
    }
  };

  const handleContinue = async () => {
    if (submitting) return;
    setAttemptedNext(true);

    if (!form.terms) {
      toast.error(t("alerts.accept_terms"));
      return;
    }

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

    if (!form.files?.some((f) => f.collection_name === "main_image")) {
      toast.error(t("participation.alerts.main_image_required"));
      return;
    }

    try {
      setSubmitting(true);
      const payload = buildAnimalPayload(form);
      const res = await submitListing(payload, form.offer);
      const rawData = (res as any)?.data;
      const createdId =
        rawData && typeof rawData === "object" ? rawData.id : rawData;
      if (createdId) {
        setForm((p) => ({ ...p, createdId: String(createdId) }));
        setShowPayment(true);
      } else {
        toast.error(t("participation.alerts.missing_created_id"));
      }
    } catch (error: any) {
      const msg =
        error?.info?.message ||
        error?.message ||
        t("participation.alerts.submit_failed");
      toast.error(msg);
    } finally {
      setSubmitting(false);
    }
  };

  const rawCreatedId: any = form.createdId;
  const createdIdValue =
    rawCreatedId && typeof rawCreatedId === "object"
      ? (rawCreatedId.id ?? String(rawCreatedId))
      : rawCreatedId;

  const paymentParams = {
    payment_purpose: "publish_single_auction",
    single_auction_id: createdIdValue,
  };

  const handlePaymentSuccess = () => {
    onSuccess?.(String(createdIdValue));
  };

  return (
    <div
      className="h-dvh sm:h-[85vh] flex flex-col"
      dir={(locale || "").toLowerCase().startsWith("ar") ? "rtl" : "ltr"}
    >
      <div className="sticky top-0 z-10 border-b border-emerald-100 bg-gradient-to-b from-emerald-50 to-white">
        <div className="p-5">
          <div className="flex items-start justify-between gap-4">
            <div className="space-y-2">
              <div className="inline-flex items-center gap-2 rounded-full bg-white/70 backdrop-blur border border-emerald-100 px-3 py-1 text-xs font-bold text-emerald-900">
                <span>{t("participation.badge")}</span>
                <span className="text-slate-400">/</span>
                <span>{currentStepMeta?.label ?? ""}</span>
              </div>
              <h2 className="text-2xl md:text-3xl font-extrabold text-emerald-950">
                {t("participation.title")}
              </h2>
            </div>

            <div className="shrink-0 text-start hidden sm:block">
              <div className="text-xs text-slate-600">
                {t("participation.fee_label")}
              </div>
              <div className="mt-1 inline-flex items-center gap-1 rounded-xl bg-white border border-emerald-100 px-3 py-2 font-extrabold text-emerald-950">
                <span>{participationFee}</span>
                <RiyalIcon className="w-4 h-4" />
              </div>
            </div>
          </div>

          <div className="mt-4">
            <div className="h-2 rounded-full bg-emerald-100 overflow-hidden">
              <div
                className="h-full bg-gradient-to-r from-emerald-700 to-emerald-500"
                style={{ width: `${progressPercent}%` }}
              />
            </div>
            <div className="mt-3 flex items-center gap-2 overflow-x-hidden whitespace-nowrap pb-1">
              {steps.map((s) => {
                const isActive = uiStep === s.key;
                const isDone = uiStep > s.key;
                return (
                  <button
                    key={s.key}
                    type="button"
                    onClick={() => {
                      if (showPayment && s.key !== paymentStep) return;
                      if (s.key > lastDataStep && !showPayment) return;
                      if (s.key < uiStep) gotoStep(s.key);
                    }}
                    className={
                      "shrink-0 inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-sm font-bold transition " +
                      (isDone
                        ? "bg-emerald-700 text-white border-emerald-700"
                        : isActive
                          ? "bg-white text-emerald-900 border-emerald-300"
                          : "bg-white/60 text-slate-500 border-slate-200")
                    }
                  >
                    <span
                      className={
                        "w-6 h-6 rounded-full grid place-items-center text-xs font-extrabold " +
                        (isDone
                          ? "bg-white/15 text-white"
                          : isActive
                            ? "bg-emerald-50 text-emerald-800"
                            : "bg-slate-100 text-slate-500")
                      }
                    >
                      {isDone ? (
                        <svg
                          xmlns="http://www.w3.org/2000/svg"
                          className="w-3.5 h-3.5"
                          viewBox="0 0 24 24"
                          fill="none"
                          stroke="currentColor"
                          strokeWidth="3"
                          strokeLinecap="round"
                          strokeLinejoin="round"
                        >
                          <polyline points="20 6 9 17 4 12" />
                        </svg>
                      ) : (
                        s.key
                      )}
                    </span>
                    <span>{s.label}</span>
                  </button>
                );
              })}
            </div>
          </div>
        </div>
      </div>

      <div className="flex-1 overflow-y-auto p-5">
        {uiStep === 1 && (
          <div className="rounded-xl bg-white shadow-sm">
            <div className="p-5">
              <h3 className="text-lg font-extrabold text-emerald-950">
                {t("participation.conditions.title")}
              </h3>
              <p className="mt-1 text-sm text-slate-600">
                {t("participation.conditions.subtitle")}
              </p>
            </div>

            <div className="px-5 pb-5">
              <ul className="list-disc pr-6 text-sm text-slate-700 space-y-2 text-start">
                <li>{t("participation.conditions.items.policy")}</li>
                <li>{t("participation.conditions.items.documents")}</li>
                <li>
                  {t("participation.conditions.items.fee_prefix")}{" "}
                  <span className="inline-flex items-center gap-1">
                    <span>{participationFee}</span>
                    <RiyalIcon className="w-4 h-4" />
                  </span>{" "}
                  {t("participation.conditions.items.fee_suffix")}
                </li>
              </ul>

              <div className="mt-5 flex items-center justify-between gap-3 rounded-2xl border border-slate-100 bg-slate-50 p-4">
                <div className="text-sm font-bold text-slate-800">
                  {t("participation.conditions.agree_label")}
                </div>
                <Checkbox
                  isSelected={form.terms}
                  onValueChange={(v) => setForm((p) => ({ ...p, terms: v }))}
                />
              </div>
              {attemptedNext && !form.terms && (
                <p className="text-red-500 text-sm mt-2">
                  {t("alerts.accept_terms")}
                </p>
              )}
            </div>
          </div>
        )}

        {uiStep === 2 && (
          <div className="rounded-xl bg-white shadow-sm">
            <div className="p-5">
              <h3 className="text-lg font-extrabold text-emerald-950 text-start">
                {t("participation.sections.basic_info.title")}
              </h3>
              <p className="mt-1 text-sm text-slate-600">
                {t("participation.sections.basic_info.subtitle")}
              </p>
            </div>
            <div className="p-5 text-start text-sm">
              <Step2
                onValidChange={setStep2Valid}
                showErrors={attemptedNext}
              />
            </div>
          </div>
        )}

        {uiStep === 3 && (
          <div className="rounded-xl bg-white shadow-sm">
            <div className="p-5">
              <h3 className="text-lg font-extrabold text-start text-emerald-950">
                {t("participation.sections.attachments.title")}
              </h3>
              <p className="mt-1 text-sm text-slate-600">
                {t("participation.sections.attachments.subtitle")}
              </p>
            </div>
            <div className="p-5 text-start text-sm">
              <Step4
                onValidChange={setStep4Valid}
                showErrors={attemptedNext}
              />
            </div>
          </div>
        )}

        {uiStep === 4 && (
          <div className="rounded-xl bg-white shadow-sm">
            <div className="p-5">
              <h3 className="text-lg font-extrabold text-emerald-950 text-start">
                {t("participation.sections.details.title")}
              </h3>
              <p className="mt-1 text-sm text-slate-600">
                {t("participation.sections.details.subtitle")}
              </p>
            </div>
            <div className="p-5 text-start text-sm">
              <Step5 />
            </div>
          </div>
        )}

        {uiStep === 5 && (
          <div className="rounded-xl bg-white shadow-sm">
            <div className="p-5">
              <h3 className="text-lg font-extrabold text-emerald-950">
                {t("participation.sections.additional_info.title")}
              </h3>
              <p className="mt-1 text-sm text-slate-600">
                {t("participation.sections.additional_info.subtitle")}
              </p>
            </div>
            <div className="p-5 text-start text-sm">
              <Step6 showErrors={attemptedNext} hideMap />
            </div>
          </div>
        )}

        {uiStep === 6 && (
          <div className="rounded-xl bg-white shadow-sm">
            <div className="p-5">
              <h3 className="text-lg font-extrabold text-emerald-950">
                {t("participation.sections.review.title")}
              </h3>
              <p className="mt-1 text-sm text-slate-600">
                {t("participation.sections.review.subtitle")}
              </p>
            </div>
            <div className="p-5 text-start text-sm">
              <Step7 />
            </div>
          </div>
        )}

        {uiStep === paymentStep && (
          <div className="rounded-xl bg-white shadow-sm">
            <div className="p-5">
              <h3 className="text-lg font-extrabold text-emerald-950">
                {t("participation.sections.payment.title")}
              </h3>
              <p className="mt-1 text-sm text-slate-600">
                {t("participation.sections.payment.subtitle")}
              </p>
            </div>
            <div className="p-5">
              <PaymentMethodSelector
                amount={participationFee}
                paymentParams={paymentParams}
                onSuccess={handlePaymentSuccess}
                showSummary={true}
              />
            </div>
          </div>
        )}
      </div>

      <div className="sticky bottom-0 z-10 border-t border-emerald-100 bg-white/80 backdrop-blur">
        <div className="p-4 flex items-center justify-between gap-4">
          <div className="text-xs text-slate-600 hidden sm:block">
            {t("participation.footer.step", {
              current: uiStep,
              total: steps.length,
            })}
          </div>

          <div className="flex items-center gap-3">
            {uiStep !== 1 && uiStep !== paymentStep && (
              <Button
                variant="bordered"
                className="px-8 py-3 rounded-full text-base font-bold"
                onPress={() => gotoStep(Math.max(1, uiStep - 1))}
                isDisabled={submitting || paying}
              >
                {t("participation.actions.back")}
              </Button>
            )}

            {uiStep < lastDataStep && (
              <Button
                color="primary"
                className="bg-[#0f5132] hover:bg-[#114529] text-white px-8 py-3 rounded-full text-base font-bold"
                onPress={validateAndNext}
                isDisabled={submitting || paying}
              >
                {t("participation.actions.next")}
              </Button>
            )}

            {uiStep === lastDataStep && (
              <Button
                color="primary"
                className="bg-[#0f5132] hover:bg-[#114529] text-white px-8 py-3 rounded-full text-base font-bold"
                isLoading={submitting}
                onPress={handleContinue}
              >
                {t("participation.actions.continue")}
              </Button>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
