import { inputText } from "@lib/_common/util/surveyUtil";
import { addStyles } from "@lib/setupRoot";
import { createSignal, onMount } from "solid-js";
import stylesheetMain from "../styles/icu/modal.css?inline";
import { IcuPicker } from "./IcuPicker";
import { WinkPicker } from "./WinkPicker";

declare global {
  interface Window {
    upcsPickedArray: string[];
    setEyeglassesElements?: (_inputElm: HTMLInputElement, _submitBtn: HTMLButtonElement) => void;
  }
}

export function AppIcuPickerT3312() {
  const [isAppVisible, setIsAppVisible] = createSignal(true);
  const icuUpcsPicked = new Set<string>();
  const winkUpcsPicked = new Set<string>();

  let inputElm: HTMLInputElement | undefined = undefined;
  let submitBtn: HTMLButtonElement | undefined = undefined;

  onMount(() => {
    addStyles(stylesheetMain);

    window.setEyeglassesElements = (_inputElm: HTMLInputElement, _submitBtn: HTMLButtonElement) => {
      inputElm = _inputElm;
      submitBtn = _submitBtn;
    };
  });

  function handleIcuSubmit() {
    const upcsPickedArray = Array.from(icuUpcsPicked);
    console.log("Picked UPCs:", upcsPickedArray);

    window.upcsPickedArray = upcsPickedArray; // Expose the picked UPCs globally for debugging
    if (inputElm && submitBtn) {
      for (const upc of upcsPickedArray) {
        inputElm.value = upc;
        submitBtn.click();
      }
    }

    setIsAppVisible(() => false);

    // upcsPicked.forEach((upc) => {
    //   inputText(
    //     "Scan each out of stock item using your Store specific Scan Guide for the ICU CORE SIDECAP Fixture  ",
    //     upc,
    //     {
    //       clickSubmit: true,
    //       isRequireVisible: true,
    //     }
    //   );
    //   setIsAppVisible(() => false);
    // });
  }

  function handleWinkSubmit() {
    const upcsPickedArray = Array.from(winkUpcsPicked);
    console.log("Picked Wink UPCs:", upcsPickedArray);

    for (const upc of upcsPickedArray) {
      inputText(
        "SCAN each out of stock item using your Store specific Scan Guide for the ICU Wink SIDECAP Display.",
        upc,
        {
          clickSubmit: true,
        }
      );
    }
  }

  return (
    <div classList={{ "visually-hidden": !isAppVisible() }}>
      <div id="modal-icu-upc-picker">
        <div id="grids-container">
          <IcuPicker upcsPicked={icuUpcsPicked} onSubmit={handleIcuSubmit} />
          <WinkPicker upcsPicked={winkUpcsPicked} onSubmit={handleWinkSubmit} />
        </div>
      </div>
    </div>
  );
}
