import { createContext, useState, useEffect, ReactNode, useContext } from 'react'
import api, { authApi, characterApi, Account, Character } from '../services/api'

// ... (interface remains same) ...

export const useAuth = () => useContext(AuthContext)


interface AuthContextType {
  isAuthenticated: boolean
  loading: boolean
  account: Account | null
  characters: Character[]
  currentCharacter: Character | null
  needsCharacterCreation: boolean
  login: (email: string, password: string) => Promise<void>
  register: (email: string, password: string) => Promise<void>
  loginWithSteam: (steamId: string, steamName: string) => Promise<void>
  logout: () => void
  refreshCharacters: () => Promise<void>
  selectCharacter: (characterId: number) => Promise<void>
  createCharacter: (data: {
    name: string
    strength: number
    agility: number
    endurance: number
    intellect: number
    avatar_data?: any
  }) => Promise<Character>
  deleteCharacter: (characterId: number) => Promise<void>
}

export const AuthContext = createContext<AuthContextType>({
  isAuthenticated: false,
  loading: true,
  account: null,
  characters: [],
  currentCharacter: null,
  needsCharacterCreation: false,
  login: async () => { },
  register: async () => { },
  loginWithSteam: async () => { },
  logout: () => { },
  refreshCharacters: async () => { },
  selectCharacter: async () => { },
  createCharacter: async () => ({} as Character),
  deleteCharacter: async () => { },
})

export function AuthProvider({ children }: { children: ReactNode }) {
  const [isAuthenticated, setIsAuthenticated] = useState(false)
  const [loading, setLoading] = useState(true)
  const [account, setAccount] = useState<Account | null>(null)
  const [characters, setCharacters] = useState<Character[]>([])
  const [currentCharacter, setCurrentCharacter] = useState<Character | null>(null)
  const [needsCharacterCreation, setNeedsCharacterCreation] = useState(false)

  useEffect(() => {
    const token = localStorage.getItem('token')
    const storedCharacterId = localStorage.getItem('currentCharacterId')

    if (token) {
      api.defaults.headers.common['Authorization'] = `Bearer ${token}`
      initializeAuth(storedCharacterId ? parseInt(storedCharacterId) : null)
    } else {
      // Check if running in Electron with Steam
      tryAutoSteamLogin()
    }
  }, [])

  const tryAutoSteamLogin = async () => {
    try {
      // Check if we're in Electron
      if (typeof window !== 'undefined' && (window as any).electronAPI) {
        const steamAuth = await (window as any).electronAPI.getSteamAuth()

        if (steamAuth && steamAuth.available) {
          console.log('Steam detected, auto-logging in...')
          await loginWithSteam(steamAuth.steamId, steamAuth.steamName)
          return
        }
      }
    } catch (error) {
      console.log('Steam auto-login failed:', error)
    } finally {
      setLoading(false)
    }
  }

  const initializeAuth = async (characterId: number | null) => {
    try {
      // Try to fetch characters (this validates the token)
      const chars = await characterApi.list()
      setCharacters(chars)
      setIsAuthenticated(true)

      // If we have a stored character ID, try to set it as current
      if (characterId && chars.find(c => c.id === characterId)) {
        setCurrentCharacter(chars.find(c => c.id === characterId) || null)
      }

      // Check if we need character creation
      setNeedsCharacterCreation(chars.length === 0)
    } catch (error) {
      console.error('Failed to initialize auth:', error)
      localStorage.removeItem('token')
      localStorage.removeItem('currentCharacterId')
      delete api.defaults.headers.common['Authorization']
    } finally {
      setLoading(false)
    }
  }

  const login = async (email: string, password: string) => {
    const response = await authApi.login(email, password)
    const { access_token, account: acc, characters: chars } = response

    localStorage.setItem('token', access_token)
    api.defaults.headers.common['Authorization'] = `Bearer ${access_token}`

    setAccount(acc)
    setCharacters(chars)
    setIsAuthenticated(true)
    setNeedsCharacterCreation(chars.length === 0)
  }

  const register = async (email: string, password: string) => {
    const data = await authApi.register(email, password)

    localStorage.setItem('token', data.access_token)
    api.defaults.headers.common['Authorization'] = `Bearer ${data.access_token}`

    setAccount(data.account)
    setCharacters(data.characters)
    setIsAuthenticated(true)
    setNeedsCharacterCreation(data.needs_character_creation || data.characters.length === 0)
  }

  const loginWithSteam = async (steamId: string, steamName: string) => {
    const data = await authApi.steamLogin(steamId, steamName)

    localStorage.setItem('token', data.access_token)
    api.defaults.headers.common['Authorization'] = `Bearer ${data.access_token}`

    setAccount(data.account)
    setCharacters(data.characters)
    setIsAuthenticated(true)
    setNeedsCharacterCreation(data.needs_character_creation || data.characters.length === 0)
  }

  const logout = () => {
    localStorage.removeItem('token')
    localStorage.removeItem('currentCharacterId')
    delete api.defaults.headers.common['Authorization']
    setIsAuthenticated(false)
    setAccount(null)
    setCharacters([])
    setCurrentCharacter(null)
    setNeedsCharacterCreation(false)
  }

  const refreshCharacters = async () => {
    const chars = await characterApi.list()
    setCharacters(chars)
    setNeedsCharacterCreation(chars.length === 0)
  }

  const selectCharacter = async (characterId: number) => {
    const response = await characterApi.select(characterId)
    const { access_token, character } = response

    localStorage.setItem('token', access_token)
    localStorage.setItem('currentCharacterId', characterId.toString())
    api.defaults.headers.common['Authorization'] = `Bearer ${access_token}`

    setCurrentCharacter(character)
  }

  const createCharacter = async (data: {
    name: string
    strength: number
    agility: number
    endurance: number
    intellect: number
    avatar_data?: any
  }): Promise<Character> => {
    const character = await characterApi.create(data)
    await refreshCharacters()
    return character
  }

  const deleteCharacter = async (characterId: number) => {
    await characterApi.delete(characterId)
    await refreshCharacters()

    // If we deleted the current character, clear it
    if (currentCharacter?.id === characterId) {
      setCurrentCharacter(null)
      localStorage.removeItem('currentCharacterId')
    }
  }

  return (
    <AuthContext.Provider
      value={{
        isAuthenticated,
        loading,
        account,
        characters,
        currentCharacter,
        needsCharacterCreation,
        login,
        register,
        loginWithSteam,
        logout,
        refreshCharacters,
        selectCharacter,
        createCharacter,
        deleteCharacter,
      }}
    >
      {children}
    </AuthContext.Provider>
  )
}
