import React, { useGlobal } from "reactn";

import Page from "../layouts/Page";

import InputRow from "../components/InputRow.js";

import { projectsRef } from "../config/firebase";
import {
  checkIfFigmaLinkIsValid,
  getValueFromKeyState,
} from "../helpers/index.js";

export default (props) => {
  const [, setIsLoading] = useGlobal("_isLoading");
  const [, setTooltip] = useGlobal("_tooltip");

  const [currentProjectData] = useGlobal("currentProjectData");

  const settingsList = [
    {
      title: "Lien du Figma",
      key: "links.figma",
      type: "string",
    },
    {
      title: "Lien de test",
      key: "links.test",
      type: "string",
    },
    {
      title: "Lien de production",
      key: "links.production",
      type: "string",
    },
    {
      title: "Lien du dashboard",
      key: "dashboardURL",
      type: "string",
    },
    {
      title: "Lien du git",
      key: "links.git",
      type: "string",
    },
  ];

  const onUpdateSetting = async ({ key, value }) => {
    try {
      setIsLoading(true);

      if (key === "links.figma") {
        if (!checkIfFigmaLinkIsValid({ figmaLink: value })) {
          throw new Error("Le lien Figma n'est pas valide");
        }
      }

      await projectsRef.doc(currentProjectData.id).update({
        [key]: value,
      });

      setTooltip({
        type: "success",
        text: "Paramètre mis à jour",
      });
    } catch (error) {
      setTooltip({
        type: "error",
        text: error.message,
      });
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <Page headerType="NAVIGATE" title={"Liens du projet"} scrollEnabled>
      {settingsList.map((setting) => {
        const { title, key, type } = setting;

        return (
          <InputRow
            key={key}
            itemKey={key}
            value={getValueFromKeyState({ key, state: currentProjectData })}
            type={type}
            title={title}
            onUpdateValue={onUpdateSetting}
          />
        );
      })}
    </Page>
  );
};
