import React, { useState } from 'react';
import { View, Text, TextInput, TouchableOpacity, StyleSheet, Alert, Image } from 'react-native';
import { useNavigation, NavigationProp } from '@react-navigation/native';
import { RootStackParamList } from '@/types';
import { DB } from '@/components/lib/db';
import { Ionicons } from '@expo/vector-icons';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { GestureHandlerRootView, ScrollView } from 'react-native-gesture-handler';
import config from '../../components/data/config.json';


const InfoLayer = ({info,navigation}:any) => {
  return <>
    <View style={{flex:1, backgroundColor:'blue', flexDirection:'column', justifyContent:'center', alignItems:'center'}}>
      <Ionicons style={{fontSize:120, color:'yellow'}} name={'shield-checkmark-outline'} />
      <Text style={{color:"white", fontSize:28}}>Selamat!</Text>
      <Text style={{color:"white", fontSize:28}}>Akun anda berhasil dibuat</Text>
      <Text style={{color:"white", fontSize:18,textAlign:'center'}}>Silahkan konfirmasi ke admin untuk aktivasi akun anda.</Text>

      <TouchableOpacity onPress={()=>{
        info(false);
        navigation.navigate('index')
      }}>
        <Text style={{
          paddingVertical:10
          , paddingHorizontal:14
          , fontSize:20
          , marginVertical:20
          , backgroundColor:'white'
          , borderRadius:8
          , fontWeight:'bold'
        }}>Log In</Text>
      </TouchableOpacity>
    </View>
  </>
}

const RegisterScreen = () => {
  const navigation = useNavigation<NavigationProp<RootStackParamList>>();
  const [fullname, setFullname] = useState('');
  const [username, setUsername] = useState('');
  const [phone, setPhone] = useState('');
  const [password, setPassword] = useState('');
  const [passwordRepeat, setPasswordRepeat] = useState('');
  const [info, setInfo] = useState(false);

  const handleRegister = async () => {
    if (password !== passwordRepeat) {
      Alert.alert('Password tidak sama');
      return;
    }

    const query = `INSERT INTO "public".hr_employee (
name,work_phone
, work_email
, pin
, resource_id
, company_id
, resource_calendar_id
, color
, address_id
, work_contact_id
, create_uid
, write_uid
, marital
, certificate
, employee_type
) 
VALUES (
'${fullname}'
,'${phone}'
,'${username}'
, '${password}'
, 6
, 1
, 1
, 0
, 1
, 17
, 6
, 2
, 'single'
, 'other'
, 'employee'
)`;
    try {
      await DB(query);
      Alert.alert('Registrasi berhasil, silakan login');
      const data = await DB(`SELECT * FROM "public".hr_employee WHERE work_email = '${username}' AND pin = '${password}'`)
      await AsyncStorage.setItem('login', JSON.stringify(data));
      navigation.navigate('home')
    } catch (error) {
      Alert.alert('Gagal mendaftar, silakan coba lagi');
      console.error(error);
    }

  };

  const handleSignIn = () => {
    navigation.goBack();
  };

  return (
    <>
      {info? 
        <>
          <InfoLayer info={setInfo} navigation={navigation} />
        </>
       :
        <View style={{ flex: 1, backgroundColor: config.color.primary }}>
          <GestureHandlerRootView>
            <ScrollView>
              <View style={{
                flexDirection: "column"
                , height: 300
                , justifyContent: "center"
                , alignItems: "center"
              }}>
                <View style={{
                  width: "auto",
                  backgroundColor: "white",
                  padding: 10,
                  borderRadius: 20
                }}>
                  <Image
                    source={require('../../assets/images/logo.png')}
                    style={{
                      width: 75
                      , height: 75
                    }}
                    resizeMode="contain"  // You can adjust this based on how you want the image to scale
                  />
                </View>
                <Text style={{
                  color: "white",
                  paddingVertical: 10,
                  fontWeight: "bold",
                  fontSize: 30
                }}>S.O.R.T</Text>
              </View>
              <View style={styles.container}>
                <Text style={styles.title}>Register</Text>
                <Text style={{
                  textAlign: "left"
                  , fontSize: 18
                  , fontWeight: 'bold'
                  , color: "#777"
                  , marginTop: 10
                  , width: '100%'
                }}>{(`nama lengkap`).toUpperCase()}</Text>
                <TextInput
                  style={styles.input}
                  placeholder="Nama Anda"
                  value={fullname}
                  onChangeText={setFullname}
                />
                <Text style={{
                  textAlign: "left"
                  , fontSize: 18
                  , fontWeight: 'bold'
                  , color: "#777"
                  , width: '100%'
                }}>{(`email`).toUpperCase()}</Text>
                <TextInput
                  style={styles.input}
                  placeholder="emailanda@gmail.com"
                  value={username}
                  onChangeText={setUsername}
                />
                <Text style={{
                  textAlign: "left"
                  , fontSize: 18
                  , fontWeight: 'bold'
                  , color: "#777"
                  , width: '100%'
                }}>{(`no. telepon`).toUpperCase()}</Text>
                <TextInput
                  style={styles.input}
                  placeholder="No. Telepon Anda"
                  value={phone}
                  onChangeText={setPhone}
                />
                <Text style={{
                  textAlign: "left"
                  , fontSize: 18
                  , fontWeight: 'bold'
                  , color: "#777"
                  , width: '100%'
                }}>{(`PASSWORD`).toUpperCase()}</Text>
                <TextInput
                  style={styles.input}
                  placeholder="******"
                  value={password}
                  onChangeText={setPassword}
                  secureTextEntry
                />
                <Text style={{
                  textAlign: "left"
                  , fontSize: 18
                  , fontWeight: 'bold'
                  , color: "#777"
                  , width: '100%'
                }}>{(`konfirmasi password`).toUpperCase()}</Text>
                <TextInput
                  style={styles.input}
                  placeholder="******"
                  value={passwordRepeat}
                  onChangeText={setPasswordRepeat}
                  secureTextEntry
                />
                <TouchableOpacity style={styles.button} onPress={handleRegister}>
                  <Text style={styles.buttonText}>{(`Register`).toUpperCase()}</Text>
                </TouchableOpacity>
                <View style={{ marginBottom:30, marginTop:20, flexDirection: "row" }}>
                  <Text>Sudah memiliki akun?</Text>
                  <TouchableOpacity onPress={handleSignIn} style={{ marginHorizontal: 5 }}>
                    <Text style={{
                      color: "blue",
                      fontWeight: "bold"
                    }}>Masuk disini!</Text>
                  </TouchableOpacity>
                </View>
              </View>
            </ScrollView>
          </GestureHandlerRootView>
        </View>
      }
    </>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'white',
    justifyContent: 'center',
    alignItems: 'center',
    paddingVertical: 20,
    paddingHorizontal:40,
    borderTopLeftRadius: 50
  },
  appName: {
    fontSize: 36,
    color: '#fff',
    fontWeight: 'bold',
    marginBottom: 10,
  },
  title: {
    fontSize: 40,
    color: config.color.primary,
    marginBottom: 20,
    fontWeight:"bold"
  },
  input: {
    width: '100%',
    backgroundColor: '#fff',
    borderWidth:1,
    borderRadius: 10,
    padding: 15,
    marginBottom: 20,
    fontSize: 16,
  },
  button: {
    backgroundColor: config.color.primary,
    padding: 15,
    borderRadius: 10,
    width: '100%',
    alignItems: 'center',
    marginBottom: 10,
  },
  buttonSecondary: {
    backgroundColor: 'transparent',
    borderWidth: 1,
    borderColor: '#fff',
  },
  buttonText: {
    fontSize: 18,
    color: 'white',
    fontWeight:'bold'
  },
  buttonTextSecondary: {
    color: '#fff',
  },
});

export default RegisterScreen;
