import React, { useState } from "react";
import { Button, Text, View } from "react-native";
import ELogo from "@components/ELogo";
import ETextInput from "@components/ETextInput";
import EFullButton, { EIconButton } from "@components/EButton";
import { ColorScheme } from "@components/Design";
import { AppleIcon, GoogleIcon } from "@components/EIcons";
import { ECaptionText, ELabelText } from "@components/EText";
import auth from "@react-native-firebase/auth";
import { useRouter } from "expo-router";
import { GoogleSignin } from "@react-native-google-signin/google-signin";
import { useAuthState } from "@components/AuthProvider";

GoogleSignin.configure({
  webClientId:
    "406674810515-l8a40f83kl5hnvflvcjrabmjmbvda7am.apps.googleusercontent.com",
});

export default function LoginScreen(props: any) {
  const [email, setEmail] = useState<string>("");
  const [password, setPassword] = useState<string>("");
  const [error, setError] = useState(false);
  const router = useRouter();
  const [loginAttempting, setLoginAttempting] = useState(false);
  const signInWithEmail = async () => {
    setLoginAttempting(true);
    try {
      await auth().signInWithEmailAndPassword(email, password);
      router.replace("/");
    } catch (e) {
      setError(true);
    }
    setLoginAttempting(false);
  };
  const signInWithGoogle = async () => {
    setLoginAttempting(true);
    await GoogleSignin.hasPlayServices({ showPlayServicesUpdateDialog: true });
    const { idToken } = await GoogleSignin.signIn();
    const googleCredential = auth.GoogleAuthProvider.credential(idToken);
    return auth().signInWithCredential(googleCredential);
  };
  const [user, loginstate, setLoginState] = useAuthState();
  return (
    <>
      <View
        style={{
          flex: 1,
          rowGap: 24,
          flexDirection: "column",
          paddingTop: 80,
        }}
      >
        <ELogo />
        <View style={{ rowGap: 16, flexDirection: "column" }}>
          <ETextInput
            placeholder={"이메일"}
            value={email}
            setValue={setEmail}
            onChange={() => setError(false)}
          />
          <ETextInput
            placeholder={"비밀번호"}
            value={password}
            setValue={setPassword}
            passwordHidden={true}
            onChange={() => setError(false)}
          />
          {error && (
            <ECaptionText error={true}>
              이메일 혹은 비밀번호가 일치하지 않습니다
            </ECaptionText>
          )}
        </View>
        <View style={{ rowGap: 16, flexDirection: "column" }}>
          <EFullButton
            text={"로그인"}
            active={
              email.length !== 0 && password.length !== 0 && !loginAttempting
            }
            onPress={() => signInWithEmail()}
          />
          <EFullButton
            style={{ backgroundColor: ColorScheme.passthrough }}
            onPress={() => {
              setLoginState &&
                setLoginState({ ...loginstate, passwordReset: true });
              router.push("auth/passwordresetemail");
            }}
            active={true}
            text={"비밀번호를 모르겠어요"}
          />
          <View
            style={{
              flex: 1,
              justifyContent: "center",
              columnGap: 16,
              flexDirection: "row",
            }}
          >
            <EIconButton active={false}>
              <AppleIcon fill={ColorScheme.fill[10]} />
            </EIconButton>
            <EIconButton
              active={!loginAttempting}
              onPress={() => {
                signInWithGoogle()
                  .then((d) => {
                    console.log("worked!");
                    setLoginAttempting(false);
                    router.replace("");
                  })
                  .catch((e) => {
                    console.error(e);
                    setLoginAttempting(false);
                  });
              }}
            >
              <GoogleIcon fill={ColorScheme.fill[10]} />
            </EIconButton>
          </View>
        </View>
      </View>
      <View style={{ flexDirection: "column", rowGap: 16, marginTop: 200 }}>
        <ELabelText style={{ textAlign: "center" }}>
          아직 회원이 아니신가요?
        </ELabelText>
        <EFullButton
          onPress={() => {
            setLoginState &&
              setLoginState({ ...loginstate, passwordReset: false });
            router.push("auth/registeremail");
          }}
          style={{ backgroundColor: ColorScheme.frostedfill.white[10] }}
          active={true}
          text={"회원가입"}
        />
      </View>
    </>
  );
}
