import { FC, useEffect, useState } from "react";
import {
  SettingsAreaColumn,
  SettingsAreaColumnContent,
  SettingsAreaColumnTitle,
  SettingsAreaUnactiveColumn,
  SettingsDropArea,
  SettingsDropAreaUnactive,
} from "../organizations.style";
import { dictionary } from "../../../untils/dictionary";
import { t } from "../../../helpers/userHelper";
import { IListConfing } from "../../../definitionsNew/configs";
import { fields, Scopes } from "../../../definitionsNew/fields";
import { FormListItem } from "../../FormListItem/FormListItem";
import { useStoreState, useStoreActions } from "../../../store";
import { apiCall } from "../../../untils/apiCall";
import { JointSettingForm } from "./JointSettingForm";
import {
  handleMoveItem,
  setRowsFromFileds,
} from "../../../definitionsNew/setFieldsHelper";
import { PlaceholderHorizontal } from "./Placeholders";

export interface IFieldsState {
  active: IListConfing[];
  unactive: IListConfing[];
}

interface ISettingForms {
  configName: string;
  isExportable: boolean;
}

export interface ISelectedState {
  hoverID: string;
  sourceList: string;
  targetList: string;
  movedItem: string;
  sourceGroup: number;
  targetGroup: number;
}

export const SettingForms: FC<ISettingForms> = ({
  configName,
  isExportable,
}) => {
  const { orgID, configs } = useStoreState((state) => state.user.userDetails);
  const { setConfing } = useStoreActions((actions) => actions.user);

  const configFileds = () => {
    const newFields: IFieldsState = {
      active: [],
      unactive: [],
    };

    const activeFields =
      configs.find((_item) => _item.configName === configName)?.config || [];

    newFields.active = activeFields.sort(
      (a, b) => (a.itemIndex || 0) - (b.itemIndex || 0)
    );
    newFields.unactive = fields
      .filter(
        (_item) =>
          (_item.scope as Scopes[]).includes(configName as Scopes) &&
          !activeFields.map((_listItem) => _listItem.id).includes(_item.id)
      )
      .map((_item) => ({
        ..._item,
        visable: true,
        export: true,
      }));
    return newFields;
  };

  const [fileds, setFields] = useState<IFieldsState>(configFileds());

  const [selected, setSelected] = useState<ISelectedState>({
    hoverID: "",
    sourceList: "",
    targetList: "",
    movedItem: "",
    sourceGroup: -1,
    targetGroup: -1,
  });

  useEffect(() => {
    const newFields = configFileds();
    setFields(newFields);
  }, [configs, configName]);

  const updateItem = async (id: string, mode: string) => {
    let newActive: IListConfing[] = [...fileds.active];
    switch (mode) {
      case "visable":
        const visableItem = newActive.find((_item) => _item.id === id);
        if (visableItem) {
          visableItem.visable = !visableItem.visable;
        }
        break;
      case "export":
        const exportItem = newActive.find((_item) => _item.id === id);
        if (exportItem) {
          exportItem.export = !exportItem.export;
        }
        break;
    }
    updateAction(newActive, configName);
  };

  const updateAction = async (
    newConfig: IListConfing[],
    configName: string
  ) => {
    const options = {
      orgID: orgID,
      configName: configName,
      config: newConfig,
    };
    await apiCall("organization/saveListConfig", options, (response: any) => {
      setConfing({ configName: configName, config: newConfig });
    });
  };

  const handleDragOver = (e: any, id: string, list: string, group?: number) => {
    e.preventDefault();
    if (list !== selected.targetList) {
      setSelected({
        ...selected,
        targetList: list,
      });
    }
    if (selected.hoverID !== id && id !== "placeholder") {
      if (selected.sourceList === "active" || list === "active") {
        setSelected({
          ...selected,
          hoverID: id,
        });
      } else if (
        selected.sourceList === "activeGroups" ||
        list === "activeGroups"
      ) {
        setSelected({
          ...selected,
          hoverID: id,
          targetGroup: group !== undefined ? group : -1,
        });
      }
    }
  };

  const handleDrop = () => {
    const newConfig = handleMoveItem(selected, fileds.active);
    setSelected({
      ...selected,
      hoverID: "",
      targetList: "",
      sourceList: "",
      movedItem: "",
      sourceGroup: -1,
      targetGroup: -1,
    });
    if (newConfig) {
      updateAction(newConfig, configName);
    }
  };

  const handleonDragEnd = () => {
    if (selected.targetList === "") {
      setSelected({
        ...selected,
        hoverID: "",
        targetList: "",
        sourceList: "",
        movedItem: "",
        sourceGroup: -1,
        targetGroup: -1,
      });
    }
  };
  const handleDropLeave = () => {
    setSelected({
      ...selected,
      hoverID: "",
      targetList: "",
      targetGroup: -1,
    });
  };

  const handleDragStart = (
    e: any,
    id: string,
    list: string,
    groupID?: number
  ) => {
    setSelected({
      ...selected,
      sourceList: list,
      movedItem: id,
      sourceGroup: groupID !== undefined ? groupID : -1,
    });
  };
  //IRowsConfig
  return (
    <>
      <SettingsAreaColumn>
        <SettingsAreaColumnTitle>
          {t(dictionary.active)}
        </SettingsAreaColumnTitle>
        <SettingsAreaColumnContent onDragLeave={handleDropLeave}>
          {configName === Scopes.JointDetail ? (
            <JointSettingForm
              rows={setRowsFromFileds(fileds.active)}
              handleDragStart={handleDragStart}
              handleDragOver={handleDragOver}
              handleonDragEnd={handleonDragEnd}
              handleDrop={handleDrop}
              hoverID={selected.hoverID}
              movedItem={selected.movedItem}
              targetGroupID={selected.targetGroup}
            />
          ) : (
            <SettingsDropArea
              onDragOver={(e) => e.preventDefault()}
              onDrop={handleDrop}
            >
              <PlaceholderHorizontal
                handleDragOver={handleDragOver}
                listName="active"
                id={"topBox"}
                key={`placeholder_topBox`}
                isActive={selected.hoverID === "topBox"}
              />

              {fileds.active.map((_activeItem) => (
                <>
                  <FormListItem
                    key={_activeItem.id}
                    id={_activeItem.id}
                    isActive={true}
                    isExportible={_activeItem.export}
                    isVisable={_activeItem.visable}
                    updateItem={updateItem}
                    isExportable={isExportable}
                    isRequired={_activeItem.required || false}
                    isForm={false}
                    handleDragStart={handleDragStart}
                    handleonDragEnd={handleonDragEnd}
                    listName="active"
                    isDraging={selected.movedItem === _activeItem.id}
                    isGroup={false}
                    groupID={-1}
                  />
                  <PlaceholderHorizontal
                    handleDragOver={handleDragOver}
                    listName="active"
                    id={_activeItem.id}
                    key={`placeholder_${_activeItem.id}`}
                    isActive={selected.hoverID === _activeItem.id}
                  />
                </>
              ))}
            </SettingsDropArea>
          )}
        </SettingsAreaColumnContent>
      </SettingsAreaColumn>
      <SettingsAreaColumn>
        <SettingsAreaColumnTitle>
          {t(dictionary.unactive)}
        </SettingsAreaColumnTitle>
        <SettingsAreaUnactiveColumn
          onDragLeave={handleDropLeave}
          onDragOver={(e) => handleDragOver(e, "", "unactive")}
          isActive={selected.targetList === "unactive"}
          onDrop={handleDrop}
        >
          <SettingsDropAreaUnactive onDragOver={(e) => e.preventDefault()}>
            {fileds.unactive.map((_unactiveItem, index) => (
              <FormListItem
                key={_unactiveItem.id}
                id={_unactiveItem.id}
                isActive={false}
                isExportible={false}
                isVisable={false}
                updateItem={updateItem}
                isExportable={isExportable}
                isRequired={_unactiveItem.required || false}
                isForm={false}
                handleDragStart={handleDragStart}
                handleonDragEnd={handleonDragEnd}
                listName="unactive"
                isDraging={selected.movedItem === _unactiveItem.id}
                isGroup={false}
                groupID={-1}
              />
            ))}
          </SettingsDropAreaUnactive>
        </SettingsAreaUnactiveColumn>
      </SettingsAreaColumn>
    </>
  );
};
