"use client"

import Link from "next/link"
import { usePathname, useSearchParams } from "next/navigation"

import { useT } from "@/components/locale-provider"
import { cn } from "@/lib/utils"
import { VIEWS, type View } from "@/lib/task-views"

import type { MessageKey } from "@/lib/i18n/messages"

const WORDS: Record<View, MessageKey> = {
  day: "tasks.today",
  week: "tasks.thisWeek",
  month: "tasks.thisMonth",
}

/**
 * Three links and not three buttons, because the view is in the url. A person
 * who works from the week can keep the week, and somebody asking a colleague
 * "what have you got this month" can send them the month.
 *
 * `Link` rather than a router push so the browser's own back button walks back
 * through the views, which is what somebody expects after clicking three of
 * them looking for a task.
 */
export function ViewSwitch({ current }: { current: View }) {
  const pathname = usePathname()
  const params = useSearchParams()
  const t = useT()

  return (
    <nav aria-label={t("tasks.whichDays")} className="flex gap-1">
      {VIEWS.map((view) => {
        const next = new URLSearchParams(params)
        next.set("view", view)
        const active = view === current
        return (
          <Link
            key={view}
            href={`${pathname}?${next}`}
            aria-current={active ? "page" : undefined}
            className={cn(
              "rounded-lg px-3 py-2 text-sm font-medium transition-colors",
              "focus-visible:ring-3 focus-visible:ring-ring/50 focus-visible:outline-none",
              active
                ? "bg-primary text-primary-foreground"
                : "text-foreground/80 hover:bg-muted",
            )}
          >
            {t(WORDS[view])}
          </Link>
        )
      })}
    </nav>
  )
}
