"use client";
import { Button } from "@/components/ui/button";
import { IoIosArrowForward, IoIosArrowBack } from "react-icons/io";
import { useLocale, useTranslations } from "next-intl";
import { StepperRef } from "./Stepper/Stepper";
import { useState, useEffect } from "react";
import { useFormContext } from "react-hook-form";

interface NavigationButtonsProps {
  stepperRef?: React.RefObject<StepperRef>;
  isSubmitting?: boolean;
  // False until the terms are accepted on the last step
  canSubmit?: boolean;
  isTrial?: boolean;
}

export default function NavigationButtons({
  stepperRef,
  isSubmitting,
  canSubmit = true,
  isTrial = false,
}: NavigationButtonsProps) {
  const locale = useLocale();
  const isRTL = locale === "ar";
  const t = useTranslations("SubscribePage");
  const [isFirstStep, setIsFirstStep] = useState(false);
  const [isLastStep, setIsLastStep] = useState(false);
  const { trigger } = useFormContext();

  useEffect(() => {
    const updateState = () => {
      if (stepperRef?.current) {
        setIsFirstStep(stepperRef.current.isFirstStep);
        setIsLastStep(stepperRef.current.isLastStep);
      }
    };

    updateState();
    // Update state when stepper changes
    const interval = setInterval(updateState, 100);
    return () => clearInterval(interval);
  }, [stepperRef]);

  const handleBack = () => {
    stepperRef?.current?.goToPrevious();
  };

  const handleNext = async () => {
    let isValid = false;

    // Validate based on current step
    // Note: This relies on knowing which fields are in which step.
    // Ideally Stepper should tell us the index.
    // Assuming simple mapping for now:
    // Step 1 (Index 0): Basic Info
    // Step 2 (Index 1): Company Info
    // Step 3 (Index 2): Terms (None/Checkbox?)

    const currentStep = stepperRef?.current?.currentStep ?? 1;

    if (currentStep === 1) {
      isValid = await trigger([
        "user_name",
        "phone",
        "email",
        "password",
        "password_confirmation",
      ]);
    } else if (currentStep === 2) {
      isValid = await trigger([
        "name",
        "activity",
        "address",
        "location",
        "description",
      ]);
    } else {
      isValid = true; // Terms step usually validation happens via submit or checkbox
    }

    if (isValid) {
      stepperRef?.current?.goToNext();
    }
  };

  return (
    <div className="flex justify-between">
      <Button
        variant="outline"
        size="icon"
        className="border-secondary-dark text-secondary-dark hover:bg-secondary-dark hover:text-primary-main"
        onClick={handleBack}
        disabled={isFirstStep || isSubmitting}
        type="button"
      >
        {isRTL ? (
          <IoIosArrowForward className="size-4" />
        ) : (
          <IoIosArrowBack className="size-4" />
        )}
        <span>{t("back")}</span>
      </Button>

      {isLastStep ? (
        <Button
          className="bg-secondary-dark text-white hover:bg-secondary-main"
          type="submit"
          disabled={isSubmitting || !canSubmit}
        >
          {isSubmitting ? "..." : isTrial ? t("startTrial") : t("submit")}
        </Button>
      ) : (
        <Button
          className="bg-secondary-dark text-white hover:bg-secondary-main"
          onClick={handleNext}
          disabled={isSubmitting}
          type="button"
        >
          <span>{t("next")}</span>
          {isRTL ? (
            <IoIosArrowBack className="size-4" />
          ) : (
            <IoIosArrowForward className="size-4" />
          )}
        </Button>
      )}
    </div>
  );
}
