/* eslint-disable react/display-name */
import React, { useEffect, useGlobal } from "reactn";
import Page from "../../layouts/Page";
import { gutters, Palette, Style } from "../../styles";
import { background } from "../../assets";
import { Platform, Text, View } from "react-native";
import { responsiveHeight } from "react-native-responsive-dimensions";
import { BlurView } from "expo-blur";
import Switch from "../../components/Switch";
import { useState } from "react";
import firebase, { usersRef } from "../../config/firebase";
import { FONT_FAMILY } from "../../styles/Fonts";

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

  const [isSwitch, setIsSwitch] = useState(false);

  useEffect(() => {
    setIsSwitch(!!currentUserData?.notifications);
  }, [currentUserData?.notifications]);

  const onToggle = async (next) => {
    try {
      setIsSwitch(next);
      const uid = currentUID || firebase.auth().currentUser?.uid;
      if (!uid) return;
      await usersRef.doc(uid).set({ notifications: next }, { merge: true });
      setTooltip({ type: "success", text: "Préférence enregistrée" });
    } catch (e) {
      setIsSwitch(!next);
      setTooltip({ type: "error", text: e?.message || "Enregistrement impossible" });
    }
  };

  return (
    <Page
      headerType="NAVIGATE"
      title="Paramètres"
      backgroundImg={background.profileBG}
      contentContainerStyle={{
        paddingBottom: gutters * 4,
      }}
      containerStyle={{
        backgroundColor: "#0000004D",
      }}
    >
      <View style={{ flex: 1, marginTop: responsiveHeight(2) }}>
        <BlurView
          intensity={20}
          style={{
            gap: 12,
            paddingVertical: 15,
            paddingHorizontal: 20,
            borderRadius: 20,
            overflow: "hidden",
            backgroundColor: Palette.glass,
          }}
          experimentalBlurMethod={
            Platform.OS !== "ios" ? "dimezisBlurView" : "none"
          }
        >
          <View style={Style.containerSpaceBetween}>
            <Text
              style={{
                fontSize: 20,
                color: Palette.white,
                fontFamily: FONT_FAMILY.HelveticaNeueMedium,
              }}
            >
              Notifications
            </Text>
            <Switch value={isSwitch} setValue={onToggle} />
          </View>
          <Text
            style={{
              fontSize: 12,
              color: Palette.white,
              fontFamily: FONT_FAMILY.InterRegular,
            }}
          >
            Nous t’encourageons à activer les notifications pour découvrir les
            derniers classements, les nouveaux sons et les meilleurs playbacks.
          </Text>
        </BlurView>
      </View>
    </Page>
  );
};
