"use client";
import React, { useEffect, useState } from "react";
import { useWizardContext } from "../wizardContext";
import type { StepComponentProps } from "../wizardTypes";
import Image from "next/image";

const options = [
  {
    id: 1,
    type: "standard",
    title: "Standard Fit",
    description: "Share standard sizes, height / weight, and fit preferences.",
    image: "/custom_product/measurement-standard-fit.png",
    alt: "measurement-standard-fit",
  },
  {
    id: 2,
    type: "custom",
    title: "Custom Fit",
    description:
      "Measure yourself (guided) and fill out a form with exact body measurements.",
    image: "/custom_product/measurement-custom-fit.png",
    alt: "measurement-custom-fit",
  },
] as const;

type MeasurementType = (typeof options)[number]["type"];

interface ChooseMeasurementProps extends StepComponentProps {
  startPath?: string; // new optional prop for conditional logic
}

export default function ChooseMeasurement({
  onJump,
  jumpToStepId,
  setIsStepValid,
  activeGroupIdx,
  wizardDataGroupSteps,
  startPath,
}: ChooseMeasurementProps) {
  const { updateState } = useWizardContext();
  const [selectedType, setSelectedType] = useState<MeasurementType | null>(
    null,
  );

  // Jump based on selected type
  useEffect(() => {
    if (!selectedType) return;

    const targetStepId =
      selectedType === "standard"
        ? "standard_measurement"
        : "custom_measurement";

    const stepIdx = wizardDataGroupSteps.findIndex(
      (step) => step.id === targetStepId,
    );

    if (stepIdx !== -1 && typeof onJump === "function") {
      onJump(activeGroupIdx, stepIdx);
    } else {
      console.warn(`Could not find step: ${targetStepId}`);
      console.log(
        "Available step IDs:",
        wizardDataGroupSteps.map((s) => s.id),
      );
    }
  }, [selectedType, onJump, activeGroupIdx, wizardDataGroupSteps]);

  useEffect(() => {
    setIsStepValid(!!selectedType);
  }, [selectedType, setIsStepValid]);

  const handleSelect = (type: MeasurementType) => {
    setSelectedType(type);
    updateState("measurementType", type);
    if (typeof window !== "undefined") {
      localStorage.setItem("measurementType", type);
    }
  };

  const handleShareLater = () => {
    let targetStep = "vision_order_summary"; // default fallback

    if (startPath === "start-with-vision") {
      targetStep = "vision_order_summary";
    } else if (startPath === "morni-guidance") {
      targetStep = "guidance_order_summary";
    }

    if (typeof jumpToStepId === "function") {
      jumpToStepId(targetStep);
    }
  };

  return (
    <div className="mx-auto flex w-full flex-col items-center justify-center gap-8 md:w-[50%]">
      <div className="flex flex-col items-center gap-2 text-center">
        <h2 className="font-light">
          How would you like to share your{" "}
          <span className="font-medium">measurements</span>?
        </h2>
        <p className="text-sm font-light">
          Choose the method that works best for you.
        </p>
      </div>

      <div className="cc-vision-wrap">
        <div className="ccvision-scrollcontent noBottomBtn">
          <div className="gridItems mt-8">
            {options.map((option) => {
              const isSelected = selectedType === option.type;
              return (
                <button
                  key={option.type}
                  onClick={() => handleSelect(option.type)}
                  className={`flex flex-col items-center gap-2 border bg-gray-100 p-2 transition ${
                    isSelected
                      ? "border-2 border-green-400 bg-green-50"
                      : "border border-gray-950/50 hover:border-gray-950"
                  }`}
                >
                  <div className="border-1">
                    <Image
                      src={option.image}
                      alt={option.alt}
                      width={600}
                      height={600}
                      className="img-responsive"
                      priority={isSelected}
                    />
                  </div>
                  <div className="flex flex-col items-center gap-1 pb-2 font-light">
                    <p className="text-sm md:text-lg">{option.title}</p>
                    <p className="text-center text-xs">{option.description}</p>
                  </div>
                </button>
              );
            })}
          </div>
        </div>

        <div className="ccBottomBtnWrap">
          <button onClick={handleShareLater} className="btn-link">
            Share later
          </button>
        </div>
      </div>
    </div>
  );
}
