import * as React from "react";
import { get } from "lodash";

import {
  SortableList,
  DefaultItemComponent,
} from "@sc/modules/v2/CRUD/SortableList";
import theme from "@sc/components/ui/theme";

import Icon, { IconTypes } from "../../Icon";

import { ListItemType, ListBuilderProps } from "../types";
import style from "./style";
import { AttributeContainer } from "@sc/modules/v2/CRUD/FormBuilder";
import { AttributeNames } from "@sc/modules/v2/CRUD/AttributeBuilder/types";
import { LiveFormFieldProps } from "@sc/modules/v2/CRUD/FormBuilder/LiveFormField/types";
import { ItemComponentTypes } from "@sc/modules/v2/CRUD/SortableList/types";

interface ItemComponentProps extends ListItemType {
  onMouseEnter?: (event: React.MouseEvent<HTMLDivElement, MouseEvent>) => void;
  onMouseLeave?: (event: React.MouseEvent<HTMLDivElement, MouseEvent>) => void;
  isHovering?: boolean;
}

export const ListBuilder: React.FC<ListBuilderProps> = ({
  data,
  onChange,
  icon,
}) => {
  const [isExpandedList, setIsExpandedList] = React.useState<string[]>([]);

  const handleChange = (mutatedPayload: ListItemType[]): void => {
    console.log({ mutatedPayload });
    onChange(mutatedPayload);
  };

  const handleEdit = (data: ListItemType): void => {
    // toggle expansion
    if (isExpandedList.indexOf(data.id) > -1) {
      // remove if it exists
      setIsExpandedList(isExpandedList.filter((id) => id !== data.id));
    } else {
      // add if it doesn't exist
      setIsExpandedList([...isExpandedList, data.id]);
    }
  };

  const handleAdd = () => {
    handleChange([
      ...data,
      {
        caption: "",
        id: Math.random()
          .toString(36)
          .slice(2),
      },
    ]);
  };

  const ItemComponent: React.FC<ItemComponentProps> = (itm) => {
    const { id, caption } = itm;
    const icn = get(itm, "icon", icon);

    const [attributes, setAttributes] = React.useState<LiveFormFieldProps>({
      icon: icn,
      description: caption,
    });

    const isExpanded = Boolean(isExpandedList.indexOf(id) > -1);

    const handleSingleFieldBlur = (
      caption: string,
      icon: boolean | IconTypes = false
    ): void => {
      const key = data.findIndex((itm) => itm.id === id);
      const newData = [
        ...data.slice(0, key),
        { ...data[key], caption, icon },
        ...data.slice(key + 1),
      ];
      console.log({ newData });
      onChange(newData);
    };

    return (
      <DefaultItemComponent
        {...itm}
        icon={icn}
        placeholder="Enter new bullet point"
        type={ItemComponentTypes.INPUT}
        onAdd={handleAdd}
        onBlur={handleSingleFieldBlur}
        isExpanded={isExpanded}
      >
        <AttributeContainer
          attributes={attributes}
          data={[
            {
              id: "4",
              attribute: AttributeNames.DESCRIPTION,
              settings: { label: "Caption" },
            },
            { id: "1", attribute: AttributeNames.ICON, settings: {} },
          ]}
          onChange={(attr) => {
            console.log({ attr });
            setAttributes(attr);
          }}
          onBlur={(data) => {
            handleSingleFieldBlur(data.description, data.icon);
            console.log({ data });
          }}
          hideFooter
        />
      </DefaultItemComponent>
    );
  };

  return (
    <div>
      <SortableList
        data={data}
        itemStyle={{
          border: "1px solid #DDD",
          borderRadius: 3,
          margin: "10px 0",
          height: 45,
        }}
        ItemComponent={ItemComponent}
        onAdd={handleAdd}
        onEdit={handleEdit}
        onChange={handleChange}
        onDelete={(payload, updatedData) => handleChange(updatedData)}
        canDragAndDrop
        showItemInline={false}
        name="Bullet Point"
      />
    </div>
  );
};
