"use client"

import { useCallback, useMemo } from "react"
import { useRouter, usePathname, useSearchParams } from "next/navigation"
import {
  parseMailSegments,
  buildMailPath,
  type MailRouteState,
} from "@/lib/mail-url"
import { useMailRouteRoot } from "@/lib/demo/demo-mail-context"

function segmentsFromPathname(
  pathname: string | null,
  routeRoot: string
): string[] | undefined {
  const base = `/${routeRoot}`
  if (!pathname?.startsWith(base)) return undefined
  const rest = pathname.slice(base.length).replace(/^\//, "")
  if (!rest) return []
  return rest.split("/").filter(Boolean)
}

export function useMailRoute() {
  const router = useRouter()
  const pathname = usePathname()
  const routeRoot = useMailRouteRoot()
  const currentSearchParams = useSearchParams()
  const segments = useMemo(
    () => segmentsFromPathname(pathname, routeRoot),
    [pathname, routeRoot]
  )
  const route = useMemo(() => {
    const parsed = parseMailSegments(segments)
    const queryMailId = currentSearchParams.get("message")?.trim()
    if (!parsed.mailId && queryMailId) {
      return { ...parsed, mailId: queryMailId }
    }
    return parsed
  }, [segments, currentSearchParams])

  const navigateRoute = useCallback(
    (patch: Partial<MailRouteState>) => {
      const next: MailRouteState = {
        folderId: patch.folderId ?? route.folderId,
        inboxTab:
          patch.inboxTab !== undefined && patch.inboxTab !== null
            ? patch.inboxTab
            : route.inboxTab,
        page: patch.page !== undefined ? patch.page : route.page,
        mailId: patch.mailId !== undefined ? patch.mailId : route.mailId,
      }
      let url = buildMailPath(next, routeRoot)
      if (next.folderId === "search") {
        const qs = new URLSearchParams(currentSearchParams.toString())
        qs.delete("message")
        const q = qs.toString()
        if (q) url += `?${q}`
      }
      router.push(url, { scroll: false })
    },
    [router, route, currentSearchParams, routeRoot]
  )

  return {
    route,
    navigateRoute,
    pathname,
    searchParams: currentSearchParams,
    routeRoot,
  }
}
