"use client"

import useSWR, { mutate } from "swr"

const fetcher = async (url: string) => {
  const res = await fetch(url)
  if (!res.ok) {
    const error = await res.json()
    throw new Error(error.error || "Une erreur est survenue")
  }
  return res.json()
}

// Dashboard Stats
export function useDashboardStats() {
  const { data, error, isLoading } = useSWR("/api/stats/dashboard", fetcher, {
    refreshInterval: 30000, // Refresh every 30 seconds
  })

  return {
    stats: data,
    isLoading,
    error,
  }
}

// Users
export function useUsers(params?: { page?: number; limit?: number; search?: string; role?: string; status?: string }) {
  const searchParams = new URLSearchParams()
  if (params?.page) searchParams.set("page", params.page.toString())
  if (params?.limit) searchParams.set("limit", params.limit.toString())
  if (params?.search) searchParams.set("search", params.search)
  if (params?.role) searchParams.set("role", params.role)
  if (params?.status) searchParams.set("status", params.status)

  const { data, error, isLoading } = useSWR(`/api/users?${searchParams.toString()}`, fetcher)

  return {
    users: data?.data || [],
    total: data?.total || 0,
    totalPages: data?.totalPages || 0,
    isLoading,
    error,
    mutate: () => mutate(`/api/users?${searchParams.toString()}`),
  }
}

export function useUser(id: string) {
  const { data, error, isLoading } = useSWR(id ? `/api/users/${id}` : null, fetcher)

  return {
    user: data,
    isLoading,
    error,
  }
}

// Tracks
export function useTracks(params?: {
  page?: number
  limit?: number
  search?: string
  status?: string
  artist_id?: string
}) {
  const searchParams = new URLSearchParams()
  if (params?.page) searchParams.set("page", params.page.toString())
  if (params?.limit) searchParams.set("limit", params.limit.toString())
  if (params?.search) searchParams.set("search", params.search)
  if (params?.status) searchParams.set("status", params.status)
  if (params?.artist_id) searchParams.set("artist_id", params.artist_id)

  const { data, error, isLoading } = useSWR(`/api/tracks?${searchParams.toString()}`, fetcher)

  return {
    tracks: data?.data || [],
    total: data?.total || 0,
    totalPages: data?.totalPages || 0,
    isLoading,
    error,
    mutate: () => mutate(`/api/tracks?${searchParams.toString()}`),
  }
}

export function useTrack(id: string) {
  const { data, error, isLoading } = useSWR(id ? `/api/tracks/${id}` : null, fetcher)

  return {
    track: data,
    isLoading,
    error,
  }
}

// Artists
export function useArtists(params?: { page?: number; limit?: number; search?: string; verified?: string }) {
  const searchParams = new URLSearchParams()
  if (params?.page) searchParams.set("page", params.page.toString())
  if (params?.limit) searchParams.set("limit", params.limit.toString())
  if (params?.search) searchParams.set("search", params.search)
  if (params?.verified) searchParams.set("verified", params.verified)

  const { data, error, isLoading } = useSWR(`/api/artists?${searchParams.toString()}`, fetcher)

  return {
    artists: data?.data || [],
    total: data?.total || 0,
    totalPages: data?.totalPages || 0,
    isLoading,
    error,
    mutate: () => mutate(`/api/artists?${searchParams.toString()}`),
  }
}

export function useArtist(id: string) {
  const { data, error, isLoading } = useSWR(id ? `/api/artists/${id}` : null, fetcher)

  return {
    artist: data,
    isLoading,
    error,
  }
}

// Albums
export function useAlbums(params?: {
  page?: number
  limit?: number
  search?: string
  artist_id?: string
  status?: string
}) {
  const searchParams = new URLSearchParams()
  if (params?.page) searchParams.set("page", params.page.toString())
  if (params?.limit) searchParams.set("limit", params.limit.toString())
  if (params?.search) searchParams.set("search", params.search)
  if (params?.artist_id) searchParams.set("artist_id", params.artist_id)
  if (params?.status) searchParams.set("status", params.status)

  const { data, error, isLoading } = useSWR(`/api/albums?${searchParams.toString()}`, fetcher)

  return {
    albums: data?.data || [],
    total: data?.total || 0,
    totalPages: data?.totalPages || 0,
    isLoading,
    error,
    mutate: () => mutate(`/api/albums?${searchParams.toString()}`),
  }
}

export function useAlbum(id: string) {
  const { data, error, isLoading } = useSWR(id ? `/api/albums/${id}` : null, fetcher)

  return {
    album: data,
    isLoading,
    error,
  }
}

// Playlists
export function usePlaylists(params?: {
  page?: number
  limit?: number
  search?: string
  user_id?: string
  editorial?: string
}) {
  const searchParams = new URLSearchParams()
  if (params?.page) searchParams.set("page", params.page.toString())
  if (params?.limit) searchParams.set("limit", params.limit.toString())
  if (params?.search) searchParams.set("search", params.search)
  if (params?.user_id) searchParams.set("user_id", params.user_id)
  if (params?.editorial) searchParams.set("editorial", params.editorial)

  const { data, error, isLoading } = useSWR(`/api/playlists?${searchParams.toString()}`, fetcher)

  return {
    playlists: data?.data || [],
    total: data?.total || 0,
    totalPages: data?.totalPages || 0,
    isLoading,
    error,
    mutate: () => mutate(`/api/playlists?${searchParams.toString()}`),
  }
}

// Genres
export function useGenres() {
  const { data, error, isLoading } = useSWR("/api/genres", fetcher)

  return {
    genres: data || [],
    isLoading,
    error,
    mutate: () => mutate("/api/genres"),
  }
}

// Subscriptions
export function useSubscriptions(params?: { page?: number; limit?: number; status?: string; plan_id?: string }) {
  const searchParams = new URLSearchParams()
  if (params?.page) searchParams.set("page", params.page.toString())
  if (params?.limit) searchParams.set("limit", params.limit.toString())
  if (params?.status) searchParams.set("status", params.status)
  if (params?.plan_id) searchParams.set("plan_id", params.plan_id)

  const { data, error, isLoading } = useSWR(`/api/subscriptions?${searchParams.toString()}`, fetcher)

  return {
    subscriptions: data?.data || [],
    total: data?.total || 0,
    totalPages: data?.totalPages || 0,
    isLoading,
    error,
    mutate: () => mutate(`/api/subscriptions?${searchParams.toString()}`),
  }
}

// API helper functions for mutations
export const api = {
  // Users
  async createUser(data: Record<string, unknown>) {
    const res = await fetch("/api/users", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(data),
    })
    if (!res.ok) throw new Error("Erreur lors de la création")
    return res.json()
  },

  async updateUser(id: string, data: Record<string, unknown>) {
    const res = await fetch(`/api/users/${id}`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(data),
    })
    if (!res.ok) throw new Error("Erreur lors de la mise à jour")
    return res.json()
  },

  async deleteUser(id: string) {
    const res = await fetch(`/api/users/${id}`, { method: "DELETE" })
    if (!res.ok) throw new Error("Erreur lors de la suppression")
    return res.json()
  },

  // Tracks
  async createTrack(data: Record<string, unknown>) {
    const res = await fetch("/api/tracks", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(data),
    })
    if (!res.ok) throw new Error("Erreur lors de la création")
    return res.json()
  },

  async updateTrack(id: string, data: Record<string, unknown>) {
    const res = await fetch(`/api/tracks/${id}`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(data),
    })
    if (!res.ok) throw new Error("Erreur lors de la mise à jour")
    return res.json()
  },

  async deleteTrack(id: string) {
    const res = await fetch(`/api/tracks/${id}`, { method: "DELETE" })
    if (!res.ok) throw new Error("Erreur lors de la suppression")
    return res.json()
  },

  // Artists
  async createArtist(data: Record<string, unknown>) {
    const res = await fetch("/api/artists", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(data),
    })
    if (!res.ok) throw new Error("Erreur lors de la création")
    return res.json()
  },

  async updateArtist(id: string, data: Record<string, unknown>) {
    const res = await fetch(`/api/artists/${id}`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(data),
    })
    if (!res.ok) throw new Error("Erreur lors de la mise à jour")
    return res.json()
  },

  async deleteArtist(id: string) {
    const res = await fetch(`/api/artists/${id}`, { method: "DELETE" })
    if (!res.ok) throw new Error("Erreur lors de la suppression")
    return res.json()
  },

  // Albums
  async createAlbum(data: Record<string, unknown>) {
    const res = await fetch("/api/albums", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(data),
    })
    if (!res.ok) throw new Error("Erreur lors de la création")
    return res.json()
  },

  async updateAlbum(id: string, data: Record<string, unknown>) {
    const res = await fetch(`/api/albums/${id}`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(data),
    })
    if (!res.ok) throw new Error("Erreur lors de la mise à jour")
    return res.json()
  },

  async deleteAlbum(id: string) {
    const res = await fetch(`/api/albums/${id}`, { method: "DELETE" })
    if (!res.ok) throw new Error("Erreur lors de la suppression")
    return res.json()
  },

  // Playlists
  async createPlaylist(data: Record<string, unknown>) {
    const res = await fetch("/api/playlists", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(data),
    })
    if (!res.ok) throw new Error("Erreur lors de la création")
    return res.json()
  },

  // Genres
  async createGenre(data: Record<string, unknown>) {
    const res = await fetch("/api/genres", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(data),
    })
    if (!res.ok) throw new Error("Erreur lors de la création")
    return res.json()
  },

  // File upload
  async uploadFile(file: File, folder = "uploads") {
    const formData = new FormData()
    formData.append("file", file)
    formData.append("folder", folder)

    const res = await fetch("/api/upload", {
      method: "POST",
      body: formData,
    })
    if (!res.ok) throw new Error("Erreur lors du téléchargement")
    return res.json()
  },

  // Auth
  async login(email: string, password: string) {
    const res = await fetch("/api/auth/login", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ email, password }),
    })
    if (!res.ok) {
      const error = await res.json()
      throw new Error(error.error || "Erreur de connexion")
    }
    return res.json()
  },

  async signup(data: { email: string; password: string; name: string; role?: string }) {
    const res = await fetch("/api/auth/signup", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(data),
    })
    if (!res.ok) {
      const error = await res.json()
      throw new Error(error.error || "Erreur lors de l'inscription")
    }
    return res.json()
  },

  async logout() {
    await fetch("/api/auth/logout", { method: "POST" })
  },
}
