import { useUser } from '@clerk/clerk-react'
import { CameraView, useCameraPermissions } from 'expo-camera'
import React, { useRef, useState } from 'react'
import { Button, Image, Modal, StyleSheet, Text, TextInput, TouchableOpacity, View } from 'react-native'

export default function App() {
    const { user } = useUser()
    const [permission, requestPermission] = useCameraPermissions()
    const [photo, setPhoto] = useState('')
    const [address, setAddress] = useState('')
    const [notes, setNotes] = useState('')
    const [showConfirmation, setShowConfirmation] = useState(false)
    const cameraRef = useRef<CameraView>(null)

    async function resetState() {
        setPhoto('')
        setAddress('')
        setNotes('')
    }

    async function _takePhoto() {
        if (cameraRef.current) {
            let pic = await cameraRef.current.takePictureAsync({
                quality: 0.1,
                base64: true
            })
            console.log(pic)
            setPhoto(pic.base64 || '')
        }
    }

    async function sendData() {
        await fetch('http://localhost:3000/api/v1/posts', {
            method: 'POST',
            headers: {
                Accept: 'application/json, text/plain, */*',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                clerkUserID: user?.id,
                date: new Date(),
                photo,
                address,
                notes
            })
        }).then((res) => {
            console.log(res.status)
            if (res.status === 200) {
                setShowConfirmation(true)
                resetState()
            }
        })
    }

    if (!permission) {
        // Camera permissions are still loading.
        return <View />
    }

    if (!permission.granted) {
        // Camera permissions are not granted yet.
        return (
            <View style={styles.container}>
                <Text style={styles.message}>We need your permission to show the camera</Text>
                <Button onPress={requestPermission} title='grant permission' />
            </View>
        )
    }

    return (
        <View style={styles.container}>
            {photo ? (
                <View style={styles.cameraContainer}>
                    <Image source={{ uri: photo }} style={styles.camera} />
                    <View>
                        <Text style={styles.label}>Address</Text>
                        <TextInput
                            style={styles.input}
                            placeholder='Add address here...'
                            value={address}
                            onChangeText={setAddress}
                        />
                    </View>
                    <View>
                        <Text style={styles.label}>Notes</Text>
                        <TextInput
                            style={styles.multiline}
                            placeholder='Add notes here...'
                            multiline
                            numberOfLines={4}
                            value={notes}
                            onChangeText={setNotes}
                        />
                    </View>
                    <View style={styles.buttonContainer}>
                        <TouchableOpacity style={styles.button} onPress={() => resetState()}>
                            <Text style={styles.text}>Retake</Text>
                        </TouchableOpacity>
                        <TouchableOpacity style={styles.button} onPress={sendData}>
                            <Text style={styles.text}>Continue</Text>
                        </TouchableOpacity>
                    </View>
                </View>
            ) : (
                <>
                    <View style={styles.cameraContainer}>
                        <CameraView style={styles.camera} facing={'back'} ref={cameraRef}></CameraView>
                    </View>
                    <View style={styles.buttonContainer}>
                        <TouchableOpacity style={styles.button} onPress={_takePhoto}>
                            <Text style={styles.text}>Take Photo</Text>
                        </TouchableOpacity>
                    </View>
                </>
            )}
            <Modal
                animationType='fade'
                transparent={true}
                visible={showConfirmation}
                onRequestClose={() => {
                    setShowConfirmation(!showConfirmation)
                }}
            >
                <View style={styles.modalView}>
                    <Text style={styles.modalText}>
                        Your post has been submitted and will be reviewed within 3 business days. Thanks!
                    </Text>
                    <TouchableOpacity
                        style={[styles.modalButton, styles.buttonClose]}
                        onPress={() => setShowConfirmation(!showConfirmation)}
                    >
                        <Text style={styles.textStyle}>Close</Text>
                    </TouchableOpacity>
                </View>
            </Modal>
        </View>
    )
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#25292e',
        justifyContent: 'center',
        paddingHorizontal: 25,
        paddingVertical: 200
    },
    centeredView: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center'
    },
    modalView: {
        flex: 1,
        top: '80%',
        height: 100,
        backgroundColor: '#363c43ff',
        borderRadius: 12,
        padding: 35,
        shadowColor: '#000',
        shadowOffset: {
            width: 0,
            height: 2
        },
        shadowOpacity: 0.25,
        shadowRadius: 4,
        elevation: 5
    },
    modalText: {
        marginBottom: 15,
        textAlign: 'center',
        color: 'white'
    },
    modalButton: {
        borderRadius: 20,
        padding: 10,
        elevation: 2
    },
    buttonClose: {
        backgroundColor: '#96a5b1ff',
        paddingHorizontal: 20,
        paddingVertical: 5,
        borderRadius: 12
    },
    textStyle: {
        color: 'white',
        fontWeight: 'bold',
        textAlign: 'center'
    },
    cameraContainer: {
        flex: 1
    },
    message: {
        textAlign: 'center',
        paddingBottom: 10
    },
    camera: {
        flex: 1
    },
    buttonContainer: {
        flex: 0.2,
        flexDirection: 'row',
        backgroundColor: 'orange',
        marginTop: 15,
        borderRadius: 5
    },
    button: {
        flex: 1,
        alignSelf: 'center',
        alignItems: 'center'
    },
    text: {
        fontSize: 24,
        fontWeight: 'bold',
        color: 'white'
    },
    input: {
        backgroundColor: 'white',
        borderRadius: 5,
        fontSize: 18,
        textAlignVertical: 'top'
    },
    label: { color: 'white', fontSize: 18, marginBottom: 5, marginTop: 10 },
    multiline: {
        backgroundColor: 'white',
        borderRadius: 5,
        fontSize: 18,
        minHeight: 80,
        textAlignVertical: 'top'
    }
})
