import React, { useRef, useContext, useGlobal } from "reactn";
import { Text, View } from "react-native";

import { WebViewContext } from "../providers/WebViewProvider";
import { useUserData } from "../providers/UserDataProvider";

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

import { Routes } from "../navigation";
import { responsiveHeight } from "../actions/responsiveSizes.js";

import ItemRowList from "../components/ItemRowList";
import BottomSheetContainer from "../components/BottomSheetContainer.js";
import IconSelector from "../components/IconSelector.js";

import useLayoutType from "../hooks/useLayoutType";

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

import { onStoreReview, openLinkInBrowser } from "../helpers";
import {
  agencyWhatsAppNumber,
  calendlyUrl,
  instagramUrl,
  termsOfSalesUrl,
} from "../data";
import IconContainer from "../components/IconContainer.js";

export default ({ navigation }) => {
  const { isDesktop, isWeb, isNative } = useLayoutType();
  const { onSignOut } = useUserData();

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

  const { setWebViewUrl } = useContext(WebViewContext);

  const appIconBottomSheetRef = useRef(null);

  const settingsList = [
    {
      sectionTitle: "Projet",
      icon: icons.tools,
      optionList: [
        {
          title: "Paramètres",
          action: () => navigation.navigate(Routes.ProjectSettings),
        },
      ],
      condition: currentProjectID,
    },
    {
      sectionTitle: "Compte",
      icon: icons.user,
      optionList: [
        {
          title: "Paramètres du compte",
          action: () => navigation.navigate(Routes.AccountSettings),
        },
      ],
    },
    {
      sectionTitle: "Support",
      icon: icons.support,
      optionList: [
        {
          title: "Prendre rendez-vous",
          action: () => setWebViewUrl(calendlyUrl),
        },
        {
          title: "Nous suivre sur Instagram",
          action: () => setWebViewUrl(instagramUrl),
        },
        {
          title: "Nous contacter sur WhatsApp",
          action: () => {
            openLinkInBrowser({
              url: `http://api.whatsapp.com/send/?phone=${agencyWhatsAppNumber}&text&type=phone_number`,
            });
          },
        },
        {
          title: "Changer l'icône de l'application",
          action: () => {
            appIconBottomSheetRef.current?.expand();
          },
          condition: isNative,
        },
        {
          title: "Noter l'application",
          action: () => {
            onStoreReview();
          },
          condition: !isWeb,
        },
      ],
    },
    {
      sectionTitle: "Légal",
      icon: icons.law,
      optionList: [
        {
          title: "Conditions générales d'utilisation",
          action: () => navigation.navigate(Routes.TermsOfUse),
        },
        {
          title: "Conditions générales de vente",
          action: () => setWebViewUrl(termsOfSalesUrl),
        },
        {
          title: "Politique de confidentialité",
          action: () => navigation.navigate(Routes.PrivacyPolicy),
        },
        {
          title: "Se déconnecter",
          action: async () => {
            await onSignOut();
          },
          textStyle: { color: Palette.red },
          addMarginTopFromPrevious: true,
        },
      ],
    },
  ]
    .filter(({ condition = true }) => condition)
    .filter(
      ({ optionList }) =>
        optionList.filter(({ condition }) => !condition || condition).length > 0
    );

  return (
    <>
      <Page
        headerType={isDesktop ? "NONE" : "BASE"}
        scrollEnabled
        pageTitle="Paramètres"
        contentContainerStyle={{
          paddingTop: gutters / 2,
          paddingBottom: responsiveHeight(50),
        }}
      >
        {settingsList.map(
          ({ icon, sectionTitle = "", optionList = [] }, index) => (
            <View
              key={index}
              style={{ ...Style.containerItem, marginBottom: gutters / 2 }}
            >
              <View
                style={{
                  ...Style.containerRow,
                }}
              >
                <IconContainer icon={icon} />

                <Text
                  style={Fonts({
                    type: "title",
                    color: Palette.white,
                    style: {},
                  })}
                >
                  {sectionTitle}
                </Text>
              </View>

              {optionList
                .filter(({ condition = true }) => condition)
                .map((item, index) => (
                  <ItemRowList
                    key={index}
                    {...item}
                    containerStyle={{}}
                    separatorPosition="top"
                  />
                ))}
            </View>
          )
        )}
      </Page>

      <BottomSheetContainer
        bottomSheetRef={appIconBottomSheetRef}
        index={-1}
        enablePanDownToClose
        snapPoints={["80%"]}
      >
        <IconSelector onClose={() => appIconBottomSheetRef.current?.close()} />
      </BottomSheetContainer>
    </>
  );
};
