/* eslint-disable @typescript-eslint/no-explicit-any */
import { PanelLabel } from "@/page/App/components/InspectPanel/components/Label";
import { SerializedStyles, css } from "@emotion/react";
import { fixedWidthStyle } from "@/page/App/components/InspectPanel/PanelSetters/style";
import {BaseSelectSetterProps} from './interface';

import TextField from "@mui/material/TextField";
import Autocomplete from "@mui/material/Autocomplete";
import { isObject } from "lodash";

import "./styles.css";

const applyBaseSelectWrapperStyle = (
  isSetterSingleRow: boolean = false
): SerializedStyles => {
  return isSetterSingleRow
    ? css`
        width: 100%;
      `
    : fixedWidthStyle;
};

const setterContainerStyle = (isSetterSingleRow: boolean = false) => {
  const basicStyle = css`
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
  `;
  const singleRowStyle = css`
    flex-direction: column;
    gap: 8px;
  `;
  return css`
    display: flex;
    padding: 8px 0;
    ${isSetterSingleRow ? singleRowStyle : basicStyle};
    width: 100%;
  `;
};

const BaseSelectSetter = (props: BaseSelectSetterProps) => {
  const {
    isSetterSingleRow,
    options,
    attrName,
    handleUpdateDsl,
    value,
    onChange,
    labelName,
    labelDesc,
    labelSize,
  } = props;

  return (
    <div css={setterContainerStyle(isSetterSingleRow)}>
      <span>
        {labelName && (
          <PanelLabel
            labelName={labelName}
            labelDesc={labelDesc}
            labelSize={labelSize}
          />
        )}
      </span>
      <div css={applyBaseSelectWrapperStyle(isSetterSingleRow)}>
        <Autocomplete
          className="custom-autocomplete"
           id={`combo-box-demo-${attrName}`}
           key={`combo-box-demo-${attrName}`}
          value={value}
          options={options}
          renderInput={(params) => <TextField {...params} size="small" />}
          sx={{ width: 180 }}
          disableCloseOnSelect
          isOptionEqualToValue={()=>true}
          onChange={(_event, val:any) => {
           if(isObject(val)){
            //@ts-expect-error mkkkk
            const { value } = val??{value:""};
            handleUpdateDsl(attrName, value);
            onChange?.(value);
           }else{
            handleUpdateDsl(attrName, val);
            onChange?.(val);
           }
          }}
        />
      </div>
    </div>
  );
};

BaseSelectSetter.displayName = "BaseSelect";

export default BaseSelectSetter;
