"use client"

import { createContext, useContext, useState, useCallback, useEffect, type ReactNode } from "react"
import { preCacheForOffline } from "@/lib/offline-fetch"

export type UserRole = "user" | "artist" | "admin"

export interface AuthUser {
  id: string
  email: string
  name: string
  avatar: string
  role: UserRole
  isPremium: boolean
  artistId?: string
  subscription?: {
    plan: "free" | "premium" | "family" | "student"
    startDate: string
    endDate?: string
    autoRenew: boolean
  }
  artistProfile?: {
    stageName: string
    verified: boolean
    monthlyListeners: number
    totalStreams: number
  }
  createdAt: string
}

interface AuthContextType {
  user: AuthUser | null
  isAuthenticated: boolean
  isLoading: boolean
  login: (email: string, password: string) => Promise<{ success: boolean; error?: string }>
  signup: (data: SignupData) => Promise<{ success: boolean; error?: string }>
  logout: () => void
  updateProfile: (data: Partial<AuthUser>) => void
}

interface SignupData {
  email: string
  password: string
  name: string
  role?: UserRole
  artistName?: string
}

const AuthContext = createContext<AuthContextType | undefined>(undefined)

export function AuthProvider({ children }: { children: ReactNode }) {
  const [user, setUser] = useState<AuthUser | null>(null)
  const [isLoading, setIsLoading] = useState(true)

  useEffect(() => {
    const savedUser = localStorage.getItem("auth_user")
    const savedToken = localStorage.getItem("auth_token")

    console.log("[v0] AuthProvider init - Checking localStorage:", {
      hasUser: !!savedUser,
      hasToken: !!savedToken,
    })

    if (savedUser && savedToken) {
      try {
        const parsedUser = JSON.parse(savedUser)
        console.log("[v0] AuthProvider - Restored user from localStorage:", {
          email: parsedUser.email,
          role: parsedUser.role,
          id: parsedUser.id,
        })
        setUser(parsedUser)
        
        // Pre-cache data for offline use when session is restored
        preCacheForOffline(parsedUser.id).catch(console.error)
      } catch (error) {
        console.error("[v0] AuthProvider - Failed to parse saved user:", error)
        localStorage.removeItem("auth_user")
        localStorage.removeItem("auth_token")
      }
    } else {
      console.log("[v0] AuthProvider - No saved session found")
    }
    setIsLoading(false)
  }, [])

  const login = useCallback(async (email: string, password: string) => {
    setIsLoading(true)
    console.log("[v0] Login attempt for:", email)

    try {
      const res = await fetch("/api/auth/login", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email, password }),
      })

      const data = await res.json()
      console.log("[v0] Login API response:", {
        ok: res.ok,
        status: res.status,
        hasUser: !!data.user,
        userRole: data.user?.role,
        userEmail: data.user?.email,
      })

      if (!res.ok) {
        setIsLoading(false)
        return { success: false, error: data.error || "Erreur de connexion" }
      }

      const authUser: AuthUser = {
        id: data.user.id,
        email: data.user.email,
        name: data.user.name,
        avatar: data.user.avatar_url || "/diverse-woman-avatar.png",
        role: data.user.role as UserRole,
        isPremium: data.user.subscription_type !== "free",
        artistId: data.user.artist?.id,
        subscription: {
          plan: data.user.subscription_type || "free",
          startDate: new Date().toISOString().split("T")[0],
          autoRenew: false,
        },
        artistProfile: data.user.artist
          ? {
              stageName: data.user.artist.name,
              verified: data.user.artist.is_verified,
              monthlyListeners: 0,
              totalStreams: 0,
            }
          : undefined,
        createdAt: new Date().toISOString().split("T")[0],
      }

      console.log("[v0] Created authUser object:", {
        id: authUser.id,
        email: authUser.email,
        role: authUser.role,
        name: authUser.name,
      })

      setUser(authUser)
      localStorage.setItem("auth_user", JSON.stringify(authUser))
      localStorage.setItem("auth_token", data.token)

      console.log("[v0] Login successful - User saved to state and localStorage")
      
      // Pre-cache data for offline use
      preCacheForOffline(authUser.id).catch(console.error)
      
      setIsLoading(false)
      return { success: true }
    } catch (error) {
      console.error("[v0] Login error:", error)
      setIsLoading(false)
      return { success: false, error: "Erreur de connexion au serveur" }
    }
  }, [])

  const signup = useCallback(async (data: SignupData) => {
    setIsLoading(true)

    try {
      const res = await fetch("/api/auth/signup", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          email: data.email,
          password: data.password,
          name: data.name,
          role: data.role || "user",
        }),
      })

      const responseData = await res.json()

      if (!res.ok) {
        setIsLoading(false)
        return { success: false, error: responseData.error || "Erreur lors de l'inscription" }
      }

      const authUser: AuthUser = {
        id: responseData.user.id,
        email: responseData.user.email,
        name: responseData.user.name,
        avatar: responseData.user.avatar_url || "/diverse-woman-avatar.png",
        role: responseData.user.role as UserRole,
        isPremium: false,
        artistId: responseData.user.artist?.id,
        subscription: {
          plan: "free",
          startDate: new Date().toISOString().split("T")[0],
          autoRenew: false,
        },
        artistProfile: responseData.user.artist
          ? {
              stageName: responseData.user.artist.name,
              verified: false,
              monthlyListeners: 0,
              totalStreams: 0,
            }
          : undefined,
        createdAt: new Date().toISOString().split("T")[0],
      }

      setUser(authUser)
      localStorage.setItem("auth_user", JSON.stringify(authUser))
      localStorage.setItem("auth_token", responseData.token)
      setIsLoading(false)
      return { success: true }
    } catch (error) {
      console.error("Signup error:", error)
      setIsLoading(false)
      return { success: false, error: "Erreur de connexion au serveur" }
    }
  }, [])

  const logout = useCallback(() => {
    console.log("[v0] Logout - Clearing auth state")
    setUser(null)
    localStorage.removeItem("auth_user")
    localStorage.removeItem("auth_token")
  }, [])

  const updateProfile = useCallback((data: Partial<AuthUser>) => {
    setUser((prev) => {
      if (!prev) return null
      const updated = { ...prev, ...data }
      localStorage.setItem("auth_user", JSON.stringify(updated))
      console.log("[v0] Profile updated:", {
        email: updated.email,
        role: updated.role,
      })
      return updated
    })
  }, [])

  return (
    <AuthContext.Provider
      value={{
        user,
        isAuthenticated: !!user,
        isLoading,
        login,
        signup,
        logout,
        updateProfile,
      }}
    >
      {children}
    </AuthContext.Provider>
  )
}

export function useAuth() {
  const context = useContext(AuthContext)
  if (context === undefined) {
    throw new Error("useAuth must be used within an AuthProvider")
  }
  return context
}
