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

export type UserRole = 'farmacia' | 'admin'

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 })
    navigate('/dashboard', { replace: true })
  }

  const logout = () => {
    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
}
