import { View, Text, Pressable } 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 { useRoute } from "@react-navigation/native";
import firebase, { usersRef } from "../config/firebase";
import { Routes } from "../navigation";

const CreatePassword = () => {
  const route = useRoute();
  const email = route?.params?.email || "";
  const [password, setPassword] = useState("");
  const [loading, setLoading] = useState(false);
  const [, setTooltip] = useGlobal("_tooltip");

  const onCreateAccount = async () => {
    try {
      setLoading(true);
      const cred = await firebase
        .auth()
        .createUserWithEmailAndPassword(email.trim(), password);
      const uid = cred?.user?.uid || firebase.auth().currentUser?.uid;
      if (!uid) throw new Error("Création de compte échouée");
      await usersRef.doc(uid).set(
        {
          email: email.trim(),
          createdAt: firebase.firestore.FieldValue.serverTimestamp(),
          updatedAt: firebase.firestore.FieldValue.serverTimestamp(),
        },
        { merge: true },
      );
      setTooltip({ text: "Compte créé, continuons", type: "success" });
      navigate(Routes.CreatePseudo);
    } catch (e) {
      console.log("Register error", e?.message);
      setTooltip({ text: e?.message || "Création impossible", type: "error" });
    } finally {
      setLoading(false);
    }
  };

  return (
    <Page
      backgroundImg={background.homeBG}
      headerType="NAVIGATION"
      title="Inscription"
    >
      <View style={{ flex: 1, paddingTop: 20 }}>
        <ItemContainer height={300}>
          <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 un mot de passe{"\n"}sécurisé
                </Text>
                <Text
                  style={{
                    fontSize: 14,
                    color: Palette.gray,
                    fontFamily: FONT_FAMILY.InterRegular,
                  }}
                >
                  Utilise au moins 8 caractères pour sécuriser ton compte.
                </Text>
              </View>
              <Input
                placeholder="Mot de passe"
                label="Mot de passe"
                isBlur
                type="password"
                value={password}
                setValue={setPassword}
              />
            </View>
            <GradientButton
              title={loading ? "Création..." : "Suivant"}
              containerStyle={{
                width: "80%",
                alignSelf: "center",
              }}
              onPress={onCreateAccount}
              disabled={loading || !email || !password}
            />
          </View>
        </ItemContainer>
      </View>
    </Page>
  );
};

export default CreatePassword;
