"use client";
import React, { useEffect, useState } from "react";
import { useWizardContext } from "../wizardContext";
import type { StepComponentProps } from "../wizardTypes";
import { FormButton } from "@/app/components/form/forms";
import Cookies from "js-cookie";
import withAuth from "@/app/hook/withAuth";

interface MeasurementItem {
  id: string;
  label: string;
  size: string | number;
}

interface Props {
  jumpToNext?: () => void;
  jumpToStepId: () => void;
}

interface MeasurementProps extends StepComponentProps {
  startPath?: string;
}

const TOP_KEYS = [
  "neck_around",
  "neck_depth",
  "shoulder_across",
  "cross_back",
  "mid_back",
  "armhole",
  "bicep",
  "chest_full",
  "chest_upper",
  "mid_top_waist",
  "lower_top_waist",
  "shirt_regular_length",
  "shirt_crop",
  "shirt_long",
  "jacket_length",
  "full_sleeve",
  "three_fourth_sleeve",
  "short_sleeve",
  "wrist",
  "neck_round",
  "shoulder_accross",
  "back_depth",
  "under_bust",
  "sleeve_length",
  "biceps",
  "elbow",
  "waist",
  "hip",
  "shirt_full_length",
  "shirt_crop_length",
  "shirt_medium_length",
  "full_body_length",
];

const BOTTOM_KEYS = [
  "waist",
  "thigh",
  "bottom_length",
  "short_length",
  "crotch_length",
  "knee",
  "ankel",
  "high_waist",
  "mid_waist",
  "low_waist",
  "hips",
  "ankle",
  "pants_full_length",
];

function SavedMeasurement({
  jumpToStepId,
  setIsStepValid,
  activeGroupIdx,
  jumpToNext,
  wizardDataGroupSteps,
  startPath,
}: MeasurementProps) {
  const { updateState } = useWizardContext();
  const [resultData, setResultData] = useState<any[]>([]);
  const [selectedMeasurementId, setSelectedMeasurementId] = useState<string>();
  const [loading, setLoading] = useState(false);

  const handleAddMeasurement = () => {
    jumpToNext?.();
  };

  const formatLabel = (key: string) => {
    return key.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
  };

  const fetchMeasurements = async () => {
    setLoading(true);
    try {
      const response = await fetch(`${process.env.API_BASE_URL}/measurement/index`, {
        method: "GET",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${Cookies.get("token")}`,
        },
      });

      const result = await response.json();

      if (result.success && result.data.length > 0) {
        setResultData(result.data);
        setSelectedMeasurementId(String(result.data[0].measurement_id)); // set first as default
      } else {
        setResultData([]);
      }
    } catch (error) {
      console.error("Failed to fetch measurements", error);
      setResultData([]);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchMeasurements();
  }, []);

  const selectedEntry = resultData.find(
    (item) => String(item.measurement_id) === String(selectedMeasurementId),
  );

  const handleContinueMeasurement = () => {
    let targetStep = "vision_order_summary";

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

    if (typeof jumpToStepId === "function") {
      jumpToStepId(targetStep);
    }
    console.log(selectedEntry);
  };

  return (
    <>
      <div className="mx-auto flex w-full flex-col items-center justify-center gap-8 align-middle">
        <div className="mx-auto flex w-full flex-col items-center justify-center gap-2 text-center md:w-[50%]">
          <h2 className="font-light">
            Your saved <span className="font-medium">measurement(s)</span>
          </h2>
          <p className="text-sm font-light">Choose any one option or add new</p>
        </div>

        <div className="cc-vision-wrap">
          <div className="ccvision-scrollcontent">
            <div className="mx-auto flex w-full flex-col items-center justify-center gap-4">
              <div className="relative mx-auto flex w-full flex-col border-1 border-gray-950/25 bg-gray-100 md:w-[50%]">
                <span className="absolute right-1 flex h-full w-8 items-center justify-center align-middle md:right-4">
                  <i className="icon-[fluent--chevron-up-down-24-filled]"></i>
                </span>
                <select
                  name="SavedMeasurement"
                  className="relative z-10 cursor-pointer bg-transparent p-4 px-2 text-sm font-medium capitalize md:px-8 md:text-base"
                  value={selectedMeasurementId}
                  onChange={(e) => setSelectedMeasurementId(e.target.value)}
                >
                  {resultData.map((option) => (
                    <option
                      key={option.measurement_id}
                      value={String(option.measurement_id)}
                    >
                      {option.name} - ({option.for_whom},{" "}
                      {option.measurement_type})
                    </option>
                  ))}
                </select>
              </div>

              {selectedEntry && (
                <div className="mx-auto flex w-full flex-col bg-gray-100/50 p-4 md:w-[80%] md:p-10">
                  <div className="font-bogart flex flex-col items-center justify-center text-center text-lg md:text-xl">
                    Height {selectedEntry.measurement_data.height} cm / Weight{" "}
                    {selectedEntry.measurement_data.weight} kg.
                  </div>

                  <div className="py-4">
                    <h5 className="font-bogart">Top (in inches)</h5>
                    <ul className="no-list flex flex-wrap gap-2">
                      {Object.entries(selectedEntry.measurement_data)
                        .filter(([key]) => TOP_KEYS.includes(key))
                        .map(([key, value]) => (
                          <li
                            key={key}
                            className="flex items-center gap-1 border-1 border-gray-950/20 bg-gray-100/50 px-2.5 py-1.25 align-middle text-xs capitalize"
                          >
                            <span>{formatLabel(key)}</span> -{" "}
                            <span className="text-sm font-semibold">
                              {typeof value === "string" ||
                              typeof value === "number"
                                ? value
                                : ""}
                            </span>
                          </li>
                        ))}
                    </ul>
                  </div>

                  <div className="py-2">
                    <h5 className="font-bogart">Bottom (in inches)</h5>
                    <ul className="no-list flex flex-wrap gap-2">
                      {Object.entries(selectedEntry.measurement_data)
                        .filter(([key]) => BOTTOM_KEYS.includes(key))
                        .map(([key, value]) => (
                          <li
                            key={key}
                            className="flex items-center gap-1 border-1 border-gray-950/20 bg-gray-100/50 px-2.5 py-1.25 align-middle text-xs capitalize"
                          >
                            <span>{formatLabel(key)}</span> -{" "}
                            <span className="text-sm font-semibold">
                              {typeof value === "string" ||
                              typeof value === "number"
                                ? value
                                : ""}
                            </span>
                          </li>
                        ))}
                    </ul>
                  </div>
                </div>
              )}
            </div>
            <div className="mx-auto flex w-full flex-col items-center justify-center pt-4 md:w-1/3">
              <button
                type="button"
                onClick={handleAddMeasurement}
                className="mt-4 flex w-full flex-col items-center justify-between border-1 border-dashed p-2 text-center transition-all duration-300 hover:bg-gray-100"
              >
                <p className="text-xs/4 font-light">
                  You can add new measurement
                </p>
                <p className="text-base/4 font-medium uppercase">Add New</p>
              </button>
            </div>
          </div>

          <div className="ccBottomBtnWrap">
            <FormButton
              id="btn_add_new_measurement"
              label="Continue"
              type="submit"
              color="gray"
              hairline="blue"
              onClick={handleContinueMeasurement}
            />
          </div>
        </div>
      </div>
    </>
  );
}
export default withAuth(SavedMeasurement);
