import { createContext, ReactNode, useContext, useEffect, useMemo, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { apiClient } from '../services/apiClient'
import { authService } from '../services/auth'

export type UserRole = 'admin' | 'owner' | 'employee' | 'delivery' | 'seller' | 'customer'

export interface AuthUser {
  name: string
  role: UserRole
  token: string
}

interface AuthContextValue {
  user: AuthUser | null
  loading: boolean
  login: (token: string, role: UserRole, name: string) => void
  logout: () => void
}

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

const AUTH_KEY = 'mp-auth-user'

export function AuthProvider({ children }: { children: ReactNode }) {
  const [user, setUser] = useState<AuthUser | null>(() => {
    const persisted = localStorage.getItem(AUTH_KEY)
    return persisted ? (JSON.parse(persisted) as AuthUser) : null
  })
  const [loading, setLoading] = useState(true)
  const navigate = useNavigate()

  useEffect(() => {
    setLoading(false)
  }, [])

  useEffect(() => {
    if (user) {
      localStorage.setItem(AUTH_KEY, JSON.stringify(user))
      apiClient.setToken(user.token)
    } else {
      localStorage.removeItem(AUTH_KEY)
      apiClient.setToken(null)
    }
  }, [user])

  const login = (token: string, role: UserRole, name: string) => {
    setUser({ token, role, name })

    // Redirect based on role
    switch (role) {
      case 'admin':
        navigate('/admin', { replace: true })
        break
      case 'owner':
      case 'seller':
        navigate('/dashboard', { replace: true })
        break
      case 'employee':
        navigate('/colaborador', { replace: true })
        break
      case 'delivery':
        navigate('/entregas', { replace: true })
        break
      default:
        navigate('/dashboard', { replace: true })
    }
  }

  const logout = () => {
    authService.logout().catch(() => undefined)
    setUser(null)
    navigate('/login', { replace: true })
  }

  const value = useMemo(
    () => ({
      user,
      loading,
      login,
      logout
    }),
    [user, loading]
  )

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

export const useAuth = () => {
  const ctx = useContext(AuthContext)
  if (!ctx) throw new Error('useAuth must be used within AuthProvider')
  return ctx
}
