"use client";
import React, {
  useState,
  Children,
  useRef,
  useLayoutEffect,
  useImperativeHandle,
  forwardRef,
} from "react";
import { motion, AnimatePresence } from "motion/react";
import { useLocale } from "next-intl";

interface StepLabel {
  step: number;
  label: string;
}

export interface StepperRef {
  goToNext: () => void;
  goToPrevious: () => void;
  goToStep: (step: number) => void;
  currentStep: number;
  totalSteps: number;
  isFirstStep: boolean;
  isLastStep: boolean;
}

interface StepperProps extends React.HTMLAttributes<HTMLDivElement> {
  children: React.ReactNode;
  initialStep?: number;
  onStepChange?: (step: number) => void;
  onFinalStepCompleted?: () => void;
  stepCircleContainerClassName?: string;
  stepContainerClassName?: string;
  contentClassName?: string;
  disableStepIndicators?: boolean;
  renderStepIndicator?: (props: {
    step: number;
    currentStep: number;
    onStepClick: (clicked: number) => void;
  }) => React.ReactNode;
  stepLabels?: StepLabel[];
}

interface StepIndicatorProps {
  step: number;
  currentStep: number;
  onClickStep: (step: number) => void;
  disableStepIndicators?: boolean;
  label?: string;
}

interface StepConnectorProps {
  isComplete: boolean;
  isRTL: boolean;
}

interface StepContentWrapperProps {
  isCompleted: boolean;
  currentStep: number;
  direction: number;
  isRTL: boolean;
  children: React.ReactNode;
  className?: string;
}

interface SlideTransitionProps {
  children: React.ReactNode;
  direction: number;
  isRTL: boolean;
  onHeightReady: (height: number) => void;
}

const Stepper = forwardRef<StepperRef, StepperProps>(
  (
    {
      children,
      initialStep = 1,
      onStepChange = () => {},
      onFinalStepCompleted = () => {},
      stepCircleContainerClassName = "",
      stepContainerClassName = "",
      contentClassName = "",
      disableStepIndicators = false,
      renderStepIndicator,
      stepLabels = [] as StepLabel[],
      ...rest
    },
    ref
  ) => {
    const locale = useLocale();
    const isRTL = locale === "ar";
    const [currentStep, setCurrentStep] = useState(initialStep);
    const [direction, setDirection] = useState(0);
    const stepsArray = Children.toArray(children);
    const totalSteps = stepsArray.length;
    const isCompleted = currentStep > totalSteps;
    const isLastStep = currentStep === totalSteps;
    const isFirstStep = currentStep === 1;

    const updateStep = (newStep: number) => {
      setCurrentStep(newStep);
      if (newStep > totalSteps) {
        onFinalStepCompleted();
      } else {
        onStepChange(newStep);
      }
    };

    const handleBack = () => {
      if (currentStep > 1) {
        setDirection(-1);
        updateStep(currentStep - 1);
      }
    };

    const handleNext = () => {
      if (!isLastStep) {
        setDirection(1);
        updateStep(currentStep + 1);
      }
    };

    const goToStep = (step: number) => {
      if (step >= 1 && step <= totalSteps) {
        setDirection(step > currentStep ? 1 : -1);
        updateStep(step);
      }
    };

    useImperativeHandle(ref, () => ({
      goToNext: handleNext,
      goToPrevious: handleBack,
      goToStep,
      currentStep,
      totalSteps,
      isFirstStep,
      isLastStep,
    }));

    return (
      <div {...rest}>
        <div
          className={`w-full rounded-[2rem] ${stepCircleContainerClassName}`}
        >
          <div
            className={`flex w-full items-start pb-10 ${stepContainerClassName}`}
          >
            {stepsArray.map((_, index) => {
              const stepNumber = index + 1;
              const isNotLastStep = index < totalSteps - 1;
              const stepLabelData = stepLabels.find(
                (sl) => sl.step === stepNumber
              );
              const stepLabel = stepLabelData?.label || "";
              return (
                <React.Fragment key={stepNumber}>
                  <div className="flex flex-col items-center shrink-0 relative">
                    {renderStepIndicator ? (
                      renderStepIndicator({
                        step: stepNumber,
                        currentStep,
                        onStepClick: (clicked) => {
                          setDirection(clicked > currentStep ? 1 : -1);
                          updateStep(clicked);
                        },
                      })
                    ) : (
                      <StepIndicator
                        step={stepNumber}
                        disableStepIndicators={disableStepIndicators}
                        currentStep={currentStep}
                        onClickStep={(clicked) => {
                          setDirection(clicked > currentStep ? 1 : -1);
                          updateStep(clicked);
                        }}
                        label={stepLabel}
                      />
                    )}
                  </div>
                  {isNotLastStep && (
                    <StepConnector
                      isComplete={currentStep > stepNumber}
                      isRTL={isRTL}
                    />
                  )}
                </React.Fragment>
              );
            })}
          </div>

          <StepContentWrapper
            isCompleted={isCompleted}
            currentStep={currentStep}
            direction={direction}
            isRTL={isRTL}
            className={`relative overflow-hidden ${contentClassName}`}
          >
            {stepsArray[currentStep - 1]}
          </StepContentWrapper>
          {/* 
        {!isCompleted && !hideButtons && (
          <div className={`footer-container ${footerClassName}`}>
            <div
              className={`footer-nav ${currentStep !== 1 ? "spread" : "end"}`}
            >
              {currentStep !== 1 && (
                <button
                  onClick={handleBack}
                  className={`back-button ${
                    currentStep === 1 ? "inactive" : ""
                  }`}
                  {...backButtonProps}
                >
                  {backButtonText}
                </button>
              )}
              <button
                onClick={isLastStep ? handleComplete : handleNext}
                className="next-button"
                {...nextButtonProps}
              >
                {isLastStep ? "Complete" : nextButtonText}
              </button>
            </div>
          </div>
        )} */}
        </div>
      </div>
    );
  }
);

Stepper.displayName = "Stepper";

export default Stepper;

function StepContentWrapper({
  isCompleted,
  currentStep,
  direction,
  isRTL,
  children,
  className,
}: StepContentWrapperProps) {
  const [parentHeight, setParentHeight] = useState(0);

  return (
    <motion.div
      className={className}
      style={{ position: "relative", overflow: "hidden" }}
      animate={{ height: isCompleted ? 0 : parentHeight }}
      transition={{ type: "spring", duration: 0.4 }}
    >
      <AnimatePresence initial={false} mode="sync" custom={direction}>
        {!isCompleted && (
          <SlideTransition
            key={currentStep}
            direction={direction}
            isRTL={isRTL}
            onHeightReady={(h) => setParentHeight(h)}
          >
            {children}
          </SlideTransition>
        )}
      </AnimatePresence>
    </motion.div>
  );
}

function SlideTransition({
  children,
  direction,
  isRTL,
  onHeightReady,
}: SlideTransitionProps) {
  const containerRef = useRef<HTMLDivElement>(null);

  useLayoutEffect(() => {
    if (containerRef.current) onHeightReady(containerRef.current.offsetHeight);
  }, [children, onHeightReady]);

  const stepVariants = {
    enter: (dir: number) => {
      // For RTL (Arabic): next step comes from right (100%), previous from left (-100%)
      // For LTR (English): next step comes from left (-100%), previous from right (100%)
      if (isRTL) {
        return {
          x: dir >= 0 ? "100%" : "-100%",
          opacity: 0,
        };
      } else {
        return {
          x: dir >= 0 ? "-100%" : "100%",
          opacity: 0,
        };
      }
    },
    center: {
      x: "0%",
      opacity: 1,
    },
    exit: (dir: number) => {
      // For RTL (Arabic): current step exits to left (-50%), previous to right (50%)
      // For LTR (English): current step exits to right (50%), previous to left (-50%)
      if (isRTL) {
        return {
          x: dir >= 0 ? "-50%" : "50%",
          opacity: 0,
        };
      } else {
        return {
          x: dir >= 0 ? "50%" : "-50%",
          opacity: 0,
        };
      }
    },
  };

  return (
    <motion.div
      ref={containerRef}
      custom={direction}
      variants={stepVariants}
      initial="enter"
      animate="center"
      exit="exit"
      transition={{ duration: 0.4 }}
      style={{ position: "absolute", left: 0, right: 0, top: 0 }}
    >
      {children}
    </motion.div>
  );
}

export function Step({ children }: { children: React.ReactNode }) {
  return <div className="">{children}</div>;
}

function StepIndicator({
  step,
  currentStep,
  onClickStep,
  disableStepIndicators,
  label,
}: StepIndicatorProps) {
  const status =
    currentStep === step
      ? "active"
      : currentStep < step
      ? "inactive"
      : "complete";

  const handleClick = () => {
    if (step !== currentStep && !disableStepIndicators) onClickStep(step);
  };

  return (
    <div className="flex flex-col items-center">
      <motion.div
        onClick={handleClick}
        className="relative cursor-pointer outline-none flex items-center justify-center"
        animate={status}
        initial={false}
        style={{ height: "24px" }}
      >
        <motion.div
          variants={{
            inactive: {
              scale: 1,
              backgroundColor: "#9FBABA",
              color: "#ffffff",
            },
            active: { scale: 1, backgroundColor: "#a3ae28", color: "#ffffff" },
            complete: {
              scale: 1,
              backgroundColor: "#27AE60",
              color: "#ffffff",
            },
          }}
          transition={{ duration: 0.3 }}
          className="flex h-6 w-6 items-center justify-center rounded-full font-semibold"
        >
          {status === "complete" ? (
            <CheckIcon className="h-4 w-4 text-white" />
          ) : (
            <span className="text-[12px] font-light text-white">{step}</span>
          )}
        </motion.div>
      </motion.div>
      {label && (
        <span className="mt-2 text-center text-[12px] sm:text-[16px] text-secondary-dark font-bold whitespace-nowrap">
          {label}
        </span>
      )}
    </div>
  );
}

function StepConnector({ isComplete, isRTL }: StepConnectorProps) {
  const lineVariants = {
    incomplete: { width: 0, backgroundColor: "transparent" },
    complete: { width: "100%", backgroundColor: "#f7f9d6" },
  };

  return (
    <div
      className="relative mx-1 h-px flex-1 overflow-hidden rounded bg-gray-48"
      style={{ marginTop: "11.5px" }}
    >
      <motion.div
        className="absolute top-0 h-full"
        variants={lineVariants}
        initial={false}
        animate={isComplete ? "complete" : "incomplete"}
        transition={{ duration: 0.4 }}
        style={{
          [isRTL ? "right" : "left"]: 0,
          [isRTL ? "left" : "right"]: "auto",
        }}
      />
    </div>
  );
}

function CheckIcon(props: React.SVGProps<SVGSVGElement>) {
  return (
    <svg
      {...props}
      fill="none"
      stroke="currentColor"
      strokeWidth={2}
      viewBox="0 0 24 24"
    >
      <motion.path
        initial={{ pathLength: 0 }}
        animate={{ pathLength: 1 }}
        transition={{
          delay: 0.1,
          type: "tween",
          ease: "easeOut",
          duration: 0.3,
        }}
        strokeLinecap="round"
        strokeLinejoin="round"
        d="M5 13l4 4L19 7"
      />
    </svg>
  );
}
