'use client'

import { BookOpen, ClipboardList, GitCompare, Home, Trophy } 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'
import { useTranslations } from 'next-intl'

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; votingStartAt: Date | null; votingEndAt: Date | null }
    evaluation: { status: string } | null
  }>).filter((a) => {
    const isActive =
      a.round.status === 'ACTIVE' &&
      a.round.votingStartAt &&
      a.round.votingEndAt &&
      new Date(a.round.votingStartAt) <= now &&
      new Date(a.round.votingEndAt) >= 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 t = useTranslations('nav')
  const navigation: NavItem[] = [
    {
      name: t('dashboard'),
      href: '/jury',
      icon: Home,
    },
    {
      name: t('assignments'),
      href: '/jury/assignments',
      icon: ClipboardList,
    },
    {
      name: t('awards'),
      href: '/jury/awards',
      icon: Trophy,
    },
    {
      name: t('compare'),
      href: '/jury/compare',
      icon: GitCompare,
    },
    {
      name: t('learningHub'),
      href: '/jury/learning',
      icon: BookOpen,
    },
  ]

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