'use client'

/**
 * Next.js adapter for mizan/allauth.
 *
 * Usage:
 * ```tsx
 * // In layout.tsx (server component)
 * import { createDjangoSSRClient } from 'mizan/client'
 * import { getInitialAuth } from 'mizan/allauth'
 * import { NextAllauthContext } from 'mizan/allauth/nextjs'
 *
 * export default async function RootLayout({ children }) {
 *     const ssrClient = createDjangoSSRClient({ cookies: await cookies() })
 *     const hydration = await getInitialAuth(ssrClient)
 *
 *     return (
 *         <NextAllauthContext hydration={hydration}>
 *             {children}
 *         </NextAllauthContext>
 *     )
 * }
 * ```
 */

import { ReactNode } from 'react'
import { useRouter, usePathname, useSearchParams, useParams } from 'next/navigation'
import type { RouterAdapter } from './adapters/router'
import type { InitialAuth } from './hydration'
import { AllauthContext } from './contexts/AllauthContext'
import { AllauthConfig } from './config'
import { AuthClassNames } from './styles/types'

/**
 * Create a RouterAdapter from Next.js App Router hooks.
 */
export function useNextRouter(): RouterAdapter {
    const router = useRouter()
    const pathname = usePathname()
    const searchParams = useSearchParams()
    const params = useParams()

    return {
        push: (path: string) => router.push(path),
        replace: (path: string) => router.replace(path),
        pathname,
        searchParams: new URLSearchParams(searchParams.toString()),
        getParam: (name: string) => params[name] as string | string[] | undefined,
    }
}

export interface NextAllauthContextProps {
    children: ReactNode

    /** Optional initial auth state from getInitialAuth() - if not provided, fetches client-side */
    hydration?: InitialAuth

    /** Library configuration (basePath, routes) */
    allauthConfig?: Partial<AllauthConfig>

    /** CSS class names for styling components */
    classNames?: AuthClassNames
}

/**
 * Next.js-specific AllauthContext that handles the router automatically.
 *
 * IMPORTANT: Must be wrapped by DjangoContext which provides user data.
 *
 * ```tsx
 * <DjangoContext client={client} hydration={djangoHydration}>
 *   <NextAllauthContext hydration={allauthHydration}>
 *     {children}
 *   </NextAllauthContext>
 * </DjangoContext>
 * ```
 */
export function NextAllauthContext({
    children,
    hydration,
    allauthConfig,
    classNames,
}: NextAllauthContextProps) {
    const router = useNextRouter()

    return (
        <AllauthContext
            hydration={hydration}
            router={router}
            allauthConfig={allauthConfig}
            classNames={classNames}
        >
            {children}
        </AllauthContext>
    )
}
