"use client";
import { useRef } from "react";
import Stepper, { Step, StepperRef } from "./Stepper/Stepper";
import NavigationButtons from "./NavigationButtons";
import BasicInfoCard from "./BasicInfoCard";
import CompanyInfoCard from "./CompanyInfoCard";
import TermsAndConditionsCard from "./TermsAndConditionsCard";
import PackageSummaryCard from "./PackageSummaryCard";

import { useForm, FormProvider } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import {
  createSubscriptionSchema,
  SubscriptionFormData,
} from "@/lib/schemas/subscription";
import { useTranslations } from "next-intl";
import { useState } from "react";
import { toast } from "sonner";
import { Package } from "@/types/package";
import { Policy } from "@/types/policy";
import { useSearchParams } from "next/navigation";

interface StepperWrapperProps {
  stepLabels: { step: number; label: string }[];
  locale: string;
  packages: Package[];
  // Set when signing up for the free trial (/subscribe?trial)
  trialPackage?: Package | null;
  terms?: Policy | null;
}

export default function StepperWrapper({
  stepLabels,
  locale,
  packages,
  trialPackage = null,
  terms,
}: StepperWrapperProps) {
  const isTrial = !!trialPackage;
  const stepperRef = useRef<StepperRef | null>(null);
  const t = useTranslations("SubscribePage");
  const tValidation = useTranslations("Validation");
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [agreedToTerms, setAgreedToTerms] = useState(false);

  const subscriptionSchema = createSubscriptionSchema((key) =>
    tValidation(key),
  );

  const searchParams = useSearchParams();
  const packageIdFromUrl = searchParams.get("package_id") || "";
  const durationFromUrl =
    searchParams.get("duration") === "year" ? "year" : "month";

  const methods = useForm<SubscriptionFormData>({
    resolver: zodResolver(subscriptionSchema),
    mode: "onBlur",
    defaultValues: {
      country: "saudi arabia",
      city: "riyadh",
      // The trial is priced on the monthly cycle (0), which makes the backend
      // activate it immediately for the package's trial days
      package_id: trialPackage?.uuid ?? packageIdFromUrl,
      pay_type: isTrial ? "month" : durationFromUrl,
    },
  });

  const onSubmit = async (data: SubscriptionFormData) => {
    setIsSubmitting(true);
    try {
      const selectedPackage = [...packages, ...(trialPackage ? [trialPackage] : [])].find(
        (pkg) => pkg.uuid === data.package_id,
      );
      const submissionData = {
        ...data,
        package_id: selectedPackage
          ? selectedPackage.id.toString()
          : data.package_id,
      };

      const { createSubscription } =
        await import("@/services/subscriptionService");
      const result = await createSubscription(submissionData, locale);

      if (result.status === 1) {
        toast.success(t("submissionSuccess") || "Submitted successfully!");
        // Store package_id and pay_type for success/failed page summary
        localStorage.setItem("selected_package_id", data.package_id);
        localStorage.setItem("selected_pay_type", data.pay_type);
        window.location.href =
          result.data.payment_url ||
          (isTrial ? "/subscribe/success?trial" : "/subscribe/success");
      } else {
        console.error("Submission failed:", result);
        toast.error(
          result.message || t("submissionError") || "Submission failed",
        );

        if (result.data && typeof result.data === "object") {
          const serverErrors = result.data as Record<string, string[]>;
          const step1Fields = [
            "user_name",
            "phone",
            "email",
            "password",
            "password_confirmation",
          ];
          const step2Fields = [
            "name",
            "activity",
            "address",
            "location",
            "description",
          ];

          let firstErrorStep = -1;

          Object.entries(serverErrors).forEach(([field, messages]) => {
            let errorMessage = messages[0];
            if (errorMessage === "The email has already been taken.") {
              errorMessage = tValidation("emailTaken");
            } else if (errorMessage === "The phone has already been taken.") {
              errorMessage = tValidation("phoneTaken");
            }

            methods.setError(field as keyof SubscriptionFormData, {
              type: "server",
              message: errorMessage,
            });

            if (firstErrorStep === -1 || firstErrorStep > 1) {
              if (step1Fields.includes(field)) firstErrorStep = 1;
              else if (step2Fields.includes(field) && firstErrorStep !== 1)
                firstErrorStep = 2;
            }
          });

          if (firstErrorStep !== -1) {
            stepperRef.current?.goToStep(firstErrorStep);
          }
        }
      }
    } catch (error) {
      console.error("Error submitting form:", error);
      toast.error(
        t("submissionError") || "Failed to submit form. Please try again.",
      );
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <FormProvider {...methods}>
      <form onSubmit={methods.handleSubmit(onSubmit)}>
        <div className="space-y-6">
          <Stepper
            ref={stepperRef}
            renderStepIndicator={undefined}
            stepLabels={stepLabels}
            disableStepIndicators={true}
          >
            <Step>
              <BasicInfoCard />
            </Step>
            <Step>
              <CompanyInfoCard />
            </Step>
            <Step>
              <TermsAndConditionsCard
                terms={terms}
                isTrial={isTrial}
                agreed={agreedToTerms}
                onAgreedChange={setAgreedToTerms}
              />
            </Step>
          </Stepper>
          <NavigationButtons
            stepperRef={stepperRef as React.RefObject<StepperRef>}
            isSubmitting={isSubmitting}
            canSubmit={agreedToTerms}
            isTrial={isTrial}
          />
          <PackageSummaryCard packages={packages} trialPackage={trialPackage} />
        </div>
      </form>
    </FormProvider>
  );
}
