import React, { FC, useEffect, useMemo, useState } from "react";
import { Form, Modal } from "venice-ui";
import { apiCall } from "../../untils/apiCall";
import { t } from "../../helpers/userHelper";
import { dictionary } from "../../untils/dictionary";
import { useStoreActions, useStoreState } from "../../store";
import {
  setFormConfig,
  setObjectState,
} from "../../definitionsNew/setFieldsHelper";
import { Scopes } from "../../definitionsNew/fields";
import { serializeEditedSection } from "../../definitionsNew/serializaConfigs";

export interface EditSectionData {
  show: boolean;
  projectID: string;
  sectionID: string;
  sectionName: string;
  kks: string;
}

interface IEditSectionModalProps {
  onClose: () => void;
  projectID: string;
  sectionID: string;
  show: boolean;
}

export const EditSectionModal: FC<IEditSectionModalProps> = ({
  onClose,
  projectID,
  sectionID,
}) => {
  const { orgID, configs, contracts } = useStoreState(
    (state) => state.user.userDetails
  );
  const { sections } = useStoreState(
    (state) => state.projectDetails.projectDetails
  );

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

  const { updateSection } = useStoreActions(
    (actions) => actions.projectDetails
  );

  const currentSection = useMemo(() => {
    return sections.find((_section) => _section.sectionID === sectionID);
  }, [sectionID, sections]);

  const [section, setSection] = useState<
    Record<string, string | number | undefined | File>
  >(setObjectState(configs, Scopes.AddSectionForm, true, currentSection));

  const validationSection = () => {
    const name = section.sectionName as string;
    const kks = section.kks as string;
    return name.trim().length === 0 || kks.trim().length === 0;
  };

  const updateForm = (field: string, value: string) => {
    setSection({
      ...section,
      [field]: value,
    });
  };
  const updateProject = async () => {
    const serializeData = serializeEditedSection(section);
    await apiCall(
      "projects/updateSection",
      {
        orgID: orgID,
        projectID: projectID,
        sectionID: sectionID,
        sectionUpdates: serializeData,
      },
      () => {
        serializeData.sectionID = sectionID;
        updateSection(serializeData);
        onClose();
      }
    );
  };

  const editForm = {
    action: updateForm,
    data: setFormConfig(
      configs,
      Scopes.AddSectionForm,
      section,
      contracts,
      projectDetails,
      projects,
      true
    ),
  };
  return (
    <>
      {section.show && (
        <Modal
          title={`${t(dictionary.editModalTitle)}: ${
            section.sectionName as string
          }`}
          headerDivader={true}
          handleClose={onClose}
          handleConfirm={() => updateProject()}
          submitDisabled={validationSection()}
          isOpen={section.show as unknown as boolean}
          exitOnEsc={true}
          labels={{
            primary: t(dictionary.save),
            secondary: t(dictionary.cancel),
          }}
        >
          <Form formData={editForm} />
        </Modal>
      )}
    </>
  );
};
