'use client'

// import { useRouter } from 'next/router'
import { parseCookies, setCookie } from 'nookies'
import { createContext, useEffect, useState } from 'react'

import { getAccountsId } from '@/api/accounts'
import { login } from '@/api/login'
import { api } from '@/lib/axios'
import { useRouter } from 'next/navigation'

type User = {
  id: string
  name: string
  email: string
} | null

type SignInData = {
  email: string
  password: string
}

type AuthContextType = {
  isAuthenticated: boolean
  user: User
  signIn: (data: SignInData) => Promise<void>
}

export const AuthContext = createContext({} as AuthContextType)

export function AuthProvider({ children }) {
  const [user, setUser] = useState<User | null>(null)
  const router = useRouter()

  const isAuthenticated = !!user

  useEffect(() => {
    const { 'sevenpro-token': token } = parseCookies()
    const { 'sevenpro-user': userCookie } = parseCookies()

    if (token && userCookie) {
      const { id } = JSON.parse(userCookie)
      getAccountsId(id).then((response) => {
        setUser(response.data)
      })
    }
  }, [])

  async function signIn({ email, password }: SignInData) {
    const { data } = await login({
      email,
      password,
    })

    const token = data.access_token
    const user = data.user

    setCookie(undefined, 'sevenpro-token', token, {
      maxAge: 60 * 60 * 1, // 1 hour
    })
    setCookie(undefined, 'sevenpro-user', JSON.stringify(user), {
      maxAge: 60 * 60 * 1, // 1 hour
    })

    api.defaults.headers.Authorization = `Bearer ${token}`

    setUser(user)

    router.push('/admin')
  }

  return (
    <AuthContext.Provider value={{ user, isAuthenticated, signIn }}>
      {children}
    </AuthContext.Provider>
  )
}
