import { Button } from "@progress/kendo-react-buttons";
import { useEffect, useRef, useState } from "react";
import { TextBox, TextBoxChangeEvent } from "@progress/kendo-react-inputs";
import FactoryRenderer from "../../../../Renderer";

interface CreateScreenPopupProps {
  onViewToggle: () => void;
  create: (viewName: string) => Promise<void>;
  error?: string;
}

const VIEW_NAME_MAX_LENGTH = 25;

const CreateScreenPopup = (props: CreateScreenPopupProps) => {
  const [screenName, setScreenName] = useState("");
  const [validationError, setValidationError] = useState("");
  const popupRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        popupRef.current &&
        !popupRef.current.contains(event.target as Node)
      ) {
        popupRef.current.classList.add("tmpl-popup-animation-2-reverse");
        setTimeout(props.onViewToggle, 200);
      }
    };

    document.addEventListener("mousedown", handleClickOutside);

    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, []);

  const validateViewName = (value: string): string => {
    if (!value.trim()) return "Required";
    if (value.length > VIEW_NAME_MAX_LENGTH)
      return `Maximum ${VIEW_NAME_MAX_LENGTH} characters allowed`;
    return "";
  };

  const handleCreate = () => {
    const error = validateViewName(screenName);
    if (error) {
      setValidationError(error);
      return;
    }
    props.create(screenName.trim());
  };

  const onScreenNameChange = (e: TextBoxChangeEvent) => {
    const value = e.target.value?.toString() || "";
    setScreenName(value);
    setValidationError(validateViewName(value));
  };
  return (
    <div className="tmpl-screen-creater-popup" ref={popupRef}>
      <div className="tmpl-screen-creater-popup-header">
        <div>
          <h2>Create New View</h2>
        </div>
        <FactoryRenderer
          widgetStyle={{
            className: "qo-btn qo-text-default tmpl-button-sm",
          }}
          name="close"
          fillMode="clear"
          onClick={props.onViewToggle}
          uiElementType="WIDGET"
          widgetType="ICON"
          title=""
        />
      </div>
      <div className="tmpl-screen-creater-popup-body">
        <div className="tmpl-dropdown-container">
          <span>View Name <span style={{ color: "red", display: "inline" }}>*</span></span>
          <TextBox
            value={screenName}
            className="tmpl-input"
            placeholder="Type Here..."
            maxLength={VIEW_NAME_MAX_LENGTH}
            onChange={onScreenNameChange}
          />
          {validationError && (
            <span
              className="tmpl-error-message"
              style={{ color: "var(--qo-text-danger, red)" }}
            >
              {validationError}
            </span>
          )}
          {props.error && <span className="tmpl-error-message">{props.error}</span>}
        </div>
        <div className="tmpl-screen-creater-popup-footer">
          <Button
            title="Create"
            className="qo-btn qo-btn-primary qo-btn-md tmpl-button"
            onClick={handleCreate}
            disabled={!!validateViewName(screenName)}
          >
            Create
          </Button>
        </div>
      </div>
    </div>
  );
};
export default CreateScreenPopup;
