import * as React from "react";
// import ReactJson from "react-json-view";
// import styled from "styled-components";
import { get, head } from "lodash";
// import { Grid } from "@material-ui/core";
import TextField from "@material-ui/core/TextField";
import Icon from "@sc/plugins/webcomponents/v2/Icon";

import { DropdownFieldProps } from "../types";
import { EditorMode } from "@sc/modules/v2/Editor/types";
import { AttributeContainer } from "@sc/modules/v2/CRUD/AttributeBuilder";
import { AttributeNames } from "@sc/modules/v2/CRUD/AttributeBuilder/types";
// import IconSelector from "@sc/modules/v2/Properties/components/properties/IconSelector";
import SortableList from "@sc/modules/v2/CRUD/SortableList";
import { LiveFormFieldProps } from "../../LiveFormField/types";

/**
 * A component that shows a LIVE dropdown input field or tools for configuring that dropdown field's look, feel, and behavior
 */
const DropdownField: React.FC<DropdownFieldProps> = (props) => {
  const {
    mode = EditorMode.LIVE,
    placeholder,
    data = [],
    items = [],
    styles = {
      labelStyle: {},
      descriptionStyle: {},
      inputStyle: {},
      containerStyle: {},
      validationStyle: {},
      iconStyle: {},
    },
    name,
    label,
    description,
    defaultValue,
    disabled,
    icon,
    columns = 12,
    onBlur = () => null,
    onChange = () => null,
    attributeContainerDataSettings = {},
  } = props;

  /**
   * Deals with any changes that comes from the various attributes that are loaded
   *
   * • Converts to LiveFormFieldProps shape
   * • Triggers (and passes along the mutated LiveFormFieldProps payload to) the onChange event
   * @params
   */
  const handleChange = (data: LiveFormFieldProps): void => {
    console.log({ data });
    onChange(data);
  };

  const handleBlur = (data: LiveFormFieldProps): void => {
    onBlur(data);
  };

  const {
    iconStyle = {},
    descriptionStyle = {},
    containerStyle = {},
    inputStyle = {},
    validationStyle = {},
    labelStyle = {},
  } = styles;

  const ItemComponent = (itm) => {
    const [value, setValue] = React.useState<string>("");

    React.useEffect(() => {
      setValue(itm.value);
    }, []);

    return (
      <div
        style={{
          width: "100%",
          margin: 5,
        }}
      >
        <input
          type="text"
          value={value}
          // variant="outlined"
          style={{
            border: "none",
            width: "100%",
            padding: 10,
            background: "transparent",
            fontSize: "11pt",
          }}
          onClick={(e) => e.stopPropagation()}
          onBlur={(e) => {
            const k = items.findIndex((dta) => dta.name === itm.name);
            const item = head(items.filter((dta) => dta.name === itm.name));
            // console.log({ item });
            // setValue(e.target.value);
            const updatedData = {
              ...data,
              items: [
                ...items.slice(0, k),
                { ...item, value: e.target.value },
                ...items.slice(k + 1),
              ],
            };
            handleChange(updatedData);
            handleBlur(updatedData);
          }}
          onChange={(e) => {
            setValue(e.target.value);
          }}
        />
      </div>
    );
  };

  return (
    <div
      data-testid="FormBuilder-FormFields-DropdownField"
      style={containerStyle}
    >
      {mode === EditorMode.LIVE && (
        <div data-testid="FormBuilder-FormFields-DropdownField-LIVE">
          {label && <div style={labelStyle}>{label}</div>}
          {description && <div style={descriptionStyle}>{description}</div>}
          {icon && (
            <Icon type={icon} style={{ ...iconStyle, position: "absolute" }} />
          )}
          <div
            style={{
              ...inputStyle,
              padding: parseInt(get(inputStyle, "padding", 5)) - 5,
              ...(icon ? { paddingLeft: 40 } : {}),
            }}
          >
            <select
              placeholder={placeholder}
              style={{
                backgroundColor: "transparent",
                ...inputStyle,
                border: "none",
              }}
            >
              {data.map((itm, key) => (
                <option
                  key={key}
                  // selected={itm.value === defaultValue}
                  onChange={handleChange}
                >
                  {itm.label}
                </option>
              ))}
            </select>
          </div>
        </div>
      )}
      {mode === EditorMode.EDITOR && (
        <div data-testid="FormBuilder-FormFields-DropdownField-EDITOR">
          <AttributeContainer
            onChange={handleChange}
            onBlur={onBlur}
            attributes={props}
            data={[
              {
                id: "label",
                attribute: AttributeNames.LABEL,
                settings: {
                  hide: true,
                  ...attributeContainerDataSettings,
                },
              },
              {
                id: "description",
                attribute: AttributeNames.DESCRIPTION,
                settings: {
                  hide: true,
                  ...attributeContainerDataSettings,
                },
              },
              {
                id: "name",
                attribute: AttributeNames.FORMITEMNAME,
                settings: {
                  hide: true,
                  ...attributeContainerDataSettings,
                },
              },
              {
                id: "columns",
                attribute: AttributeNames.COLUMNS,
                settings: {
                  hide: true,
                  ...attributeContainerDataSettings,
                },
              },
              {
                id: "required",
                attribute: AttributeNames.REQUIRED,
                settings: {},
              },
              {
                id: "iconSelector",
                attribute: AttributeNames.ICON,
                settings: {
                  hide: true,
                  ...attributeContainerDataSettings,
                },
              },
            ]}
          >
            <div style={{ textAlign: "center", padding: 10, marginTop: 10 }}>
              - Dropdown Items -
            </div>
            <SortableList
              itemStyle={{
                border: "1px solid #DDD",
                borderRadius: 3,
                margin: "10px 0",
              }}
              data={items.map((itm) => ({ ...itm, id: itm.name }))}
              ItemComponent={ItemComponent}
              canEdit={false}
              onAdd={() => {
                const updatedData = {
                  ...data,
                  items: items.length
                    ? [
                        ...items,
                        {
                          ...items[items.length - 1],
                          name: Math.random()
                            .toString(36)
                            .slice(2),
                          id: Math.random()
                            .toString(36)
                            .slice(2),
                        },
                      ]
                    : [
                        {
                          id: Math.random()
                            .toString(36)
                            .slice(2),
                          name: Math.random()
                            .toString(36)
                            .slice(2),
                          value: "",
                        },
                      ],
                };
                handleChange(updatedData);
                handleBlur(updatedData);
              }}
              onChange={(updatedData) => {
                handleChange({ ...data, items: updatedData });
                handleBlur({ ...data, items: updatedData });
              }}
              onDelete={(payload, updatedData) => {
                handleChange({ ...data, items: updatedData });
                handleBlur({ ...data, items: updatedData });
              }}
              canDragAndDrop
            />
          </AttributeContainer>
        </div>
      )}
    </div>
  );
};

export default DropdownField;
