"use client";

import React, { useEffect, useState } from "react";
import Image from "next/image";
import type { StepComponentProps } from "../wizardTypes";
import { useWizardContext } from "../wizardContext";
import { FormButton } from "@/app/components/form/forms";
import { useSearchParams } from "next/navigation";
import { getUserSessionId } from "@/utils/helper";

export interface ColorProps {
  id: string;
  color: string;
  value: string;
}

const STORAGE_KEY = "preferredColor";
const DEFAULT_COLOR = "#FFFFFF";

export default function PreferredColor({ jumpToNext }: StepComponentProps) {
  const { updateState, state } = useWizardContext();
  const [selectedColorIndex, setSelectedColorIndex] = useState(0);
  const [selectedColor, setSelectedColor] = useState('#ffffff');
  const [hydrated, setHydrated] = useState(false);
  const [colorData, setColorData] = useState<ColorProps[]>([]);

  const searchParams = useSearchParams();
  const externalId = searchParams.get("external");
//// alert(process.env.NEXT_PUBLIC_API_BASE_URL);
  useEffect(() => {
    async function fetchColorData() {

     
      try {
        const res = await fetch(
          `${process.env.NEXT_PUBLIC_API_BASE_URL}/co-creation/color-family?external_id=${externalId}&session_id=${getUserSessionId()}`
        );
        const data = await res.json();

        if (Array.isArray(data.data)) {
          const hasWhite = data.data.some(
            (c: ColorProps) => c.color.toLowerCase() === DEFAULT_COLOR.toLowerCase()
          );
          const enrichedData = hasWhite
            ? data.data
            : [{ id: "default", color: DEFAULT_COLOR, value: "White" }, ...data.data];
        

          const L = enrichedData.findIndex(
            (c: ColorProps) => c.color.toLowerCase() === data.selected_color.toLowerCase()
          );
          localStorage.setItem('preferredColor', data.selected_color);
           setSelectedColorIndex(L >= 0 ? L : 0);
          setColorData(enrichedData);
        }


      } catch (error) {
        console.error("Failed to fetch color data:", error);
      }
    }

    fetchColorData();
  }, [externalId]);

  useEffect(() => {
    setHydrated(true);
    if (!colorData.length) return;

    const storedColor = localStorage.getItem(STORAGE_KEY);
    let index = -1;

    if (storedColor) {
      index = colorData.findIndex(
        (c: ColorProps) => c.color.toLowerCase() === storedColor.toLowerCase()
      );
    } else if (state?.preferredColor) {
      index = colorData.findIndex(
        (c: ColorProps) => c.color.toLowerCase() === state.preferredColor.toLowerCase()
      );
    }

    if (index === -1) {
      index = colorData.findIndex(
        (c: ColorProps) => c.color.toLowerCase() === DEFAULT_COLOR.toLowerCase()
      );
    }

    setSelectedColorIndex(index >= 0 ? index : 0);
  }, [colorData, state?.preferredColor]);


  const handleChange = (index: number) => {
    setSelectedColorIndex(index);
    const selected = colorData[index];
    updateState("preferredColor", selected.color);
    localStorage.setItem(STORAGE_KEY, selected.color);
  };
const determineInitialIndex = () => {
  const storedColor = localStorage.getItem(STORAGE_KEY);
  let index = -1;

  if (storedColor) {
    index = colorData.findIndex(
      (c) => c.color.toLowerCase() === storedColor.toLowerCase()
    );
  } else if (state?.preferredColor) {
    index = colorData.findIndex(
      (c) => c.color.toLowerCase() === state.preferredColor.toLowerCase()
    );
  }

  if (index === -1) {
    index = colorData.findIndex(
      (c) => c.color.toLowerCase() === DEFAULT_COLOR.toLowerCase()
    );
  }

  return index >= 0 ? index : 0;
};
  if (!hydrated || !colorData.length) return null;

  const selectedStep = colorData[selectedColorIndex];

  return (
    <div className="mx-auto flex w-full flex-col items-center justify-center gap-4 text-center">
      <div>
        <h2 className="vision">
          What is your preferred <span className="font-medium">color</span>?
        </h2>
        <p className="hidden md:flex text-xs/4 md:text-sm">
          We{"'"}ll perfect the exact tone together during our design flow.
        </p>
      </div>
      <div className="cc-vision-wrap">
        <div className="ccvision-scrollcontent">
          <div className="flex w-full flex-col-reverse items-center justify-between align-middle md:flex-row gap-1 md:gap-2">
            <div className="flex w-full flex-col md:w-2/3">

              <div className="flex w-full flex-col">
                <label
                  htmlFor="color-range"
                  className="block text-sm capitalize"
                >
                  <span className="font-light">{selectedStep?.value}</span>
                </label>
                <div className="relative flex h-16 md:h-24 w-full flex-col">
                  <div className="absolute top-0 left-0 flex h-full w-full flex-row items-center justify-center align-middle">
                    {colorData &&
                      colorData.map((step, i) => (
                        <div
                          key={i}
                          className="relative mx-auto flex flex-1 items-center justify-center align-middle"
                        >
                          <span
                            className={`hairline-thred-color flex h-3.75 w-3.75 shadow-gray-950 transition-all duration-100 md:h-7 md:w-7 lg:h-10 lg:w-10 ${
                              i === selectedColorIndex
                                ? "border-gray-950 opacity-0"
                                : ""
                            }`}
                            title={step.value}
                            style={{ backgroundColor: step.color }}
                          />
                        </div>
                      ))}
                  </div>
                  <div className="fabricRangeSlider relative -mt-0 flex flex-col items-center justify-center rounded-r-full align-middle md:mt-0.5">
                    <input
                      id="color-range"
                      type="range"
                      min={0}
                      max={colorData.length - 1}
                      step={1}
                      value={selectedColorIndex}
                      onChange={(e) => handleChange(Number(e.target.value))}
                      style={
                        {
                          "--thumb-color": selectedStep?.color,
                          "--fill-color": selectedStep?.color,
                          accentColor: selectedStep?.color,
                        } as React.CSSProperties
                      }
                      className="absolute top-0 left-0 h-16 md:h-24 w-full cursor-pointer px-3"
                    />
                  </div>
                </div>
              </div>
            </div>
            <div className="flex w-full flex-col items-center justify-center align-middle md:w-[25%]">
              <div className="relative h-64 w-64 overflow-hidden">
                <div className="border-1">
                  <Image
                    src="/custom_product/bg-fabric-flower.png"
                    alt="fabric flower"
                    width={400}
                    height={400}
                    className="img-responsive"
                  />
                </div>
                <div
                  className="icon-cc-fabric-flower absolute top-[11.5%] left-[11%] h-[95%] w-[89%]"
                  style={{
                    backgroundColor: selectedStep?.color,
                    mixBlendMode: "multiply",
                    opacity: 0.88,
                  }}
                ></div>
              </div>
            </div>
          </div>
        </div>

        <div className="ccBottomBtnWrap">
          <FormButton
            id="btn_cc_save-preferred_color"
            label="Save Color"
            type="submit"
            color="gray"
            hairline="blue"
            disabled={false}
            onClick={() => jumpToNext?.()}
          />
        </div>
      </div>
    </div>
  );
}
