"use client";
import { FormButton } from "@/app/components/form/forms";
import { useState, useEffect, Suspense, lazy } from "react";
import Cookies from "js-cookie";
import withAuth from "@/app/hook/withAuth";

const VideoPlayer = lazy(() => import("@/app/components/measurement/VideoPlayer"));

interface MeasurementPayload {
  for_whom: string;
  name?: string;
  measurement_type: "men" | "women";
  measurement_data: Record<string, number | null>;
}

const STORAGE_KEY = "radioGender";

function StandardMeasurement({
  onClose,
  initialData = null,
}: {
  onClose: () => void;
  initialData?: {
    measurement_id: string;
    for_whom: string;
    name: string;
    measurement_type: "men" | "women";
    measurement_data: Record<string, number | null>;
  } | null;
}) {
  const [saveHeight, setSaveHeight] = useState<number | null>(48);
  const [saveWeight, setSaveWeight] = useState<number | null>(40);
  const [fullName, setFullName] = useState("");
  const [forWhom, setForWhom] = useState("myself");
  const [radioGender, setRadioGender] = useState<string>("gender_for_man");
  const [measurementData, setMeasurementData] = useState<Record<string, number>>({});

  const isEditing = !!initialData;

  useEffect(() => {
    // Load gender from localStorage if not in initial data
    const savedGender = localStorage.getItem(STORAGE_KEY);
    if (savedGender) {
      setRadioGender(savedGender);
    }

    if (initialData) {
      setFullName(initialData.name || "");
      setForWhom(initialData.for_whom || "myself");
      setRadioGender(
        initialData.measurement_type === "men" ? "gender_for_man" : "gender_for_woman"
      );

      const data = initialData.measurement_data || {};
      setSaveHeight(data.height ?? 48);
      setSaveWeight(data.weight ?? 40);

      const { height, weight, ...rest } = data;
      const filteredData: Record<string, number> = Object.fromEntries(
        Object.entries(rest).filter(([_, value]) => value !== null) as [string, number][]
      );
      setMeasurementData(filteredData);
    }
  }, [initialData]);

  const handleMeasurementChange = (label: string, value: number) => {
    const key = label
      .toLowerCase()
      .replace(/\s+/g, "_")
      .replace(/[^\w_]/g, "");
    setMeasurementData((prev) => ({ ...prev, [key]: value }));
  };

  const handleSubmit = async () => {
    // const trimmedName = fullName.trim();
    // if (!trimmedName) {
    //   alert("Please enter a full name");
    //   return;
    // }

    const payload: MeasurementPayload = {
      for_whom: forWhom,
      ////name: trimmedName,
      measurement_type: radioGender === "gender_for_man" ? "men" : "women",
      measurement_data: {
        height: saveHeight,
        weight: saveWeight,
        ...measurementData,
      },
    };

    console.log("Submitting payload:", payload);

    const id = initialData?.measurement_id;
    const endpoint = id
      ? `${process.env.NEXT_PUBLIC_APP_URL}/measurement/update/${id}`
      : `${process.env.NEXT_PUBLIC_APP_URL}/measurement/save`;

    try {
      const response = await fetch(endpoint, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${Cookies.get("token")}`,
        },
        body: JSON.stringify(payload),
      });

      const text = await response.text();

      if (response.ok) {
       /// alert(id ? "Measurement updated" : "Measurement added");
        console.log("Measurement saved successfully:", text);
        onClose();
      } else {
        console.error("Failed to save measurement:", text);
       /// alert("Failed to save measurement");
      }
    } catch (error) {
      console.error("Error while saving measurement:", error);
     /// alert("Error while saving measurement");
    }
  };

  const genderType = radioGender === "gender_for_man" ? "men" : "women";

  return (
    <>
      <div className="mx-auto flex w-full flex-col items-center justify-center gap-2 text-center md:w-[50%]">
        <h2 className="font-light">Custom size measurement</h2>
        <p className="text-sm font-light">
          Measurement videos will guide you on how to take the correct measurements.
        </p>
      </div>
      <div className="cc-vision-wrap">
        <div className="ccvision-scrollcontent">
          <div className="mx-auto flex w-full flex-col gap-10 md:w-[75%]">
            {radioGender}
            <Suspense>
              <VideoPlayer
                title="Tops"
                dataFileName={`${genderType}-top.json`}
                onMeasurementChange={handleMeasurementChange}
                measurementData={measurementData}
              />
            </Suspense>
            <Suspense>
              <VideoPlayer
                title="Bottoms"
                dataFileName={`${genderType}-bottom.json`}
                onMeasurementChange={handleMeasurementChange}
                measurementData={measurementData}
              />
            </Suspense>
          </div>
        </div>
        <div className="ccBottomBtnWrap">
          <FormButton
            id="btn_save_measurement"
            label="Save & Continue"
            type="submit"
            color="gray"
            hairline="blue"
            disabled={false}
            onClick={handleSubmit}
          />
        </div>
      </div>
    </>
  );
}

export default withAuth(StandardMeasurement);
