import { createContext, useContext, useEffect, useState, type ReactNode } from 'react'
import {
  getUser,
  handleAuthCallback,
  oauthLogin,
  onAuthChange,
  updateUser,
  type CallbackResult,
  type User,
} from '@netlify/identity'
import { toast } from 'sonner'
import { recordSignIn } from '@/lib/notifications.functions'
import { recordAccountChange } from '@/lib/settings.functions'

type IdentityState = {
  user: User | null
  ready: boolean
  error: string | null
  callback: CallbackResult | null
  clearCallback: () => void
}

const IdentityContext = createContext<IdentityState | null>(null)

const CALLBACK_KEYS = ['confirmation_token', 'recovery_token', 'invite_token', 'email_change_token', 'access_token']

// Remembers, across the redirect to Google, that the visitor chose Google,
// (from Settings) which signed-in account they meant to connect it to, and
// (from Buy credit) which page to return to afterwards.
const GOOGLE_INTENT_KEY = 'akc:google-intent'

type GoogleIntent = { connectTo: string | null; next?: string | null }

// Only same-site paths, so a crafted link can't bounce visitors elsewhere.
export function safeReturnPath(path: unknown): string | null {
  if (typeof path !== 'string' || !path.startsWith('/') || path.startsWith('//') || path.includes('\\')) return null
  return path
}

export function startGoogleSignIn(connectTo?: string, next?: string) {
  try {
    const intent: GoogleIntent = { connectTo: connectTo ?? null, next: safeReturnPath(next) }
    localStorage.setItem(GOOGLE_INTENT_KEY, JSON.stringify(intent))
  } catch {
    // Private browsing can block storage. Google sign-in still works.
  }
  oauthLogin('google')
}

function takeGoogleIntent(): GoogleIntent | null {
  try {
    const raw = localStorage.getItem(GOOGLE_INTENT_KEY)
    localStorage.removeItem(GOOGLE_INTENT_KEY)
    return raw ? JSON.parse(raw) : null
  } catch {
    return null
  }
}

// Returns the page the visitor should continue on, if they asked for one.
async function afterGoogleSignIn(user: User): Promise<string | null> {
  const intent = takeGoogleIntent()
  if (!intent) return null
  if (intent.connectTo && intent.connectTo !== user.id) {
    toast.error('That Google account uses a different email, so it opened a separate account.', {
      description: 'Sign out, then sign in with your usual email. Google only connects when the email addresses match.',
      duration: 12000,
    })
    return null
  }
  if (!user.userMetadata?.google_connected) {
    await updateUser({ data: { google_connected: true } }).catch(() => undefined)
    if (intent.connectTo) {
      await recordAccountChange({ data: { change: 'google' } }).catch(() => undefined)
      toast.success('Google sign-in connected.')
    }
  }
  return intent.connectTo ? null : safeReturnPath(intent.next)
}

export function IdentityProvider({ children }: { children: ReactNode }) {
  const [state, setState] = useState<Omit<IdentityState, 'clearCallback'>>({
    user: null,
    ready: false,
    error: null,
    callback: null,
  })

  useEffect(() => {
    let active = true
    const unsubscribe = onAuthChange((_event, user) => {
      if (active) setState((previous) => ({ ...previous, user }))
    })
    async function initialize() {
      try {
        const parameters = new URLSearchParams(window.location.hash.slice(1))
        const hasCallback = CALLBACK_KEYS.some((name) => parameters.has(name))
        const callback = hasCallback ? await handleAuthCallback() : null
        // Google/GitHub sign-ins and email confirmations log the user in here.
        if (callback && (callback.type === 'oauth' || callback.type === 'confirmation') && callback.user) {
          await recordSignIn().catch(() => undefined)
        }
        if (callback?.type === 'oauth' && callback.user) {
          const next = await afterGoogleSignIn(callback.user)
          // Google always returns to the home page. A full load lets the
          // server render the next page (e.g. Buy credit) as signed in.
          if (next && next !== window.location.pathname + window.location.search) {
            window.location.replace(next)
            return
          }
        }
        if (callback?.type === 'email_change' && callback.user) {
          await recordAccountChange({ data: { change: 'email' } }).catch(() => undefined)
        }
        const user = await getUser()
        if (active) setState({ user, ready: true, error: null, callback })
      } catch {
        if (active)
          setState({ user: null, ready: true, error: 'Sign-in could not be initialized.', callback: null })
      }
    }
    void initialize()
    return () => {
      active = false
      unsubscribe()
    }
  }, [])

  const value: IdentityState = {
    ...state,
    clearCallback: () => setState((previous) => ({ ...previous, callback: null })),
  }
  return <IdentityContext.Provider value={value}>{children}</IdentityContext.Provider>
}

export function useIdentity() {
  const state = useContext(IdentityContext)
  if (!state) throw new Error('IdentityProvider is required')
  return state
}
