import React, { FC, useState } from "react";
import { Modal, Form, TextSmall } from "venice-ui";
import { getPercentageValue } from "../../helpers/mathHelpers";
import { getLimits } from "../../helpers/organizationHelper";
import { t } from "../../helpers/userHelper";
import { dictionary } from "../../untils/dictionary";
import { ProgressBar } from "../UI/ProgressBar/ProgressBar";
import { ModalProgresWrapper } from "../UI/ProgressBar/progressBar.styles";
import { ListSectionProps } from "../../types/sectionTypes";
import { apiCall } from "../../untils/apiCall";
import { useStoreState } from "../../store";
import {
  setFormConfig,
  setObjectState,
} from "../../definitionsNew/setFieldsHelper";
import { Scopes } from "../../definitionsNew/fields";
import { serializeSection } from "../../definitionsNew/serializaConfigs";
import { setDefaultSectionData } from "../../helpers/projectHelper";

interface IAddSectionModal {
  handleClose: () => void;
  handleAddSection: (newSection: ListSectionProps) => void;
  storage: number;
  planKey: string;
  projectID: string;
  isOpen: boolean;
}

export const AddSectionModal: FC<IAddSectionModal> = ({
  handleClose,
  handleAddSection,
  storage,
  planKey,
  projectID,
  isOpen,
}) => {
  const { orgID, configs, contracts } = useStoreState(
    (state) => state.user.userDetails,
  );
  const { projects } = useStoreState((state) => state.projects);
  const { projectDetails } = useStoreState((state) => state.projectDetails);
  const [modalLoader, toggleModalLoader] = useState(false);

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

  const clearState = () => {
    setSection(setObjectState(configs, Scopes.AddSectionForm));
  };

  const onClose = () => {
    clearState();
    handleClose();
  };
  const updateForm = (field: string, value: string | number | File) => {
    if (field === "file") {
      const fileValue = value as File;
     
      if (fileValue) {
        const kks = value ? fileValue.name.split(".pdf")[0] : "";
        const fileSize =
          Math.round(((fileValue.size || 0) / (1024 * 1024)) * 100) / 100;

        setSection({
          ...section,
          file: value as File,
          kks: kks,
          fileSize: fileSize,
        });
      }
    } else {
      setSection({ ...section, [field]: value });
    }
  };
  const addSectionFile = async () => {
    if (!modalLoader) {
      toggleModalLoader(true);
      let formData: FormData = serializeSection(section, orgID, projectID!);

      await apiCall("projects/setNewSection", formData, (response: any) => {
        toggleModalLoader(false);
        clearState();
        handleAddSection(response.newSection);
      });
    }
  };

  const validationNewSection = () => {
    const sectionName = section.sectionName as string;
    const availableSize = getLimits(planKey).space;
    const size = section.fileSize as number;
    const currentSize =
      parseFloat(storage.toFixed(3)) + parseFloat(size.toFixed(3));
    return (
      sectionName.trim().length === 0 ||
      section.file === undefined ||
      currentSize > availableSize ||
      (section.fileSize as number) > 25
    );
  };

  const newSectionForm = {
    action: updateForm,
    data: setFormConfig(
      configs,
      Scopes.AddSectionForm,
      section,
      contracts,
      projectDetails,
      projects,
    ),
  };
  const fileSize = section.fileSize as number;
  return (
    <Modal
      title={t(dictionary.newSection)}
      headerDivader={true}
      handleClose={onClose}
      handleConfirm={() => addSectionFile()}
      submitDisabled={validationNewSection()}
      submitLoader={modalLoader}
      isOpen={isOpen}
      exitOnEsc={true}
      labels={{
        primary: t(dictionary.createSection),
        secondary: t(dictionary.cancel),
      }}
    >
      <Form formData={newSectionForm} />
      <ModalProgresWrapper>
        <TextSmall>
          {t(dictionary.usageSpace)} (
          {(storage + fileSize).toFixed(2)} MB
          / {getLimits(planKey).space} MB )
        </TextSmall>
        <ProgressBar
          value={getPercentageValue(
            parseFloat(storage.toFixed(3)) + parseFloat(fileSize.toFixed(3)),
            getLimits(planKey).space,
          )}
        />
      </ModalProgresWrapper>
    </Modal>
  );
};
