'use client'

import { BookOpen, Home, Trophy, ClipboardList } from 'lucide-react'
import { RoleNav, type NavItem, type RoleNavUser } from '@/components/layouts/role-nav'
import { trpc } from '@/lib/trpc/client'
import { Badge } from '@/components/ui/badge'

interface JuryNavProps {
  user: RoleNavUser
}

function RemainingBadge() {
  const { data: assignments } = trpc.assignment.myAssignments.useQuery(
    {},
    { refetchInterval: 60000 }
  )

  if (!assignments) return null

  const now = new Date()
  const remaining = (assignments as Array<{
    round: { status: string; windowOpenAt: Date | null; windowCloseAt: Date | null } | null
    evaluation: { status: string } | null
  }>).filter((a) => {
    const isActive =
      a.round?.status === 'ROUND_ACTIVE' &&
      a.round.windowOpenAt &&
      a.round.windowCloseAt &&
      new Date(a.round.windowOpenAt) <= now &&
      new Date(a.round.windowCloseAt) >= now
    const isIncomplete = !a.evaluation || a.evaluation.status !== 'SUBMITTED'
    return isActive && isIncomplete
  }).length

  if (remaining === 0) return null

  return (
    <Badge variant="secondary" className="text-xs font-medium">
      {remaining} remaining
    </Badge>
  )
}

export function JuryNav({ user }: JuryNavProps) {
  const { data: myAwards } = trpc.specialAward.getMyAwards.useQuery(
    undefined,
    { refetchInterval: 60000 }
  )

  const navigation: NavItem[] = [
    {
      name: 'Dashboard',
      href: '/jury',
      icon: Home,
    },
    {
      name: 'Assignments',
      href: '/jury/competitions',
      icon: ClipboardList,
    },
    ...(myAwards && myAwards.length > 0
      ? [
          {
            name: 'Awards',
            href: '/jury/awards',
            icon: Trophy,
          },
        ]
      : []),
    {
      name: 'Learning Hub',
      href: '/jury/learning',
      icon: BookOpen,
    },
  ]

  return (
    <RoleNav
      navigation={navigation}
      roleName="Jury"
      user={user}
      basePath="/jury"
      statusBadge={<RemainingBadge />}
    />
  )
}
