import React, { useState } from 'react';
import { StyleSheet } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { ThemedText } from '../components/themed-text';
import { ThemedView } from '../components/themed-view';
import { Button } from '../components/ui/button';
import { InputField } from '../components/ui/input-field';
import { useApi } from '../lib/network/api';

export default function Login() {
  const api = useApi();
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [instanceUrl, setInstanceUrl] = useState("https://chat.murdle.top");
  const [error, setError] = useState<string | null>(null);

  const signIn = async () => {
    setError("");

    if (!email)
      return setError("Email is required");

    if (!password)
      return setError("Password is required");
    
    if (!instanceUrl)
      return setError("Instance URL is required");
    
    const res = await api.login(email, password, instanceUrl);
    if (!res.ok && res.error)
      return setError(res.error)    
  }

  return (
    <SafeAreaView style={{ flex: 1 }}>
      <ThemedView style={styles.container}>
        <ThemedText type="subtitle" style={styles.fullWidth}>Welcome!</ThemedText>

        <ThemedText
          type="default"
          style={[styles.fullWidth, { marginTop: 5, marginBottom: 15, opacity: 0.6 }]}
        >
          Enter your credentials below in order to login to your account
        </ThemedText>

        <InputField
          placeholder="Email"
          style={[styles.fullWidth]}
          onChangeText={(s) => setEmail(s)}
          value={email}
        />

        <InputField
          placeholder="Password"
          style={[styles.fullWidth, styles.controlSpacing]}
          secureTextEntry={true}
          onChangeText={(s) => setPassword(s)}
          value={password}
        />

        <InputField
          placeholder="Instance URL"
          style={[styles.fullWidth, styles.controlSpacing]}
          onChangeText={(s) => setInstanceUrl(s)}
          value={instanceUrl}
        />

        {error ?
          <ThemedText
            type="error"
            style={[styles.fullWidth, { marginTop: 12 }]}
          >
            {error}
          </ThemedText>
        : null}

        <Button style={[styles.fullWidth, { marginTop: 15 }]} onPress={signIn}>
          Sign In
        </Button>
      </ThemedView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    padding: 20,
    marginTop: 10,
  },
  fullWidth: {
    width: "90%",
    maxWidth: 670,
  },
  controlSpacing: {
    marginTop: 12,
  },
});
