import React, { useEffect } from 'react';
import { Platform } from "react-native";
import { Button, TextInput, Dialog, Portal, Avatar, useTheme } from "react-native-paper";
import { Asset } from 'expo-asset';
import * as FileSystem from 'expo-file-system';
import * as ImagePicker from "expo-image-picker";

interface ProfileScreenProps {
    visible: boolean;
    id: string;
    name: string;
    setName: (name: string) => void;
    image: string;
    setImage: (image: string) => void;
    onClose: () => void;
}

const ProfileScreen: React.FC<ProfileScreenProps> = ({ visible, name, setName, image, setImage, onClose }) => {
    const { colors } = useTheme();

    useEffect(() => {
        const loadDefaultImage = async () => {
            const asset = Asset.fromModule(require("../assets/images/default_profile_image.png"));
            await asset.downloadAsync();
            if (Platform.OS === 'web') {
                const response = await fetch(asset.uri);
                const blob = await response.blob();
                return new Promise((resolve) => {
                    const reader = new FileReader();
                    reader.onloadend = () => {
                        const base64String = reader.result?.toString().replace(/^data:.+;base64,/, '');
                        resolve(base64String);
                        if (typeof base64String == "string") {
                            setImage(base64String);
                        } else {
                            throw new Error("Failed to load asset.");
                        }
                    };
                    reader.readAsDataURL(blob);
                });
            } else if (asset.uri) {
                const base64 = await FileSystem.readAsStringAsync(asset.uri, { encoding: FileSystem.EncodingType.Base64 });
                setImage(base64);
            }
        };

        const loadImage = async () => {
            if (!image) {
                await loadDefaultImage();
            }
        };
        loadImage().then(r => null);
    }, [image]);

    const pickImage = async () => {
        let result = await ImagePicker.launchImageLibraryAsync({ base64: true });
        if (!result.canceled && result.assets.length > 0) {
            setImage(result.assets[0].base64 || image);
        }
    };

    return (
        <Portal>
            <Dialog visible={visible} onDismiss={onClose} style={{ backgroundColor: colors.background }}>
                <Dialog.Title style={{ color: colors.onBackground, textAlign: 'center' }}>Edit Your Profile</Dialog.Title>
                <Dialog.Content>
                    <Avatar.Image
                        size={100}
                        source={image ? { uri: `data:image/png;base64,${image}` } : require("../assets/images/default_profile_image.png")}
                        style={{ alignSelf: 'center', marginBottom: 15 }}
                    />
                    <Button
                        onPress={pickImage}
                        mode="contained"
                        style={{ backgroundColor: colors.primary, marginBottom: 10 }}
                        labelStyle={{ color: colors.onPrimary }}
                    >
                        Change Profile Picture
                    </Button>
                    <TextInput
                        label="Your Pet's Name"
                        mode="outlined"
                        value={name}
                        onChangeText={setName}
                        style={{ marginBottom: 15, backgroundColor: colors.surface }}
                        placeholderTextColor={colors.onSurface}
                        theme={{ colors: { text: colors.onSurface } }}
                    />
                </Dialog.Content>
                <Dialog.Actions>
                    <Button
                        onPress={onClose}
                        mode="contained"
                        style={{ backgroundColor: colors.secondary }}
                        labelStyle={{ color: colors.onPrimary }}>Save</Button>
                </Dialog.Actions>
            </Dialog>
        </Portal>
        /*
        <Portal>
            <Dialog visible={visible} onDismiss={onClose} style={{ backgroundColor: colors.background }}>
                <Dialog.Title>Edit Your Profile</Dialog.Title>
                <Dialog.Content>
                    <Avatar.Image
                        size={100}
                        source={image ? { uri: `data:image/png;base64,${image}` } : require("../assets/images/default_profile_image.png")}
                        style={{ alignSelf: 'center', marginBottom: 15 }}
                    />
                    <Button onPress={pickImage} mode="contained" style={{ backgroundColor: colors.primary, marginBottom: 10 }}>Change Profile Picture</Button>
                    <TextInput
                        label="Your Pet's Name"
                        mode="outlined"
                        value={name}
                        onChangeText={setName}
                        style={{ marginBottom: 15, backgroundColor: colors.surface, color: colors.primary }}
                    />
                </Dialog.Content>
                <Dialog.Actions>
                    <Button onPress={onClose} mode="contained" style={{ backgroundColor: colors.secondary }}>Save</Button>
                </Dialog.Actions>
            </Dialog>
        </Portal>
         */
    );
};

export default ProfileScreen;
