import React, { useState, useEffect } from 'react';
import { View, Text } from 'react-native';
import { StatusBar } from 'expo-status-bar';
import { useFormik } from 'formik';
import { SafeAreaView } from 'react-native-safe-area-context';
import { router, Link } from 'expo-router';
import {
  PageHeader,
  StyledContainer,
  InnerContainer,
  StyledFormArea,
  Title,
  SubTitle,
  PageImage,
  StyledButton,
  ButtonText,
  MessageBox,
  Line,
  ExtraView,
  ExtraText,
  TextLinkContent,
  LoginTextInput
} from '@/components/generalHelpers.jsx';

import { signInWithEmailAndPassword } from 'firebase/auth';
import { auth } from '@/contexts/firebase';
import { useNotifications } from '@/hooks';

export default function Login() {
  const [hidePassword, setHidePassword] = useState(true);
  const [loginButtonDisabled, setLoginButtonDisabled] = useState(true);
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);
  const { expoPushToken } = useNotifications();

  const formik = useFormik({
    initialValues: {
      email: '',
      password: ''
    },
    onSubmit: async (values) => {
      setError('');
      setLoading(true);
      try {
        await signInWithEmailAndPassword(auth, values.email, values.password);
        router.replace('./incidents');
      } catch (err) {
        setError(err.message);
      } finally {
        setLoading(false);
      }
    },
  });

  const formValues = formik.values;

  useEffect(() => {
    if (formValues) {
      if (formValues.email && formValues.password) {
        setLoginButtonDisabled(false);
      } else {
        setLoginButtonDisabled(true);
      }
    }
  }, [formValues]);

  return (
    <React.Fragment>
      <PageHeader>
        <View style={{ flexDirection: 'row', height: 80, alignItems: 'center' }} />
      </PageHeader>
      <StyledContainer>
        <StatusBar style="dark" />
        <SafeAreaView />
        <InnerContainer>
          <PageImage resizeMode="cover" source={require('./../assets/images/tones-logo.png')} />
          <Title>Tones</Title>
          <SubTitle>Account Login</SubTitle>
          <StyledFormArea>
            {error ? <MessageBox style={{ color: 'red' }}>{error}</MessageBox> : null}
              <LoginTextInput 
                label="Email Address"
                icon="mail-outline"
                placeholder="test@organization.com"
                placeholderTextColor="gray"
                onChangeText={formik.handleChange('email')}
                onBlur={formik.handleBlur('email')}
                value={formik.values.email}
                keyboardType="email-address"
              />
              <LoginTextInput 
                label="Password"
                icon="lock-closed-outline"
                placeholder="* * * * * *"
                placeholderTextColor="gray"
                onChangeText={formik.handleChange('password')}
                onBlur={formik.handleBlur('password')}
                value={formik.values.password}
                secureTextEntry={hidePassword}
                isPassword
                hidePassword={hidePassword}
                setHidePassword={setHidePassword}
              />
              <MessageBox>...</MessageBox>
              <StyledButton onPress={formik.handleSubmit} disabled={loginButtonDisabled} style={loginButtonDisabled ? {backgroundColor: 'grey'} : {}}>
                <ButtonText>Login</ButtonText>
              </StyledButton>
              <Line />
              <ExtraView>
                <ExtraText>Don't have an account already? </ExtraText>
                <Link href='./register'>
                  <TextLinkContent>Register</TextLinkContent>
                </Link>
              </ExtraView>
            </StyledFormArea>
            <Line />
            <Text>Temporary Area:</Text>
            <View>
              <Link href='./incidents'>
                <TextLinkContent>Incidents</TextLinkContent>
              </Link>
              <Link href='./landing'>
                <TextLinkContent>Landing</TextLinkContent>
              </Link>
            </View>
            <Text>View Token: {expoPushToken}</Text>
            <Line />
          </InnerContainer>
        </StyledContainer>
      </React.Fragment>
    );
  }