import { DropDownList } from "@progress/kendo-react-dropdowns";
import { ComprehensiveProps, Style } from "../../DomainProps";
import withValidations from "../../../hoc/withValidations";
import withHelperText from "../../../hoc/withHelperText";
import withLabel from "../../../hoc/withLabel";
import { cloneElement, useEffect, useRef, useState } from "react";
import withToolTip from "../../../hoc/withToolTip";

export interface DropDownViewProps {
  screenDataField?: string;
  widgetStyle?: Style;
  supportiveData: any[] | undefined;
  dataItemKey: string | undefined;
  defaultItem?: any;
  defaultValue?: any;
  textField?: string;
  enableSearch?: boolean;
  handleScroll?: any;
  onFilterChange?: any;
  value?: any;
  disabled?: boolean;
  popupSettings?: Record<string, any>;
  onBlur: (event: any) => void;
  onChange: (event: any) => void;
}

const itemRender = (li: any, itemProps: any) => {
  const itemChildren = (
    <div className="prc-dropdown-item">
      {itemProps.dataItem && <span className="prc-dropdown-item-selected"></span>}

      {li.props.children}
    </div>
  );
  return cloneElement(li, li.props, itemChildren);
};

const DropDownWidgetView = ({
  widgetStyle,
  onChange,
  onBlur,
  handleScroll,
  onFilterChange,
  enableSearch,
  supportiveData,
  screenDataField,
  dataItemKey,
  textField,
  disabled,
  defaultItem,
  defaultValue,
  value,
  popupSettings,
}: DropDownViewProps) => {
  const dropdownRef = useRef<any>(null);
  const [popupWidth, setPopupWidth] = useState(0);
  useEffect(() => {
    if (dropdownRef.current) {
      setPopupWidth(dropdownRef.current?.element?.clientWidth);
    }
  }, []);
  return (
    <DropDownList
      ref={dropdownRef}
      disabled={disabled}
      id={widgetStyle?.id || ""}
      className={widgetStyle?.className || ""}
      style={widgetStyle?.inline || {}}
      onChange={onChange}
      onBlur={onBlur}
      filterable={enableSearch}
      onFilterChange={onFilterChange}
      dataItemKey={dataItemKey ?? "value"}
      textField={textField ?? "label"}
      defaultItem={defaultItem}
      defaultValue={defaultValue}
      data={supportiveData || []}
      name={screenDataField}
      itemRender={itemRender}
      onPageChange={handleScroll}
      popupSettings={{
        ...popupSettings,
        style: {
          zIndex: 9999,
          width: `${popupWidth}px`,
          ...(popupSettings?.style ?? {}),
        },
      }}
      value={value !== undefined ? value : null}
    />
  );
};

export default withValidations(
  withToolTip(withHelperText(withLabel(DropDownWidgetView)))
);