"use client";
import React, { useEffect, useState } from "react";
import { FormButton } from "@/app/components/form/forms";
import TextArea from "@/app/components/form/TextArea";
import { useSearchParams } from "next/navigation";
import { getApiClient } from "@/utils/apiClient";
import { getUserSessionId } from "@/utils/helper";

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

const STORAGE_KEY = "piece_note_share";

export default function PieceNoteShare({
  updateState = () => {},
  jumpToNext = () => {},
  state = {},
}: Props) {
  const [noteShare, setNoteShare] = useState<string>(state.piece_note_share || "");

    const searchParams = useSearchParams();
    const externalId = searchParams.get("external");
    const [hasMeasurement, setHasMeasurement] = useState("FALSE");


  useEffect(() => {
    if (!state.piece_note_share) {
      const saved = localStorage.getItem(STORAGE_KEY);
      if (saved && saved !== noteShare) {
        setNoteShare(saved);
        updateState("piece_note_share", saved);
      }
    }
  }, [noteShare, state.piece_note_share, updateState]);

  const handleSubmit = (e: React.SyntheticEvent<HTMLFormElement>) => {
    e.preventDefault();
    const trimmed = noteShare.trim();
    updateState("piece_note_share", trimmed);
    localStorage.setItem(STORAGE_KEY, trimmed);
    jumpToNext();
  };

  const handleChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    setNoteShare(e.target.value);
  };
 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) {
          
          setHasMeasurement(apiData.has_measurement || "FALSE");
         
        }
    
        console.log("Loaded external wizard data");
      } catch (error) {
        console.error("Failed to fetch wizard data:", error);
      }
    };
    console.log("hasMeasurement", hasMeasurement);
  return (
    <form onSubmit={handleSubmit}>
      <div className="mx-auto flex w-full flex-col items-center justify-center gap-10 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">Anything else you{"'"}d like to share?  </h2>
          <p className="text-xs/4 md:text-sm font-light">
            Any additional thoughts, style ideas, or personal touches you envision for this piece.
          </p>
        </div>

        <div className="cc-vision-wrap">
          <div className="ccvision-scrollcontent">
            <div className="mx-auto mt-10 flex w-full flex-col md:w-[50%]">
              <TextArea
                label=""
                name="cc_note_share"
                maxLength={1000}
                placeholder="Type your answer here"
                showLimitMessage={true}
                required={false}
                value={noteShare}
                onChange={handleChange}
              />
            </div>
          </div>

          <div className="ccBottomBtnWrap">
            <FormButton
              id="btn_cc_note_share"
              label="Save Note"
              type="submit"
              color="gray"
              hairline="blue"
            />
          </div>
        </div>
      </div>
    </form>
  );
}
