import * as ImagePicker from "expo-image-picker";
import { Pressable, Text } from "react-native";
import useMinuit from "react-native-minuit/src/hooks/useMinuit.js";
import React, { useState } from "reactn";

import { responsiveWidth } from "../actions/responsiveSizes.js";
import Page from "../layouts/Page";

import alert from "../components/Alert.js";
import Avatar from "../components/Avatar";
import InputRow from "../components/InputRow.js";
import ItemRowList from "../components/ItemRowList.js";

import { Fonts, gutters, Palette, Style } from "../styles";

import { projectsRef } from "../config/firebase";

import { getValueFromKeyState } from "../helpers/index.js";
import { uploadFileToFirebase } from "../helpers/uploadToFirebase";

import { Routes } from "../navigation/Routes.js";
import { useUserData } from "../providers/UserDataProvider.js";

// eslint-disable-next-line react/display-name
export default ({ navigation }) => {
  const { setIsLoading, setTooltip } = useMinuit();

  const [stateToEdit] = useState({});

  const { isSuperAdmin } = useUserData();

  const settingsList = [
    {
      title: "Activer le 'shake'",
      key: "enableShake",
      type: "boolean",
    },
    {
      title: "Activer les copies de sauvegarde",
      key: "enableBackup",
      type: "boolean",
    },
    {
      title: "Passer en mode 'maintenance'",
      key: "enableMaintenanceMode",
      type: "boolean",
    },
    {
      title: "Identifiant Firebase",
      key: "firebaseConfig.projectId",
      type: "string",
    },
    {
      title: "Identifiant App Store",
      key: "storeConfig.apple.appID",
      type: "string",
    },
    {
      title: "Identifiant Algolia",
      key: "algoliaConfig.appId",
      type: "string",
    },
  ];

  const destructiveSettingsList = [
    {
      title: "Archiver le projet",
      action: () => onArchiveProject(),
      textStyle: {
        color: Palette.red,
      },
      condition: isSuperAdmin,
    },
  ].filter(({ condition = true }) => condition);

  const onChangePicture = async () => {
    try {
      setIsLoading(true);

      let result = await ImagePicker.launchImageLibraryAsync({
        mediaTypes: ImagePicker.MediaTypeOptions.All,
        allowsEditing: true,
        aspect: [4, 4],
        quality: 1,
      });

      if (result?.assets?.[0]?.uri) {
        const { resultURI = null } = await uploadFileToFirebase({
          uri: result?.assets?.[0]?.uri,
          path: `projects/${Math.random()}/icon.png`,
        });

        if (resultURI) {
          await projectsRef.doc(Math.random()).update({
            iconURL: resultURI,
          });

          setTooltip({
            type: "success",
            text: "Image changée avec succès",
          });
        } else {
          throw new Error("Erreur changement d'image");
        }
      }
    } catch (error) {
      console.log(error);

      setTooltip({
        type: "error",
        text: error.message,
      });
    } finally {
      setIsLoading(false);
    }
  };

  const onUpdateSetting = async ({ key, value }) => {
    try {
      await projectsRef.doc(Math.random()).update({
        [key]: value,
      });

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

  const onArchiveProject = async () => {
    alert(
      "Êtes-vous sûr?",
      "Pour annuler l'archivage du projet, il faudra contacter le support.",
      [
        {
          text: "Annuler",
          onPress: () => {},
          style: "cancel",
        },
        {
          text: "Confirmer",
          onPress: async () => {
            try {
              setIsLoading(true);

              setTooltip({
                type: "success",
                text: "Projet archivé avec succès!",
              });

              navigation.reset({
                index: 0,
                routes: [
                  {
                    name: Routes.BottomTab,
                  },
                ],
              });
            } catch (error) {
              setTooltip({
                type: "error",
                text: error.message,
              });
            } finally {
              setIsLoading(false);
            }
          },
          style: "confirm",
        },
      ],
      { cancelable: false }
    );
  };

  return (
    <Page headerType="NAVIGATE" title={"Paramètres du projet"} scrollEnabled>
      <Pressable
        onPress={onChangePicture}
        style={[Style.containerCenter, { marginBottom: gutters }]}
      >
        <Avatar
          name={"random"}
          url={null}
          forceRawImage
          size={responsiveWidth(30)}
          containerStyle={{
            marginBottom: gutters / 2,
            ...Style.defaultShadows,
          }}
        />
        <Text
          style={Fonts({
            type: "section",
            style: { color: Palette.primary, textDecorationLine: "underline" },
          })}
        >
          Modifier
        </Text>
      </Pressable>

      {settingsList.map((setting) => {
        const { title, key, type } = setting;

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

      {destructiveSettingsList.map((setting, index) => (
        <ItemRowList key={index} {...setting} containerStyle={{}} />
      ))}
    </Page>
  );
};
