import { Account, Avatars, Client, Databases, OAuthProvider, Query } from "react-native-appwrite";
import * as Linking from "expo-linking"
import { openAuthSessionAsync } from "expo-web-browser";
import { attribute } from "postcss-selector-parser";
import limit from "ajv-formats/src/limit";
import { Storage, ID } from 'react-native-appwrite';

// Add this debug log
// console.log('Environment Variables:', {
//     endpoint: process.env.EXPO_PUBLIC_APPWRITE_ENDPOINT,
//     projectId: process.env.EXPO_PUBLIC_APPWRITE_PROJECT_ID,
// });

if (!process.env.EXPO_PUBLIC_APPWRITE_ENDPOINT || !process.env.EXPO_PUBLIC_APPWRITE_PROJECT_ID) {
    throw new Error('Missing required Appwrite environment variables');
}

export const config = {
    platform: 'com.placebomk.mobilemk',
    endpoint: process.env.EXPO_PUBLIC_APPWRITE_ENDPOINT,
    projectId: process.env.EXPO_PUBLIC_APPWRITE_PROJECT_ID,
    databaseId: process.env.EXPO_PUBLIC_APPWRITE_DATABASE_ID,
    usersId: process.env.EXPO_PUBLIC_APPWRITE_USERS_COLLECTION_ID,
    carId: process.env.EXPO_PUBLIC_APPWRITE_CARS_COLLECTION_ID,
    bucketId: process.env.EXPO_PUBLIC_APPWRITE_BUCKET_ID,
}

export const client = new Client();

client
    .setEndpoint(config.endpoint!)
    .setProject(config.projectId!)
    .setPlatform(config.platform!)

export const avatar = new Avatars(client);
export const account = new Account(client);
export const databases = new Databases(client);

// Initialize storage
export const storageClient = new Storage(client);

export async function login() {
    // Your code here to authenticate the user and return their JWT token.
    try {
        const redirectUri = Linking.createURL('/');
        const response = await account.createOAuth2Token(OAuthProvider.Google, redirectUri);

        if (!response) throw new Error('failed to login');

        const browserResult = await openAuthSessionAsync(
            response.toString(),
            redirectUri
        )

        if (!browserResult.type || browserResult.type !== 'success') {
            throw new Error('failed to log in');
        }

        const url = new URL(browserResult.url);

        const secret = url.searchParams.get('secret')?.toString();
        const userId = url.searchParams.get('userId')?.toString();

        if (!secret || !userId) {
            throw new Error('failed to authenticate user');
        }

        const session = await account.createSession(userId, secret);
        if (!session) throw new Error('failed to create session');
        return true;
    }
    catch (error) {
        console.error("Failed to authenticate user:", error);
        return false;
    }
}

export async function getCurrentUser() {
    try {
        const response = await account.get();
        if (response.$id) {
            const userAvatar = avatar.getInitials(response.name)
            return {
                ...response,
                avatar: userAvatar.toString(),
            }
        }
    } catch (error) {
        console.error(error)
        return null;
    }
}

export async function logOut(): Promise<boolean> {
    try {
        await account.deleteSession('current');
        return true;
    } catch (error) {
        console.error("Failed to log out user:", error);
        return false;
    }
}


export async function saveUserToDatabase(userData: {
    userId: string;
    name: string;
    email: string;
    avatar: string;
}) {
    try {
        // First check if user already exists
        try {
            await databases.getDocument(
                config.databaseId!,
                config.usersId!,
                userData.userId
            );
            console.log('User already exists in database');
            return null;
        } catch (error) {
            // User doesn't exist, proceed with creation
            const result = await databases.createDocument(
                config.databaseId!,
                config.usersId!,
                userData.userId,
                {
                    name: userData.name,
                    email: userData.email,
                    avatar: userData.avatar,
                    createdAt: new Date().toISOString(),
                }
            );
            console.log('User created successfully');
            return result;
        }
    } catch (error) {
        console.error("Failed to save user data:", error);
        return null;
    }
}

// Add image upload function
export async function uploadImage(imageFile: {
    uri: string;
    name?: string;
    type?: string;
    size?: number;
}) {
    try {
        const response = await storageClient.createFile(
            config.bucketId!,
            ID.unique(),
            {
                uri: imageFile.uri,
                name: imageFile.name || 'image.jpg',
                type: imageFile.type || 'image/jpeg',
                size: imageFile.size || 0
            }
        );
        return storageClient.getFileView(config.bucketId!, response.$id).toString();
    } catch (error) {
        console.error('Error uploading image:', error);
        throw error;
    }
}

// Add image delete function
export async function deleteImage(fileId: string) {
    try {
        await storageClient.deleteFile(config.bucketId!, fileId);
        return true;
    } catch (error) {
        console.error('Error deleting image:', error);
        throw error;
    }
}
