"use client"

import React, { createContext, useContext, useState, useEffect, ReactNode } from "react"
import { logout as apiLogout } from "@/components/apis/authApiClients"
import { safeLocalStorage } from "@/lib/utils"

interface User {
  id: string
  name: string
  email: string
  avatar?: string
}

interface AuthContextType {
  user: User | null
  isAuthenticated: boolean
  isLoading: boolean
  login: (email: string, password: string) => Promise<boolean>
  signup: (name: string, email: string, password: string) => Promise<boolean>
  logout: () => Promise<void>
  setUserFromApi: (apiUser: any) => void
}

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

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

interface AuthProviderProps {
  children: ReactNode
}

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

  // Check if user is logged in on mount
  useEffect(() => {
    const checkAuth = () => {
      // Check localStorage for user data
      const userData = safeLocalStorage.getItem("codenuk_user")
      if (userData) {
        try {
          const user = JSON.parse(userData)
          // Ensure user object has all required properties with fallbacks
          const validatedUser: User = {
            id: user.id || "1",
            name: user.name || user.email?.split("@")[0] || "User",
            email: user.email || "user@example.com",
            avatar: user.avatar || "/avatars/01.png"
          }
          setUser(validatedUser)
        } catch (error) {
          console.error("Error parsing user data:", error)
          safeLocalStorage.removeItem("codenuk_user")
        }
      }
      setIsLoading(false)
    }

    checkAuth()
  }, [])

  // Allow setting user right after successful API login
  const setUserFromApi = (apiUser: any) => {
    const validatedUser: User = {
      id: (apiUser.id || apiUser.user_id || "1").toString(),
      name:
        apiUser.name ||
        [apiUser.first_name, apiUser.last_name].filter(Boolean).join(" ") ||
        apiUser.username ||
        (apiUser.email ? apiUser.email.split("@")[0] : "User"),
      email: apiUser.email || "user@example.com",
      avatar: apiUser.avatar || "/avatars/01.png",
    }
    setUser(validatedUser)
    safeLocalStorage.setItem("codenuk_user", JSON.stringify(validatedUser))
  }

  const login = async (email: string, password: string): Promise<boolean> => {
    try {
      setIsLoading(true)
      
      // Simulate API call
      await new Promise(resolve => setTimeout(resolve, 1000))
      
      // For demo purposes, accept any email/password combination
      if (email && password) {
        const user: User = {
          id: "1",
          name: email.split("@")[0], // Use email prefix as name
          email: email,
          avatar: "/avatars/01.png"
        }
        
        setUser(user)
        safeLocalStorage.setItem("codenuk_user", JSON.stringify(user))
        return true
      }
      
      return false
    } catch (error) {
      console.error("Login error:", error)
      return false
    } finally {
      setIsLoading(false)
    }
  }

  const signup = async (name: string, email: string, password: string): Promise<boolean> => {
    try {
      setIsLoading(true)
      
      // Simulate API call
      await new Promise(resolve => setTimeout(resolve, 1000))
      
      // For demo purposes, create user if all fields are provided
      if (name && email && password) {
        const user: User = {
          id: "1",
          name: name,
          email: email,
          avatar: "/avatars/01.png"
        }
        
        setUser(user)
        safeLocalStorage.setItem("codenuk_user", JSON.stringify(user))
        return true
      }
      
      return false
    } catch (error) {
      console.error("Signup error:", error)
      return false
    } finally {
      setIsLoading(false)
    }
  }

  const logout = async (): Promise<void> => {
    try {
      // Call the API logout function which handles backend call, token clearing, and redirect
      await apiLogout();
    } catch (error) {
      console.error("Logout error:", error);
      // Even if there's an error, clear local state
      setUser(null);
      safeLocalStorage.removeItem("codenuk_user");
    }
  }

  const value: AuthContextType = {
    user,
    isAuthenticated: !!user,
    isLoading,
    login,
    signup,
    logout,
    setUserFromApi
  }

  return (
    <AuthContext.Provider value={value}>
      {children}
    </AuthContext.Provider>
  )
}
