import { View, Text } from "react-native";
import React, { useState } from "react";
import { useGlobal } from "reactn";
import Page from "../layouts/Page";
import { background } from "../assets";
import ItemContainer from "../components/ItemContainer/ItemContainer";
import { Palette } from "../styles";
import { FONT_FAMILY } from "../styles/Fonts";
import { Input } from "../components/Input";
import GradientButton from "../components/GradientButton";
import { navigate } from "../navigation/NavigationService";
import { Routes } from "../navigation";
import firebase, { usersRef } from "../config/firebase";

const CreatePseudo = () => {
  const [userName, setUserName] = useState("");
  const [loading, setLoading] = useState(false);
  const [, setTooltip] = useGlobal("_tooltip");

  const onCreate = async () => {
    const raw = userName || "";
    const val = raw.trim();
    if (!val) return;
    try {
      setLoading(true);
      const uid = firebase.auth().currentUser?.uid;
      if (!uid) {
        return navigate(Routes.Login);
      }
      // 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: `Bienvenue ${val}`, type: "success" });
      navigate(Routes.BottomTab);
    } catch (e) {
      console.log("CreatePseudo error", e?.message);
      setTooltip({ text: e?.message || "Enregistrement impossible", type: "error" });
    } finally {
      setLoading(false);
    }
  };

  return (
    <Page
      backgroundImg={background.homeBG}
      headerType="NAVIGATION"
      title="Ton pseudo"
      hideBackButton
    >
      <View style={{ flex: 1, paddingTop: 20 }}>
        <ItemContainer height={275}>
          <View style={{ gap: 32, paddingTop: 5, paddingHorizontal: 5 }}>
            <View style={{ gap: 16 }}>
              <View style={{ gap: 2 }}>
                <Text
                  style={{
                    fontSize: 22,
                    color: Palette.white,
                    fontFamily: FONT_FAMILY.InterSemiBold,
                  }}
                >
                  Choisis ton pseudo
                </Text>
                <Text
                  style={{
                    fontSize: 14,
                    color: Palette.gray,
                    fontFamily: FONT_FAMILY.InterRegular,
                  }}
                >
                  Visible par les autres utilisateurs.
                </Text>
              </View>
              <Input
                placeholder="Pseudo"
                label="Pseudo"
                isBlur
                value={userName}
                setValue={setUserName}
              />
            </View>
            <GradientButton
              title={loading ? "Chargement..." : "Valider"}
              containerStyle={{
                width: "80%",
                alignSelf: "center",
              }}
              onPress={onCreate}
              disabled={loading || !userName?.trim()}
            />
          </View>
        </ItemContainer>
      </View>
    </Page>
  );
};

export default CreatePseudo;
