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

export default ({ navigation }) => {
  const [, setTooltip] = useGlobal("_tooltip");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [loading, setLoading] = useState(false);

  const onLogin = async () => {
    try {
      setLoading(true);
      await firebase.auth().signInWithEmailAndPassword(email.trim(), password);
      const uid = firebase.auth().currentUser?.uid;
      if (!uid) throw new Error("Aucun utilisateur après connexion");
      const snap = await usersRef.doc(uid).get();
      const hasUserName = !!snap.data()?.userName;
      if (hasUserName) {
        navigation.reset({ index: 0, routes: [{ name: Routes.BottomTab }] });
      } else {
        navigation.reset({ index: 0, routes: [{ name: Routes.CreatePseudo }] });
      }
    } catch (e) {
      console.log("Login error", e?.message);
      setTooltip({ text: e?.message || "Connexion impossible", type: "error" });
    } finally {
      setLoading(false);
    }
  };

  return (
    <Page
      backgroundImg={background.homeBG}
      headerType="NAVIGATION"
      title="Connexion"
      hideBackButton
    >
      <View style={{ flex: 1, paddingTop: 20 }}>
        <ItemContainer height={490}>
          <View style={{ gap: 30, paddingTop: 5, paddingHorizontal: 5 }}>
            <View style={{ gap: 2 }}>
              <Text
                style={{
                  fontSize: 22,
                  color: Palette.white,
                  fontFamily: FONT_FAMILY.InterSemiBold,
                }}
              >
                Bonjour !
              </Text>
              <Text
                style={{
                  fontSize: 14,
                  color: Palette.gray,
                  fontFamily: FONT_FAMILY.InterRegular,
                }}
              >
                Nous sommes heureux de te revoir parmi nous. Prêt·e à reprendre
                le rythme ?
              </Text>
            </View>
            <View style={{ gap: 20 }}>
              <Input
                placeholder="Adresse mail"
                label="Adresse mail"
                type="email"
                value={email}
                setValue={setEmail}
                isBlur
              />
              <View style={{ gap: 4 }}>
                <Input
                  placeholder="Mot de passe"
                  label="Mot de passe"
                  type="password"
                  value={password}
                  setValue={setPassword}
                  isBlur
                />
                <Pressable
                  onPress={() => navigate(Routes.ForgotPassword)}
                >
                  <Text
                    style={{
                      fontSize: 12,
                      color: Palette.white,
                      fontFamily: FONT_FAMILY.HelveticaNeueRegular,
                    }}
                  >
                    Mot de passe oublié?
                  </Text>
                </Pressable>
              </View>
            </View>
            <GradientButton
              title="Se connecter"
              containerStyle={{
                width: "80%",
                alignSelf: "center",
              }}
              onPress={onLogin}
              disabled={loading || !email || !password}
            />
            <View
              style={{
                alignItems: "center",
                gap: 4,
              }}
            >
              <Pressable onPress={() => navigate(Routes.Register)}>
                <Text
                  style={{
                    fontSize: 14,
                    color: Palette.white,
                    fontFamily: FONT_FAMILY.HelveticaNeueRegular,
                  }}
                >
                  Pas encore de compte?{" "}
                  <Text
                    style={{
                      fontFamily: FONT_FAMILY.InterSemiBold,
                    }}
                  >
                    Créer un compte
                  </Text>
                </Text>
              </Pressable>
            </View>
          </View>
        </ItemContainer>
      </View>
    </Page>
  );
};
