import { BlurView } from "expo-blur";
import * as ImagePicker from "expo-image-picker";
import React, { useEffect, useState } from "react";
import { Platform, Pressable, Text, View, Image as RNImage } from "react-native";
import { Image as ExpoImage } from "expo-image";
import { responsiveHeight } from "react-native-responsive-dimensions";
import { useGlobal } from "reactn";
import { background, img } from "../../assets";
import GradientButton from "../../components/GradientButton";
import firebase, { serverTimestamp, usersRef } from "../../config/firebase";
import { uploadFileToFirebase } from "../../helpers/uploadToFirebase";
import Page from "../../layouts/Page";
import { goBack } from "../../navigation/NavigationService";
import { useUser } from "../../providers/UserDataProvider";
import { gutters, Palette } from "../../styles";
import { FONT_FAMILY } from "../../styles/Fonts";
import { size } from "../../styles/Style";
import EditInput from "./components/EditInput";

const EditProfile = () => {
  const [currentUserData] = useGlobal("currentUserData");
  const [, setTooltip] = useGlobal("_tooltip");
  const { currentUID } = useUser();
  const [pseudo, setPseudo] = useState("");
  const [loading, setLoading] = useState(false);
  const [updatingPhoto, setUpdatingPhoto] = useState(false);

  useEffect(() => {
    if (currentUserData?.userName && !pseudo) {
      setPseudo(currentUserData.userName);
    }
  }, [currentUserData?.userName]);

  const onSave = async () => {
    const raw = pseudo || "";
    const val = raw.trim();
    if (!val) return;

    try {
      setLoading(true);
      const uid = firebase.auth().currentUser?.uid;
      if (!uid) return;

      // Check uniqueness (case-insensitive)
      const lower = val.toLowerCase();
      const snap = await usersRef
        .where("userNameLower", "==", lower)
        .limit(1)
        .get();
      if (!snap.empty && snap.docs[0].id !== uid) {
        setTooltip({ text: "Ce pseudo est déjà pris", type: "error" });
        return;
      }

      await usersRef.doc(uid).set(
        {
          userName: val,
          userNameLower: lower,
          updatedAt: firebase.firestore.FieldValue.serverTimestamp(),
        },
        { merge: true }
      );

      setTooltip({ text: "Pseudo mis à jour", type: "success" });
      goBack();
    } catch (e) {
      console.log("EditProfile onSave error", e?.message);
      setTooltip({
        text: e?.message || "Mise à jour impossible",
        type: "error",
      });
    } finally {
      setLoading(false);
    }
  };

  const onChangePicture = async () => {
    try {
      setUpdatingPhoto(true);
      const uid = currentUID;
      if (!uid) return;

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

      const pickedUri = result?.assets?.[0]?.uri || null;
      if (!pickedUri) return;

      const { resultURI = null } = await uploadFileToFirebase({
        uri: pickedUri,
        path: `users/${uid}/profilePicture.png`,
      });

      if (!resultURI) throw new Error("Téléversement de l'image impossible");

      await usersRef.doc(uid).set(
        {
          profilePictureURL: resultURI,
          updatedAt: serverTimestamp(),
        },
        { merge: true }
      );

      await firebase.auth().currentUser.updateProfile({
        photoURL: resultURI,
      });

      setTooltip({ text: "Photo de profil mise à jour", type: "success" });
    } catch (e) {
      setTooltip({
        text: e?.message || "Erreur changement photo de profil",
        type: "error",
      });
    } finally {
      setUpdatingPhoto(false);
    }
  };
  return (
    <Page
      headerType="NAVIGATE"
      backgroundImg={background.profileBG}
      contentContainerStyle={{
        paddingBottom: gutters * 2,
      }}
      containerStyle={{
        backgroundColor: "#0000004D",
      }}
    >
      <View style={{ flex: 1, marginTop: responsiveHeight(2) }}>
        <BlurView
          intensity={20}
          style={{
            paddingVertical: 14,
            backgroundColor: Palette.glass,
            paddingHorizontal: 20,
            borderRadius: 20,
            overflow: "hidden",
            gap: 24,
          }}
          experimentalBlurMethod={
            Platform.OS !== "ios" ? "dimezisBlurView" : "none"
          }
        >
          <Pressable style={{ alignItems: "center" }} onPress={onChangePicture}>
            <ExpoImage
              source={
                currentUserData?.profilePictureURL
                  ? {
                      uri: currentUserData?.profilePictureURL,
                    }
                  : img.profile
              }
              cachePolicy="memory-disk"
              priority="high"
              contentFit="cover"
              transition={100}
              style={{
                ...size({ size: 108 }),
                borderRadius: 100,
              }}
            />
            <Text
              style={{
                fontSize: 14,
                color: Palette.white,
                fontFamily: FONT_FAMILY.InterRegular,
              }}
            >
              {updatingPhoto ? "Chargement..." : "Modifier la photo"}
            </Text>
          </Pressable>
          <EditInput
            label="Pseudo"
            placeholder="Pseudo"
            value={pseudo}
            setValue={setPseudo}
          />

          <GradientButton
            title={loading ? "Chargement..." : "Enregistrer les modifications"}
            containerStyle={{
              width: "80%",
              alignSelf: "center",
            }}
            onPress={onSave}
            disabled={
              loading ||
              updatingPhoto ||
              !pseudo?.trim() ||
              pseudo?.trim() === (currentUserData?.userName || "")
            }
          />
        </BlurView>
      </View>
    </Page>
  );
};

export default EditProfile;
