import { BackgroundImage } from '@rneui/base';
import { StyleSheet, Text, View, TouchableOpacity, ScrollView } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import MapView, { MapCallout, Marker } from 'react-native-maps';
import React from 'react';
import TopBar from '../components/TopBar';
import { Point } from '../core/Point';

export default function Lap(props: { navigation: any, route : any}) {
    const { currentLap } = props.route.params;
    const { navigation } = props;

    const points: Point[] =  currentLap.getPoints();
    points.sort((pt1, pt2) => pt1.getTimer() - pt2.getTimer());


    const [currentPointIndex, setCurrentPointIndex] = React.useState(0);
    const currentPoint: Point | undefined = points[currentPointIndex];

    const goToPreviousPoint = () => {
        if (currentPointIndex > 0) {
            setCurrentPointIndex(currentPointIndex - 1);
            
        }
    };

    const goToNextPoint = () => {
        if (currentPointIndex < points.length - 1) {
            setCurrentPointIndex(currentPointIndex + 1);
        }
    };

    const markers: { id: number; name: string; coordinate: { latitude: number; longitude: number }, image: HTMLImageElement }[] = points.map((pt, index) => {
        var img;
        const brake = pt.getPBreakF();
        if(brake <= 0)
        {
            img = require("../assets/images/noBrake.png");
        }else if(brake > 0 && brake <= 30){
            img = require("../assets/images/startBrake.png");
        }else if(brake > 0 && brake <= 100){
            img = require("../assets/images/midBrake.png");
        }else{
            img = require("../assets/images/fullBrake.png");
        }
        return {
          id: index,
          name: pt.getDistance() + 'm',
          coordinate: { latitude: pt.getGeo().getGpsLat(), longitude: pt.getGeo().getGpsLong() },
          image: img,
        };
      });

    const handleMarker = (index : number) => {
        setCurrentPointIndex(index);
    }

    // currentLap.getPoints().forEach(pt => {
    //     points.push({ latitude: pt.getGeo().getGpsLat(), longitude: pt.getGeo().getGpsLong() });
            
    // });

    //var currentLap : undefined; // Penser à vérifier si la session ne possède pas de tour !! si c'est le cas afficher une popup d'erreur
    return (
        <SafeAreaView style={styles.container}>
            <View style={styles.container}>
                {/* Header */}
                <TopBar navigation={navigation} />
                
                {/* Body */}
                <View style={styles.container}>

                        <View style={styles.top_lap}>
                            <TouchableOpacity style={[styles.LapBrowserButton, currentPointIndex === 0 ? styles.disabled : null]} onPress={goToPreviousPoint}>
                                <View>
                                    <Text style={styles.button_text} >Previous Point</Text>
                                </View>
                            </TouchableOpacity>

                            <Text style={styles.text_title}>Point {currentPointIndex + 1 } </Text>

                            <TouchableOpacity style={[styles.LapBrowserButton, currentPointIndex === points.length - 1 ? styles.disabled : null]} onPress={goToNextPoint}>
                                <View>
                                    <Text style={styles.button_text} >Next Point</Text>
                                </View>
                            </TouchableOpacity>

                        </View>

                        <View style={styles.containerBody}>
                            <MapView
                                style={styles.map}
                                mapType="satellite"
                                region={{
                                    latitude:  currentLap.getLocationLat(),
                                    longitude: currentLap.getLocationLong(),
                                    latitudeDelta: 0.001,
                                    longitudeDelta: 0.015,
                                }}
                            >
                                {markers.map(({ id, name, coordinate,image }) => (
                                    <Marker key={id} title={name} coordinate={coordinate} onPress={() => handleMarker(id)} icon={image} style={{ width: 1, height: 1 }} />
                                ))}
                                 

                            </MapView>
                            <ScrollView style={ styles.scrollView}>
                            <BackgroundImage source={require('../assets/images/rdash.png')} resizeMode="contain" >   
                                
                                <View style={styles.container2}>

                                    <Text style={styles.header}>Point { currentPointIndex + 1} / { points.length} of Lap {currentLap.getNumber()}</Text>
                                    
                                    <View style={styles.infoContainer}>
                                        <Text style={styles.infoItem}>Time:</Text>
                                        <Text style={styles.infoValue}>{currentPoint.getFormattedTime()}</Text>
                                    </View>
                                    
                                    <View style={styles.infoContainer}>
                                        <Text style={styles.infoItem}>Distance:</Text>
                                        <Text style={styles.infoValue}>{currentPoint.getDistance()} m</Text>
                                    </View>

                                    <View style={styles.infoContainer}>
                                        <Text style={styles.infoItem}>Speed (vCar):</Text>
                                        <Text style={styles.infoValue}>{currentPoint.getVCar()} km/h</Text>
                                    </View>

                                    
                                    
                                    <View style={styles.infoContainer}>
                                        <Text style={styles.infoItem}>nGear:</Text>
                                        <Text style={styles.infoValue}>{currentPoint.getNGear()} gear</Text>
                                    </View>

                                    <View style={styles.infoContainer}>
                                        <Text style={styles.infoItem}>pBreakF:</Text>
                                        <Text style={styles.infoValue}>{currentPoint.getPBreakF()} bar</Text>
                                    </View>
                                    <View style={styles.infoContainer}>
                                        <Text style={styles.infoItem}>aSteer:</Text>
                                        <Text style={styles.infoValue}>{currentPoint.getASteer()} deg</Text>
                                    </View>
                                    <View style={styles.infoContainer}>
                                        <Text style={styles.infoItem}>rPedal:</Text>
                                        <Text style={styles.infoValue}>{currentPoint.getRPedal()} %</Text>
                                    </View>
                                    <View style={styles.infoContainer}>
                                        <Text style={styles.infoItem}>gLong:</Text>
                                        <Text style={styles.infoValue}>{currentPoint.getGLong()} g</Text>
                                    </View>
                                    <View style={styles.infoContainer}>
                                        <Text style={styles.infoItem}>gLat:</Text>
                                        <Text style={styles.infoValue}>{currentPoint.getGLat()} g</Text>
                                    </View>
                                </View>
                            </BackgroundImage>
                            </ScrollView>
                        </View>
                </View>

            </View>
        </SafeAreaView>
    );
}


const styles = StyleSheet.create({
    scrollView: {
        flex:1,
    },
    disabled: {
        opacity: 0.5,
        },
    addContainerButton: {
        margin:5,
        alignItems: "center",
        justifyContent: "center",
        height: "8%",
        borderRadius: 10,
        elevation: 3,
        backgroundColor: "#BF181F",
      },
    containerBody:{
        flex: 1,
        justifyContent: 'space-between',
        alignItems: 'stretch',
    },
    container2: {
        backgroundColor: 'rgba(255, 255, 255, 0.9)',
        borderColor:'black',
        borderWidth:2,
        padding: 10,
        borderRadius: 10,
        marginBottom: 20,
        shadowColor: '#000',
        shadowOffset: {
            width: 0,
            height: 2,
            },
        shadowOpacity: 0.25,
        shadowRadius: 3.84,
        elevation: 5,
    },
    header: {
        fontSize: 24,
        fontWeight: 'bold',
        marginBottom: 10,
    },
    infoContainer: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        marginBottom: 5,
    },
    infoItem: {
        fontSize: 18,
        fontWeight: 'bold',
    },
    infoValue: {
        fontSize: 18,
    },
    map: {
        flex:1,
    },
    top_lap: {
        height: "8%",
        flexDirection: 'row',
        justifyContent: 'space-between',
    },
    backgroundImage: {
        flex: 1,
        width: '100%',
    },
    container: {
        flex: 1,
    },
    LapBrowserButton: {
        width: "30%",
        marginTop:5,
        marginBottom:5,
        alignContent: 'center',
        justifyContent: 'center',
        borderRadius: 10,
        backgroundColor: '#BF181F',
    },
    button_text: {
        textAlign: 'center',
        color: '#fff',
        fontSize: 20,
    },
    text_title: {
        fontSize: 30,
        textAlign: 'center',
    },

});