/* 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 { BaseMultiSelectSetterProps } from "./interface";
import TextField from "@mui/material/TextField";
import Autocomplete from "@mui/material/Autocomplete";
import "./styles.css";
import { useSelector } from "react-redux";
import { Checkbox} from "@mui/material";
import CheckBoxOutlineBlankIcon from "@mui/icons-material/CheckBoxOutlineBlank";
import CheckBoxIcon from "@mui/icons-material/CheckBox";
import Chip from "@mui/material/Chip";
import {
  DndContext,
  closestCenter,
  KeyboardSensor,
  PointerSensor,
  useSensor,
  useSensors,
} from "@dnd-kit/core";
import {
  arrayMove,
  SortableContext,
  sortableKeyboardCoordinates,
  verticalListSortingStrategy,
  useSortable,
} from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import { useState } from "react";
import { without } from "lodash";
import { getClaasesObject } from "@/redux/currentApp/style/styleSelector";
const icon = <CheckBoxOutlineBlankIcon fontSize="small" />;
const checkedIcon = <CheckBoxIcon fontSize="small" />;
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: 1px;
  `;
  return css`
    display: flex;
    padding: 8px 0;
    ${isSetterSingleRow ? singleRowStyle : basicStyle};
    width: 100%;
  `;
};

const BaseSelectSetter = (props: BaseMultiSelectSetterProps) => {
  const {
    isSetterSingleRow,
    options,
    attrName,
    handleUpdateDsl,
    value,
    onChange,
    labelName,
    labelDesc,
    labelSize,
  } = props;
  const availableClasses = useSelector(getClaasesObject);
  const [uniquekey, setUniqueKey] = useState(value?.map((e) => e.value) || []);
  const classNames = Object.keys(availableClasses);
  const actualoptions: { title: string; value: string | number }[] =
    options ||
    classNames.map((e) => {
      return { title: e, value: e };
    });
  const getActalValues = (paramValue) => {
    const filterValues = [];
    const filterOptions = actualoptions.filter((e) => {
      if (paramValue.includes(e.value)) {
        filterValues.push(e.value);
        return true;
      }
      return false;
    });
    const returnData = paramValue.map((e) => {
      const index = filterValues.indexOf(e);
      return filterOptions[index];
    });
    return returnData;
  };
  const SortableItem = (props) => {
    const { attributes, listeners, setNodeRef, transform, transition } =
      useSortable({ id: props.value });

    const style = {
      transform: CSS.Transform.toString(transform),
      transition,
      margin: "2px",
    };

    const onMouseDown = (e) => {
      // e.preventDefault();
      // e.stopPropagation();
    };
    return (
      <div ref={setNodeRef} style={style} {...attributes} {...listeners}>
        <Chip
          key={props.value?.title}
          label={props.value?.title}
          onMouseDown={onMouseDown}
          onDelete={() => {
         
          }}
        />
      </div>
    );
  };

  const SortableChips = (props) => {
    const sensors = useSensors(
      useSensor(PointerSensor),
      useSensor(KeyboardSensor, {
        coordinateGetter: sortableKeyboardCoordinates,
      })
    );
    const handleDragEnd = (event) => {
      const { active, over } = event;
      if (active && over && active.id.title !== over.id.title) {
        const valuesArray = props.values.map((e) => e.value);
        const oldIndex = valuesArray.indexOf(active.id.value);
        const newIndex = valuesArray.indexOf(over.id.value);
        const updatedMoveValues = arrayMove(valuesArray, oldIndex, newIndex);

        handleUpdateDsl(attrName, getActalValues(updatedMoveValues));
        onChange?.(getActalValues(updatedMoveValues));
      }
    };
    return (
      <DndContext
        sensors={sensors}
        collisionDetection={closestCenter}
        onDragEnd={handleDragEnd}
      >
        <SortableContext
          items={props.values}
          strategy={verticalListSortingStrategy}
        >
          {props?.values?.map((id) => (
            <SortableItem key={id.title} value={id} />
          ))}
        </SortableContext>
      </DndContext>
    );
  };
  return (
    <div css={setterContainerStyle(isSetterSingleRow)}>
      <span>
        {labelName && (
          <PanelLabel
            labelName={labelName}
            labelDesc={labelDesc}
            labelSize={labelSize}
          />
        )}
      </span>
      <div css={applyBaseSelectWrapperStyle(isSetterSingleRow)}>
        <Autocomplete
          multiple
          options={actualoptions}
          value={
            value || []
            // ? getActalValues(value) :
          }
          isOptionEqualToValue={()=>true}
          id={attrName}

          size="small"
          fullWidth
          disableCloseOnSelect={true}
          getOptionLabel={(option) => option.title}
          renderOption={(props, option, 
            // {  _selected }
          ) => {
            const { key, ...optionProps } = props;
            return (
              <li key={key} {...optionProps}>
                <Checkbox
                  icon={icon}
                  checkedIcon={checkedIcon}
                  style={{ marginRight: 8 }}
                  checked={uniquekey.includes(key)}
                />
                {option.title}
              </li>
            );
          }}
          renderInput={(params) => <TextField value {...params} size="small" />}
          onChange={(event: any, val: any) => {
            const multiOptions = [];
      
            val?.map((e) => {
              multiOptions.push(e?.value || e);
            });
            const uniqueSet = new Set(multiOptions);
            const uniqueValues = Array.from(uniqueSet);
            if (uniqueValues.length < multiOptions.length) {
              const newArray = without(
                uniqueValues,
                multiOptions[multiOptions.length - 1]
              );
              setUniqueKey(newArray);
              handleUpdateDsl(attrName, getActalValues(newArray));
              onChange?.(getActalValues(newArray));
            } else {
              setUniqueKey(uniqueValues);
              handleUpdateDsl(attrName, getActalValues(uniqueValues));
              onChange?.(getActalValues(uniqueValues));
            }
          }}
          renderTags={(value) => <SortableChips values={value} />}
        />
      </div>
    </div>
  );
};

BaseSelectSetter.displayName = "BaseSelect";

export default BaseSelectSetter;
