import React, { FC, useEffect, useMemo, useRef, useState } from "react";
import { IElementType, IExtendElementType } from "../../definitions/element";
import { Table } from "venice-ui";
import { TableWrapper, ItemListContent } from "../ItemList/ItemList.styles";
import {
  getElement,
  setOptionsSaveElement,
  setShowListPoints,
} from "../Section/sectionModel";
import { useStoreActions, useStoreState } from "../../store";
import { PointModal } from "../Modals/PointModal";
import { EmptyState } from "../UI/EmptyState";
import { dictionary } from "../../untils/dictionary";
import { getMonthNames, t, weekDaysShortName } from "../../helpers/userHelper";
import { IAddtionalElements } from "../../definitions/additional";
import { apiCall } from "../../untils/apiCall";
import { ifHaveReferences } from "../../helpers/weldHelpers";
import { getConfig, setHeaders } from "../../definitionsNew/setFieldsHelper";
import { Scopes } from "../../definitionsNew/fields";
import { ContentWrapper } from "../components";

export const PointsList: FC = () => {
  const { sections, elements, references, projectID } = useStoreState(
    (state) => state.projectDetails.projectDetails,
  );

  const { projects } = useStoreState((state) => state.projects);

  const { projectDetails } = useStoreState((state) => state.projectDetails);

  const { orgID, configs, contracts } = useStoreState(
    (state) => state.user.userDetails,
  );

  const [pointDetails, updatePointDetails] = useState({
    show: false,
    id: "",
    mode: "read",
  });

  const [loading, setLoading] = useState(false);

  const closeLoader = () => {
    setLoading(false);
  };

  const { updateElement, removeElement, removeReference, clearReferences } =
    useStoreActions((actions) => actions.projectDetails);

  const showPointModal = (id: string) => {
    updatePointDetails({
      show: true,
      id: id,
      mode: "read",
    });
  };

  const hidePointModal = () => {
    updatePointDetails({
      show: false,
      id: "",
      mode: "read",
    });
  };

  const deleteElement = async (
    id: string,
    mapElement: boolean,
    isReference: boolean,
  ) => {
    await apiCall(
      "projects/removeElement",
      {
        orgID: orgID,
        projectID: projectID,
        elementID: id,
        mapElement: mapElement,
        isReference: isReference,
      },
      (response: any) => {
        setLoading(false);
        if (isReference) {
          removeReference(id);
        } else {
          if (ifHaveReferences(id, references)) {
            clearReferences(id);
          }
          removeElement(id);
        }
        hidePointModal();
      },
    );
  };

  const saveElement = async (element: IElementType | IAddtionalElements) => {
    const options = setOptionsSaveElement(
      element as IElementType,
      orgID,
      projectID!,
    );
    await apiCall("projects/saveElement", options, (response: any) => {
      setLoading(false);
      updateElement(element as IElementType);
      hidePointModal();
    });
  };
  const points = setShowListPoints(
    elements,
    sections,
    projectID,
    getConfig(configs, Scopes.ListGlobal),
    projects,
    projectDetails,
    contracts,
  );

    const tableHeaders = useMemo(() => {
      return setHeaders(getConfig(configs, Scopes.ListGlobal), "show");
    }, [configs]);

  return (
    <>
      {points.length > 0 ? (
        <ContentWrapper componentHeight="calc(100vh - 14.6rem)">
          <Table
            headers={tableHeaders}
            elements={points}
            onRowClick={showPointModal}
            selectable={false}
            sortable={true}
            filtrable={true}
            pagination={true}
            tableHeight="calc(100vh - 19.6rem)"
            tableWrapperHeight="calc(100vh - 14.6rem)"
            filterLabels={{
              title: t(dictionary.filters),
              close: t(dictionary.close),
              confirm: t(dictionary.confirm),
              trigger: t(dictionary.filters),
              clearAll: t(dictionary.resetFilters),
              clear: t(dictionary.clear),
            }}
            paginationLabel={{
              label: t(dictionary.itemPerPage),
            }}
            calendarLabels={{
              placeholder: t(dictionary.selectDate),
            }}
            calendarLocaleLabels={{
              months: getMonthNames(),
              weekdaysShort: weekDaysShortName(),
              firstDayOfWeek: 1,
            }}
            searchInputPlaceholder={t(dictionary.weldSection)}
                      noResultsText={t(dictionary.noResultsFound)}
          ></Table>
        </ContentWrapper>
      ) : (
        <EmptyState
          title={t(dictionary.emptyStateProjectListTitle)}
          actionLabel={t(dictionary.addSection)}
        />
      )}
      {pointDetails.show && (
        <PointModal
          handleCancel={hidePointModal}
          elementID={pointDetails.id}
          element={getElement(pointDetails.id, elements)}
          handleDelete={deleteElement}
          handleSave={saveElement}
          modalMode="read"
          fullSpec={true}
          loading={loading}
          setLoading={closeLoader}
          isOpen={pointDetails.show}
          elementTypeMode={"joints"}
        />
      )}
    </>
  );
};
