'use client'

import { BookOpen, Home, Trophy, ClipboardList, FileText } 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 { data: flags } = trpc.settings.getFeatureFlags.useQuery()
  // Only Grand-Final jury members (and admins) can open the finalist documents
  // review — hide the link from everyone else so they don't hit a dead "No access" page.
  const { data: canReviewFinals } = trpc.finalist.canReviewDocuments.useQuery()

  const useExternal = flags?.learningHubExternal && flags.learningHubExternalUrl

  const navigation: NavItem[] = [
    {
      name: 'Dashboard',
      href: '/jury',
      icon: Home,
    },
    {
      name: 'Assignments',
      href: '/jury/competitions',
      icon: ClipboardList,
    },
    ...(canReviewFinals
      ? [
          {
            name: 'Finalist Documents',
            href: '/jury/finals-documents',
            icon: FileText,
          },
        ]
      : []),
    ...(myAwards && myAwards.length > 0
      ? [
          {
            name: 'Awards',
            href: '/jury/awards',
            icon: Trophy,
          },
        ]
      : []),
    {
      name: 'Learning Hub',
      href: useExternal ? flags.learningHubExternalUrl : '/jury/learning',
      icon: BookOpen,
      external: !!useExternal,
    },
  ]

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