import React, { FC, useEffect, useMemo, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { Content, ContentFull, ContentWrapper } from "../components";
import { apiCall } from "../../untils/apiCall";
import { EmptyState } from "../UI/EmptyState";
import { Aligment, Card, Table } from "venice-ui";
import { LoadingContent } from "../layouts/Loading";
import { getMonthNames, t, weekDaysShortName } from "../../helpers/userHelper";
import { IAction } from "venice-ui/dist/types/types";
import { getSectionObj, newGetSectionObj } from "../../helpers/projectHelper";
import { dictionary } from "../../untils/dictionary";
import { useStoreActions, useStoreState } from "../../store";
import { ProjectDetailsHeader } from "./ProjectDetailsHeader";
import { PointsList } from "./PointsList";
import { setShowListPoints } from "../Section/sectionModel";
import { xlsxListGenrator } from "../../helpers/generators";
import { AddSectionModal } from "../Modals/AddSectionModal";
import { ListSectionProps } from "../../types/sectionTypes";
import { getConfig, setHeaders } from "../../definitionsNew/setFieldsHelper";
import { Scopes } from "../../definitionsNew/fields";
import { serliazizeSectionsList } from "../../definitionsNew/serializaConfigs";
import {
  DeleteProjectModal,
  DeleteSectionModal,
  EditProjectModal,
  EditSectionModal,
  ExportModal,
} from "../Modals";
import { ProjectHeader } from "./ProjectHeader";

interface ISectinosPageProps {
  loading: boolean;
  actionLoader: boolean;
  storage: number;
  planKey: string;
}

const ProjectDetails: FC = () => {
  const navigate = useNavigate();
  const [activeTab, updateActiveTab] = useState("sections");
  const tabActionClick = (value: string) => {
    updateActiveTab(value);
  };

  const { projectID } = useParams();
  const { uid, orgID, configs, contracts, orgRole } = useStoreState(
    (state) => state.user.userDetails,
  );
  const { projectName, sections, elements } = useStoreState(
    (state) => state.projectDetails.projectDetails,
  );
  const { projectDetails } = useStoreState((state) => state.projectDetails);
  const { projects } = useStoreState((state) => state.projects);

  const [modal, toogleModal] = useState(false);
  const [pageProps, updatePageProps] = useState<ISectinosPageProps>({
    loading: true,
    actionLoader: false,
    storage: 0,
    planKey: "",
  });

  const { setProjectDetails, addSection, removeSection, resetProjectDetails } =
    useStoreActions((actions) => actions.projectDetails);

  const [editProjectModal, toggleEditProjectModal] = useState(false);
  const [deleteProjectModal, toggleDeleteProjectModal] = useState(false);
  const [exportModal, toogleExportModal] = useState(false);

  const [deleteSectionModal, toggleDeleteSectionModal] = useState({
    show: false,
    id: "",
    sectionName: "",
  });

  const [editSectionModal, toggleEditSectionModal] = useState({
    sectionID: "",
    show: false,
  });
  const showDeleteSectionModal = (id?: string) => {
    if (id) {
      const section = getSectionObj(sections, id);
      toggleDeleteSectionModal({
        show: true,
        id: id,
        sectionName: section.sectionName as string,
      });
    }
  };

  const hideDeleteSectionModal = () => {
    toggleDeleteSectionModal({
      show: false,
      id: "",
      sectionName: "",
    });
  };

  const showEditSectionModal = (id?: string) => {
    if (id) {
      const section = newGetSectionObj(sections, configs, id);
      toggleEditSectionModal({
        show: true,
        sectionID: id,
      });
    }
  };

  const hideEditSectoionModal = () => {
    toggleEditSectionModal({
      ...editSectionModal,
      show: false,
    });
    updatePageProps({
      ...pageProps,
      loading: false,
    });
  };

  const getSecions = async () => {
    const options = {
      orgID,
      projectID,
    };
    await apiCall("projects/getProjectDetails", options, (response: any) => {
      setProjectDetails(response.details);
      updatePageProps({
        ...pageProps,
        loading: false,
        storage: response.storage,
        planKey: response.keyPlan,
      });
    });
  };

  useEffect(() => {
    getSecions();
  }, []);

  const hideModal = () => {
    toogleModal(false);
  };
  const showModal = () => {
    toogleModal(true);
  };
  const showExportModal = () => {
    toogleExportModal(true);
  };
  const hideExportModal = () => {
    toogleExportModal(false);
  };

  const deleteProjectAction = () => {
    resetProjectDetails();
    navigate(`/`);
  };

  const deleteSection = async (id: string) => {
    const section = getSectionObj(sections, id);
    await apiCall(
      "projects/removeSection",
      {
        orgID: orgID,
        projectID: projectID,
        sectionID: id,
        fileName: section.file,
      },
      (response: any) => {
        updatePageProps({
          ...pageProps,
        });
        removeSection(id);
        hideDeleteSectionModal();
      },
    );
  };

  const addNewSection = (newSection: ListSectionProps) => {
    addSection(newSection);
    hideModal();
    navigate(`/project/${projectID}/${newSection.sectionID}`);
  };

  const moreActionsProject = [
    {
      label: t(dictionary.editProject),
      action: () => toggleEditProjectModal(true),
      disabled: orgRole === "readOnly",
    },
    {
      label: t(dictionary.deleteProject),
      action: () => toggleDeleteProjectModal(true),
      disabled: orgRole === "readOnly",
    },
  ];

  const moreActionsSection: IAction[] = [
    {
      label: t(dictionary.editSection),
      action: showEditSectionModal,
      disabled: orgRole === "readOnly",
    },
    {
      label: t(dictionary.deleteSection),
      action: showDeleteSectionModal,
      disabled: orgRole === "readOnly",
    },
  ];

  const selectSection = async (id: string) => {
    navigate(`/project/${projectID}/${id}`);
  };
  const handleExport = () => {
    xlsxListGenrator(
      setShowListPoints(
        elements,
        sections,
        projectID!,
        getConfig(configs, Scopes.SectionsList),
        projects,
        projectDetails,
        contracts,
      ),
      setHeaders(getConfig(configs, Scopes.ListGlobal), "export"),
      projectName,
      sections,
    );
    toogleExportModal(false);
  };

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

  const tableSections = useMemo(() => {
    return serliazizeSectionsList(sections);
  }, [sections, configs]);

  const showActionButton = () => {
    if (activeTab === "sections") {
      return showModal();
    } else {
      return showExportModal();
    }
  };

  const checkIfDisabled = () => {
    if (activeTab === "sections" && orgRole === "readOnly") {
      return true;
    } else {
      return false;
    }
  };

  if (pageProps.loading) {
    return (
      <ContentFull>
        <LoadingContent />
      </ContentFull>
    );
  }
  return (
    <Content>
      <Card
        title={projectName}
        shadow={false}
        actionLabel={
          activeTab === "sections"
            ? t(dictionary.addSection)
            : t(dictionary.export)
        }
        noVerticalPadding={true}
        componentHeight="calc(100vh - 4rem)"
        actionDisabled={checkIfDisabled()}
        customHeader={
          <ProjectHeader
            title={projectName}
            actionLabel={
              activeTab === "sections"
                ? t(dictionary.addSection)
                : t(dictionary.export)
            }
            handleBack={() => navigate(`/`)}
            handleClick={showActionButton}
            options={moreActionsProject}
          />
        }
      >
        <Aligment align="stretch" direction="row">
          <ProjectDetailsHeader
            activeTab={activeTab}
            setActiveTab={tabActionClick}
          />
          {activeTab === "sections" && (
            <>
              {sections.length > 0 ? (
                <ContentWrapper componentHeight="calc(100vh - 14.6rem)">
                  <Table
                    headers={headers}
                    elements={tableSections}
                    onRowClick={selectSection}
                    selectable={true}
                    sortable={true}
                    filtrable={true}
                    pagination={true}
                    moreActions={moreActionsSection}
                    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.searchSection)}
                    noResultsText={t(dictionary.noResultsFound)}
                  ></Table>
                </ContentWrapper>
              ) : (
                <EmptyState
                  title={t(dictionary.emptyStateSectionTitle)}
                  actionLabel={t(dictionary.addSection)}
                  action={() => showModal()}
                />
              )}
            </>
          )}
          {activeTab === "joints" && <PointsList />}
          {activeTab === "spools" && <PointsList />}
        </Aligment>
      </Card>

      {modal && (
        <AddSectionModal
          handleClose={hideModal}
          handleAddSection={addNewSection}
          storage={pageProps.storage}
          planKey={pageProps.planKey}
          projectID={projectID!}
          isOpen={modal}
        />
      )}
      {editProjectModal && (
        <EditProjectModal
          onClose={() => toggleEditProjectModal(false)}
          show={editProjectModal}
          projectID={projectID!}
        />
      )}
      {deleteProjectModal && (
        <DeleteProjectModal
          handleCancel={() => toggleDeleteProjectModal(false)}
          handleCancelWithAction={deleteProjectAction}
          id={projectID!}
          name={projectName}
          isOpen={deleteProjectModal}
        />
      )}
      {editSectionModal.show && (
        <EditSectionModal
          onClose={() => hideEditSectoionModal()}
          show={editSectionModal.show}
          projectID={projectID!}
          sectionID={editSectionModal.sectionID}
        />
      )}
      {deleteSectionModal.show && (
        <DeleteSectionModal
          handleCancel={() => hideDeleteSectionModal()}
          handleDelete={deleteSection}
          id={deleteSectionModal.id}
          name={deleteSectionModal.sectionName}
          isOpen={deleteSectionModal.show}
        />
      )}

      {exportModal && (
        <ExportModal
          handleCancel={hideExportModal}
          handleConfirm={handleExport}
          name={projectName}
          isOpen={exportModal}
        />
      )}
    </Content>
  );
};

export default ProjectDetails;
