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';
import lang from '../../components/data/lang.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}}>{lang.en.register.selamat}</Text>
      <Text style={{color:"white", fontSize:28}}>{lang.en.register.akun_anda_berhasil_dibuat}</Text>
      <Text style={{color:"white", fontSize:18,textAlign:'center'}}>{lang.en.register.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: 'white'}}>
          <GestureHandlerRootView>
            <ScrollView>
              <View style={{
                flexDirection: "row"
                , height: 140
                , alignItems: "flex-end"
                , paddingHorizontal: 30
              }}>
                <View style={{ flex: 1 }}>

                </View>
                <View style={{
                  width: "auto",
                  backgroundColor: "white",
                  padding: 10,
                  borderRadius: 20
                }}>
                  <Image
                    source={require('../../assets/images/login/logo.png')}
                    style={{
                      width: 60
                      , height: 60
                    }}
                    resizeMode="contain"  // You can adjust this based on how you want the image to scale
                  />
                </View>
              </View>
              <View style={styles.container}>
                <Text style={styles.title}>{lang.en.register.buat_akun}</Text>
                <TextInput
                  style={styles.input}
                  placeholder={lang.en.register.nama_anda}
                  value={fullname}
                  onChangeText={setFullname}
                />
                
                <TextInput
                  style={styles.input}
                  placeholder={lang.en.register.email}
                  value={username}
                  onChangeText={setUsername}
                />
                
                <TextInput
                  style={styles.input}
                  placeholder={lang.en.register.no_hp}
                  value={phone}
                  onChangeText={setPhone}
                />
                
                <TextInput
                  style={styles.input}
                  placeholder={lang.en.register.password} 
                  value={password}
                  onChangeText={setPassword}
                  secureTextEntry
                />
                
                <TextInput
                  style={styles.input}
                  placeholder={lang.en.register.konfirmasi_password}
                  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" }}>
                  <View style={{ flex: 1 }}>
                    <Text>{lang.en.register.sudah_punya_akun}</Text>
                  </View>
                  <TouchableOpacity onPress={handleSignIn} style={{ marginHorizontal: 5 }}>
                    <Text style={{
                      color: "blue",
                      fontWeight: "bold"
                    }}>{lang.en.register.masuk_disini}</Text>
                  </TouchableOpacity>
                </View>
              </View>
            </ScrollView>
          </GestureHandlerRootView>
        </View>
      }
    </>
  );
};

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

export default RegisterScreen;
