"use client"

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

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

export function useMailRoute() {
  const router = useRouter()
  const pathname = usePathname()
  const currentSearchParams = useSearchParams()
  const segments = useMemo(() => segmentsFromPathname(pathname), [pathname])
  const route = useMemo(() => parseMailSegments(segments), [segments])

  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)
      if (next.folderId === "search" && currentSearchParams.toString()) {
        url += `?${currentSearchParams.toString()}`
      }
      router.push(url, { scroll: false })
    },
    [router, route, currentSearchParams]
  )

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