import { View, Text, Pressable, Image, ScrollView, Alert, ActivityIndicator } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { router } from 'expo-router';
import { PreviousPageBlackSvg } from '../global/SVG';
import NormalButton from '../global/normal_button';
import { useEffect, useState } from 'react';
import * as ImagePicker from 'expo-image-picker';
import * as SecureStore from 'expo-secure-store';
import * as FileSystem from 'expo-file-system';
import { authenticationService } from '../../service/authService';

const UberUploadPageComponent = () => {
    const [image, setImage] = useState('');
    const [isLoading, setIsLoading] = useState(false);

    const MAX_FILE_SIZE = 3 * 1024 * 1024;

    const pickImage = async () => {
        let result = await ImagePicker.launchImageLibraryAsync({
            mediaTypes: ImagePicker.MediaTypeOptions.Images,
            allowsEditing: true,
            aspect: [4, 3],
            quality: 1
        });

        if (!result.canceled) {
            const fileUri = result.assets[0].uri;

            const fileExtension = fileUri.split('.').pop().toLowerCase();
            if (!['jpg', 'jpeg', 'png'].includes(fileExtension)) {
                Alert.alert('錯誤', '請選擇 JPG, JPEG 或 PNG 格式的圖片');
                return;
            }

            setImage(fileUri);
        }
    };

    const uploadImage = async () => {
        if (!image) {
            Alert.alert('錯誤', '請先選擇一張圖片');
            return;
        }

        setIsLoading(true);

        try {
            const fileInfo = await FileSystem.getInfoAsync(image);
            if (!fileInfo.exists) {
                Alert.alert('錯誤', '無法讀取所選圖片');
                return;
            }

            const userInfo = await authenticationService.getUserInfo();
            if (!userInfo || !userInfo.data || !userInfo.data.id) {
                Alert.alert('錯誤', '無法取得使用者資訊');
                return;
            }

            const userId = userInfo?.data.id;
            const timestamp = new Date().getTime();
            const fileExtension = image.split('.').pop()?.toLowerCase() || 'jpg';
            const customFileName = `uber_${userId}_${timestamp}.${fileExtension}`;

            const result = await authenticationService.uploadUberImage(image, customFileName);

            if (result) {
                Alert.alert('成功', '證明上傳成功');
                router.push('uberUploadCompletePage');
            } else {
                Alert.alert('錯誤', result.message || '上傳失敗，請稍後再試');
            }
        } catch (error) {
            console.error('Error uploading image:', error);
            console.error('Status:', error.response?.status);
            console.error('Headers:', error.response?.headers);
            Alert.alert('錯誤', '上傳時發生錯誤，請稍後再試');
            throw error;
        } finally {
            setIsLoading(false);
        }
    };

    return (
        <SafeAreaView className="flex-1 bg-white" edges={['top', 'right', 'left']}>
            <ScrollView style={{ flex: 1 }} className="mx-[5%]" showsVerticalScrollIndicator={false}>
                <View style={{ marginTop: 25 }}>
                    <Pressable
                        onPress={() => {
                            if (router.canGoBack()) {
                                router.back();
                            } else {
                                router.replace('/accountMainPage');
                            }
                        }}
                    >
                        <PreviousPageBlackSvg />
                    </Pressable>
                    <Text style={{ fontSize: 45, marginVertical: 25 }}>上傳證明</Text>

                    <View className="space-y-2">
                        <Text style={{ fontSize: 22 }}>請上傳Uber司機的證明圖片</Text>
                        <Text style={{ fontSize: 18 }}>• 司機名稱</Text>
                        <Text style={{ fontSize: 18 }}>• 車牌</Text>
                        <Text style={{ fontSize: 18 }}>• 車輛品牌及型號</Text>
                    </View>
                    <View className="mt-5 ">
                        <Text style={{ fontSize: 22, marginBottom: 9 }}>上傳範例</Text>
                        <View className="flex-row w-full justify-between">
                            <Image
                                source={require('../../assets/uberUploadSample111.png')}
                                resizeMode="contain"
                                className="flex-1 h-auto"
                                style={{ aspectRatio: 1 }}
                            />
                            <Image
                                source={require('../../assets/uberUploadSample222.png')}
                                resizeMode="contain"
                                className="flex-1 h-auto"
                                style={{ aspectRatio: 1 }}
                            />
                        </View>

                        {image ? (
                            <Pressable onPress={pickImage} disabled={true}>
                                <View
                                    style={{ borderWidth: 1 }}
                                    className="border-[#EEEEEE] rounded-2xl items-center justify-center  p-4 "
                                >
                                    <Text className="text-xl text-[#02677d]  text-center ">上傳成功</Text>
                                </View>
                            </Pressable>
                        ) : (
                            <Pressable onPress={pickImage}>
                                <View
                                    style={{ borderWidth: 1 }}
                                    className="border-[#EEEEEE] rounded-2xl items-center justify-center  p-4 "
                                >
                                    <Text style={{ fontSize: 48 }} className="text-[#02677d] text-center">
                                        +
                                    </Text>

                                    <Text className="text-xl text-[#02677d] mb-6 text-center ">上傳圖片</Text>
                                </View>
                            </Pressable>
                        )}

                        <View className="mt-4">
                            <NormalButton
                                title={
                                    isLoading ? (
                                        <ActivityIndicator color="white" />
                                    ) : (
                                        <Text className="text-xl text-white">提交</Text>
                                    )
                                }
                                onPress={uploadImage}
                                disabled={isLoading}
                            />
                        </View>
                    </View>
                </View>
            </ScrollView>
        </SafeAreaView>
    );
};

export default UberUploadPageComponent;
