import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useAuthStore } from '@/stores/authStore'
import { authFetch } from '@/lib/api'

export const useUpdateProfile = () => {
    const queryClient = useQueryClient()
    const { user, setUser } = useAuthStore()

    return useMutation({
        mutationFn: async (updatedProfile) => {
            const response = await fetch('/api/profiles/me', {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${user.token}`
                },
                body: JSON.stringify(updatedProfile)
            })

            if (!response.ok) {
                const error = await response.json()
                throw new Error(error.message || 'Profile update failed')
            }

            return response.json()
        },
        onSuccess: (updatedUser) => {
            const updatedState = {
                email: user.email,
                id: user.id,
                role: user.role,
                profile: updatedUser
            }

            setUser(updatedState);

            // Invalidate and refetch any related queries
            queryClient.invalidateQueries(['profile'])
            queryClient.invalidateQueries(['user', user.id])
        }
    })
}


export const useUpdateAvatar = () => {
    const { user, setUser } = useAuthStore()
    const queryClient = useQueryClient()

    return useMutation({
        mutationFn: async (file) => {
            if (!file) throw new Error('No file provided');

            const presignedResponse = await fetch('/api/profiles/uploads/sign-url', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${user.token}`
                },
                body: JSON.stringify({
                    fileName: file.name,
                    fileType: file.type,
                    folder: 'avatars'
                }),
                credentials: 'include'
            })

            if (!presignedResponse.ok) {
                const error = await presignedResponse.json();
                throw new Error('Failed to get upload URL')
            }

            const { uploadUrl, fileUrl } = await presignedResponse.json();

            // Upload directly to S3 using the pre-signed URL
            const s3Response = await fetch(uploadUrl, {
                method: 'PUT',
                body: file,
                headers: {
                    'Content-Type': file.type
                },
                credentials: 'include'
            })

            if (!s3Response.ok) {
                throw new Error('Failed to upload to S3')
            }

            const dbResponse = await fetch('/api/profiles/avatar', {
                method: 'PATCH',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${user.token}`
                },
                body: JSON.stringify({
                    avatarUrl: fileUrl
                }),
                credentials: 'include'
            });

            if (!dbResponse.ok) {
                const error = await dbResponse.json()
                throw new Error(error.message || 'Avatar update failed')
            }

            const data = await dbResponse.json();
            return data;
        },
        onSuccess: (data) => {
            const updatedState = {
                email: user.email,
                id: user.id,
                role: user.role,
                profile: {
                    ...user.profile,
                    avatar: data.avatarUrl
                }
            }
            setUser(updatedState)
            queryClient.invalidateQueries(['user', user.id])
            queryClient.invalidateQueries(['profile', user.id])
        }
    })
}

export const useUpdateDocuments = () => {
    const { user, setUser } = useAuthStore()
    const queryClient = useQueryClient()

    return useMutation({
        mutationFn: async (files) => {
            const formData = new FormData()
            files.forEach(file => formData.append('documents', file))

            const response = await fetch('/api/profiles/documents', {
                method: 'PATCH',
                headers: {
                    'Authorization': `Bearer ${user.token}`
                },
                body: formData
            })

            if (!response.ok) {
                const error = await response.json()
                throw new Error(error.message || 'Documents update failed')
            }

            return response.json()
        },
        onSuccess: (documents) => {
            const updatedState = {
                email: user.email,
                id: user.id,
                role: user.role,
                profile: {
                    ...user.profile,
                    documents
                }
            }
            setUser(updatedState)
            queryClient.invalidateQueries(['user', user.id])
            queryClient.invalidateQueries(['profile', user.id])
        }
    })
}