'use client'

import { usePathname, useRouter } from 'next/navigation'
import { useTransition } from 'react'
import { ChevronDown } from 'lucide-react'
import { toast } from 'sonner'
import { Badge } from '@/components/ui/badge'
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import { cn } from '@/lib/utils'
import { setActiveSprintAction } from '@/actions/active-sprint'
import type { SprintStatusApi } from '@/lib/task-status'

type SprintItem = { id: string; code: string; status: SprintStatusApi }

interface SprintSwitcherProps {
  productId: string
  sprints: SprintItem[]
  activeSprint: SprintItem | null
  buildingSprintIds: string[]
}

const SPRINT_STATUS_LABEL: Record<SprintStatusApi, string> = {
  open: 'Open',
  closed: 'Gesloten',
  archived: 'Gearchiveerd',
  failed: 'Mislukt',
}

const SPRINT_STATUS_BADGE: Record<SprintStatusApi, string> = {
  open: 'bg-status-in-progress text-foreground',
  closed: 'bg-status-done text-foreground',
  archived: 'bg-surface-container text-muted-foreground',
  failed: 'bg-status-failed text-foreground',
}

export function SprintSwitcher({
  productId,
  sprints,
  activeSprint,
  buildingSprintIds,
}: SprintSwitcherProps) {
  const pathname = usePathname()
  const router = useRouter()
  const [isPending, startTransition] = useTransition()
  const buildingSet = new Set(buildingSprintIds)

  function handleSwitchSprint(sprintId: string) {
    if (sprintId === activeSprint?.id) return
    startTransition(async () => {
      const result = await setActiveSprintAction(productId, sprintId)
      if (result?.error) {
        toast.error(typeof result.error === 'string' ? result.error : 'Wisselen mislukt')
        return
      }
      if (pathname.includes('/sprint')) {
        router.push(`/products/${productId}/sprint/${sprintId}`)
      } else {
        router.refresh()
      }
    })
  }

  if (sprints.length === 0) {
    return (
      <TooltipProvider>
        <Tooltip>
          <TooltipTrigger
            className="text-xs text-muted-foreground/50 px-2 cursor-not-allowed select-none"
            aria-disabled="true"
          >
            Geen sprints
          </TooltipTrigger>
          <TooltipContent>Maak een sprint aan vanuit de Product Backlog</TooltipContent>
        </Tooltip>
      </TooltipProvider>
    )
  }

  return (
    <DropdownMenu>
      <DropdownMenuTrigger
        disabled={isPending}
        className="flex items-center gap-1.5 text-xs text-muted-foreground hover:text-foreground transition-colors px-2 py-1 rounded-md hover:bg-surface-container focus:outline-none"
      >
        <span className="truncate max-w-[160px]">
          {activeSprint ? activeSprint.code : 'Selecteer sprint'}
        </span>
        {activeSprint && (
          <Badge
            className={cn(
              'text-[10px] px-1.5 py-0',
              buildingSet.has(activeSprint.id)
                ? 'bg-warning text-warning-foreground'
                : SPRINT_STATUS_BADGE[activeSprint.status],
            )}
          >
            {buildingSet.has(activeSprint.id) ? 'BUILDING' : SPRINT_STATUS_LABEL[activeSprint.status]}
          </Badge>
        )}
        <ChevronDown className="w-3 h-3 shrink-0 text-muted-foreground" />
      </DropdownMenuTrigger>
      <DropdownMenuContent align="start" className="w-64">
        {sprints.map(s => (
          <DropdownMenuItem
            key={s.id}
            onClick={() => handleSwitchSprint(s.id)}
            className={cn(
              'flex items-center justify-between gap-2',
              s.id === activeSprint?.id && 'bg-primary-container text-primary-container-foreground font-medium',
            )}
          >
            <span className="truncate">{s.code}</span>
            <Badge
              className={cn(
                'text-[10px] px-1.5 py-0 shrink-0',
                buildingSet.has(s.id)
                  ? 'bg-warning text-warning-foreground'
                  : SPRINT_STATUS_BADGE[s.status],
              )}
            >
              {buildingSet.has(s.id) ? 'BUILDING' : SPRINT_STATUS_LABEL[s.status]}
            </Badge>
          </DropdownMenuItem>
        ))}
      </DropdownMenuContent>
    </DropdownMenu>
  )
}
