'use client'

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { apiGet, apiPatch, apiPost, apiDelete, ApiError } from '@/lib/api/client'

// Types
export interface Profile {
  id: string
  email: string
  name: string | null
  role: string
  profilePhotoKey: string | null
  profilePhotoUrl: string | null
  twoFactorEnabled: boolean
  createdAt: string
  updatedAt: string
}

export interface UpdateProfilePayload {
  name?: string
}

export interface ChangePasswordPayload {
  currentPassword: string
  newPassword: string
  confirmPassword: string
}

export interface PhotoUploadResult {
  success: boolean
  message: string
  profilePhotoKey: string
  profilePhotoUrl: string | null
}

// Query keys
export const profileKeys = {
  all: ['profile'] as const,
  detail: () => [...profileKeys.all, 'detail'] as const,
}

// API functions
async function getProfile(): Promise<Profile> {
  return apiGet<Profile>('/api/v1/profile')
}

async function updateProfile(data: UpdateProfilePayload): Promise<Profile> {
  return apiPatch<Profile>('/api/v1/profile', data)
}

async function changePassword(data: ChangePasswordPayload): Promise<{ success: boolean; message: string }> {
  return apiPost<{ success: boolean; message: string }>('/api/v1/profile/password', data)
}

async function uploadPhoto(file: File): Promise<PhotoUploadResult> {
  const formData = new FormData()
  formData.append('photo', file)

  const response = await fetch('/api/v1/profile/photo', {
    method: 'POST',
    body: formData,
  })

  if (!response.ok) {
    let data: unknown
    try {
      data = await response.json()
    } catch {
      // Response is not JSON
    }
    throw new ApiError(response.status, response.statusText, data)
  }

  return response.json()
}

async function deletePhoto(): Promise<{ success: boolean; message: string }> {
  return apiDelete<{ success: boolean; message: string }>('/api/v1/profile/photo')
}

// Hooks
export function useProfile() {
  return useQuery({
    queryKey: profileKeys.detail(),
    queryFn: getProfile,
  })
}

export function useUpdateProfile() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: updateProfile,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: profileKeys.detail() })
    },
  })
}

export function useChangePassword() {
  return useMutation({
    mutationFn: changePassword,
  })
}

export function useUploadPhoto() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: uploadPhoto,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: profileKeys.detail() })
    },
  })
}

export function useDeletePhoto() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: deletePhoto,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: profileKeys.detail() })
    },
  })
}
