import { getApiClient } from "@/utils/apiClient";
import { getUserSessionId } from "@/utils/helper";
import { useSearchParams } from "next/navigation";
import React, { useEffect, useState } from "react";

interface Props {
  setIsStepValid: (isValid: boolean) => void;
  updateState: (key: string, value: any) => void;
  jumpToNext: () => void;
  state: { gender?: string };
}

const STORAGE_KEY = "genderExpression";

export default function GenderExpression({
  setIsStepValid,
  updateState,
  jumpToNext,
  state,
}: Props) {
  const [selectedGender, setSelectedGender] = useState<string>(
    state?.gender || "",
  );

  const searchParams = useSearchParams();
  const externalId = searchParams.get("external");

  useEffect(() => {
    setIsStepValid(!!selectedGender);
    const saved = localStorage.getItem(STORAGE_KEY);
    if (saved && saved !== selectedGender) {
      setSelectedGender(saved);
      updateState?.("gender", saved);
    }
  }, [updateState, selectedGender, setIsStepValid]);

 
  const handleChange = (gender: string) => {
    setSelectedGender(gender);
    updateState?.("gender", gender);
    localStorage.setItem(STORAGE_KEY, gender);
    jumpToNext?.();
  };

  useEffect(() => {
    if (externalId) {
      fetchExternalWizardData(externalId);
    }
  }, [externalId]);

  const fetchExternalWizardData = async (id: string) => {
    try {
      const apiData = await getApiClient(
        `co-creation/wizard/${id}?session_id=${getUserSessionId()}`,
      );

      if (apiData) {
        if (
          apiData.gender != "null" &&
          apiData.gender !== null &&
          apiData.gender !== undefined
        ) {
          localStorage.setItem("genderExpression", apiData.gender);
          setSelectedGender(apiData.gender);
        }
      }
    } catch (error) {
      console.error("Failed to fetch wizard data:", error);
    }
  };

  const genderOptions = ["Masculine", "Feminine", "Neutral"];

  return (
    <div className="relative z-20">
      <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="vision">
            Which <span className="font-medium">gender expression</span> best
            fits the look you{"'"}re going for?
          </h2>
        </div>
        <div className="mt-8 flex flex-col gap-4 md:mt-20">
          {genderOptions.map((option) => (
            <label
              key={option}
              onClick={() => handleChange(option)}
              className={`relative cursor-pointer border-1 bg-gray-100/50 px-10 py-4 text-center font-medium capitalize transition-all duration-300 ${
                selectedGender === option
                  ? "border-1 border-dashed border-green-400 bg-gray-100"
                  : "border-gray-500 hover:border-gray-950 hover:bg-gray-100"
              }`}
            >
              {selectedGender === option && (
                <div className="absolute top-2 right-2 flex h-6 w-6 items-center justify-center rounded-full border-2 border-gray-100 bg-green-400 align-middle">
                  <i className="icon-[qlementine-icons--check-tick-16] text-white"></i>
                </div>
              )}
              <input
                type="radio"
                name="gender"
                value={option}
                checked={selectedGender === option}
                onChange={() => {}}
                className="sr-only"
              />
              <span className="text-sm font-light">{option}</span>
            </label>
          ))}
        </div>
      </div>
    </div>
  );
}
