'use client'

import { useState, useEffect, useCallback } from 'react'
import Link from 'next/link'
import { useSearchParams, usePathname } from 'next/navigation'
import { trpc } from '@/lib/trpc/client'
import { toast } from 'sonner'
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Skeleton } from '@/components/ui/skeleton'
import { Progress } from '@/components/ui/progress'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import {
  Plus,
  MoreHorizontal,
  ClipboardList,
  Bot,
  Eye,
  Pencil,
  FileUp,
  Users,
  Search,
  Trash2,
  Loader2,
  Tags,
  Clock,
  CheckCircle2,
  AlertCircle,
  Layers,
  FolderOpen,
  X,
  AlertTriangle,
  ArrowRightCircle,
  LayoutGrid,
  LayoutList,
} from 'lucide-react'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { Checkbox } from '@/components/ui/checkbox'
import { Label } from '@/components/ui/label'
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from '@/components/ui/tooltip'
import { truncate } from '@/lib/utils'
import { ProjectLogo } from '@/components/shared/project-logo'
import { StatusBadge } from '@/components/shared/status-badge'
import { Pagination } from '@/components/shared/pagination'
import { getCountryName, getCountryFlag, normalizeCountryToCode } from '@/lib/countries'
import { CountryFlagImg } from '@/components/ui/country-select'
import {
  ProjectFiltersBar,
  type ProjectFilters,
  type FilterOptions,
} from './project-filters'
import { AnimatedCard } from '@/components/shared/animated-container'

const statusColors: Record<
  string,
  'default' | 'success' | 'secondary' | 'destructive' | 'warning'
> = {
  SUBMITTED: 'secondary',
  ELIGIBLE: 'default',
  ASSIGNED: 'default',
  SEMIFINALIST: 'success',
  FINALIST: 'success',
  WINNER: 'success',
  REJECTED: 'destructive',
  WITHDRAWN: 'secondary',
}

function parseFiltersFromParams(
  searchParams: URLSearchParams
): ProjectFilters & { page: number; perPage: number } {
  return {
    search: searchParams.get('q') || '',
    statuses: searchParams.get('status')
      ? searchParams.get('status')!.split(',')
      : [],
    roundId: searchParams.get('round') || '',
    competitionCategory: searchParams.get('category') || '',
    oceanIssue: searchParams.get('issue') || '',
    country: searchParams.get('country') || '',
    wantsMentorship:
      searchParams.get('mentorship') === 'true'
        ? true
        : searchParams.get('mentorship') === 'false'
          ? false
          : undefined,
    hasFiles:
      searchParams.get('hasFiles') === 'true'
        ? true
        : searchParams.get('hasFiles') === 'false'
          ? false
          : undefined,
    hasAssignments:
      searchParams.get('hasAssign') === 'true'
        ? true
        : searchParams.get('hasAssign') === 'false'
          ? false
          : undefined,
    page: parseInt(searchParams.get('page') || '1', 10),
    perPage: parseInt(searchParams.get('pp') || '20', 10),
  }
}

function filtersToParams(
  filters: ProjectFilters & { page: number; perPage: number }
): URLSearchParams {
  const params = new URLSearchParams()
  if (filters.search) params.set('q', filters.search)
  if (filters.statuses.length > 0)
    params.set('status', filters.statuses.join(','))
  if (filters.roundId) params.set('round', filters.roundId)
  if (filters.competitionCategory)
    params.set('category', filters.competitionCategory)
  if (filters.oceanIssue) params.set('issue', filters.oceanIssue)
  if (filters.country) params.set('country', filters.country)
  if (filters.wantsMentorship !== undefined)
    params.set('mentorship', String(filters.wantsMentorship))
  if (filters.hasFiles !== undefined)
    params.set('hasFiles', String(filters.hasFiles))
  if (filters.hasAssignments !== undefined)
    params.set('hasAssign', String(filters.hasAssignments))
  if (filters.page > 1) params.set('page', String(filters.page))
  if (filters.perPage !== 20) params.set('pp', String(filters.perPage))
  return params
}

export default function ProjectsPage() {

  const pathname = usePathname()
  const searchParams = useSearchParams()

  const parsed = parseFiltersFromParams(searchParams)
  const [filters, setFilters] = useState<ProjectFilters>({
    search: parsed.search,
    statuses: parsed.statuses,
    roundId: parsed.roundId,
    competitionCategory: parsed.competitionCategory,
    oceanIssue: parsed.oceanIssue,
    country: parsed.country,
    wantsMentorship: parsed.wantsMentorship,
    hasFiles: parsed.hasFiles,
    hasAssignments: parsed.hasAssignments,
  })
  const [page, setPage] = useState(parsed.page)
  const [perPage, setPerPage] = useState(parsed.perPage || 20)
  const [searchInput, setSearchInput] = useState(parsed.search)
  const [viewMode, setViewMode] = useState<'table' | 'card'>('table')

  // Fetch display settings
  const { data: displaySettings } = trpc.settings.getMultiple.useQuery({
    keys: ['display_project_names_uppercase'],
  })
  const uppercaseNames = displaySettings?.find(
    (s: { key: string; value: string }) => s.key === 'display_project_names_uppercase'
  )?.value !== 'false'

  // Debounced search
  useEffect(() => {
    const timer = setTimeout(() => {
      if (searchInput !== filters.search) {
        setFilters((f) => ({ ...f, search: searchInput }))
        setPage(1)
      }
    }, 300)
    return () => clearTimeout(timer)
  }, [searchInput, filters.search])

  // Sync URL
  const syncUrl = useCallback(
    (f: ProjectFilters, p: number, pp: number) => {
      const params = filtersToParams({ ...f, page: p, perPage: pp })
      const qs = params.toString()
      window.history.replaceState(null, '', qs ? `${pathname}?${qs}` : pathname)
    },
    [pathname]
  )

  useEffect(() => {
    syncUrl(filters, page, perPage)
  }, [filters, page, perPage, syncUrl])

  const handlePerPageChange = (newPerPage: number) => {
    setPerPage(newPerPage)
    setPage(1)
  }

  // Reset page when filters change
  const handleFiltersChange = (newFilters: ProjectFilters) => {
    setFilters(newFilters)
    setPage(1)
  }

  // Build tRPC query input
  const queryInput = {
    search: filters.search || undefined,
    statuses:
      filters.statuses.length > 0
        ? (filters.statuses as Array<
            | 'SUBMITTED'
            | 'ELIGIBLE'
            | 'ASSIGNED'
            | 'SEMIFINALIST'
            | 'FINALIST'
            | 'REJECTED'
          >)
        : undefined,
    roundId: filters.roundId || undefined,
    competitionCategory:
      (filters.competitionCategory as 'STARTUP' | 'BUSINESS_CONCEPT') ||
      undefined,
    oceanIssue: filters.oceanIssue
      ? (filters.oceanIssue as
          | 'POLLUTION_REDUCTION'
          | 'CLIMATE_MITIGATION'
          | 'TECHNOLOGY_INNOVATION'
          | 'SUSTAINABLE_SHIPPING'
          | 'BLUE_CARBON'
          | 'HABITAT_RESTORATION'
          | 'COMMUNITY_CAPACITY'
          | 'SUSTAINABLE_FISHING'
          | 'CONSUMER_AWARENESS'
          | 'OCEAN_ACIDIFICATION'
          | 'OTHER')
      : undefined,
    country: filters.country || undefined,
    wantsMentorship: filters.wantsMentorship,
    hasFiles: filters.hasFiles,
    hasAssignments: filters.hasAssignments,
    page,
    perPage,
  }

  const utils = trpc.useUtils()
  const { data, isLoading } = trpc.project.list.useQuery(queryInput)
  const { data: filterOptions } = trpc.project.getFilterOptions.useQuery()

  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false)
  const [projectToDelete, setProjectToDelete] = useState<{ id: string; title: string } | null>(null)
  // Assign to round dialog state
  const [assignDialogOpen, setAssignDialogOpen] = useState(false)
  const [projectToAssign, setProjectToAssign] = useState<{ id: string; title: string } | null>(null)
  const [assignRoundId, setAssignRoundId] = useState('')

  const [aiTagDialogOpen, setAiTagDialogOpen] = useState(false)
  const [taggingScope, setTaggingScope] = useState<'round' | 'program'>('round')
  const [selectedRoundForTagging, setSelectedRoundForTagging] = useState<string>('')
  const [selectedProgramForTagging, setSelectedProgramForTagging] = useState<string>('')
  const [activeTaggingJobId, setActiveTaggingJobId] = useState<string | null>(null)

  // Fetch programs and rounds for the AI tagging dialog
  const { data: programs } = trpc.program.list.useQuery()

  // Start tagging job mutation
  const startTaggingJob = trpc.tag.startTaggingJob.useMutation({
    onSuccess: (result) => {
      setActiveTaggingJobId(result.jobId)
      toast.info('AI tagging job started. Progress will update automatically.')
    },
    onError: (error) => {
      toast.error(error.message || 'Failed to start tagging job')
    },
  })

  // Poll for job status when job is active
  const { data: jobStatus } = trpc.tag.getTaggingJobStatus.useQuery(
    { jobId: activeTaggingJobId! },
    {
      enabled: !!activeTaggingJobId,
      refetchInterval: (query) => {
        const status = query.state.data?.status
        // Stop polling when job is done
        if (status === 'COMPLETED' || status === 'FAILED') {
          return false
        }
        return 1500 // Poll every 1.5 seconds
      },
    }
  )

  // Handle job completion
  useEffect(() => {
    if (jobStatus?.status === 'COMPLETED') {
      toast.success(
        `AI Tagging complete: ${jobStatus.taggedCount} tagged, ${jobStatus.skippedCount} already tagged, ${jobStatus.failedCount} failed`
      )
      utils.project.list.invalidate()
    } else if (jobStatus?.status === 'FAILED') {
      toast.error(`AI Tagging failed: ${jobStatus.errorMessage || 'Unknown error'}`)
    }
  }, [jobStatus?.status, jobStatus?.taggedCount, jobStatus?.skippedCount, jobStatus?.failedCount, jobStatus?.errorMessage, utils.project.list])

  const taggingInProgress = startTaggingJob.isPending ||
    (jobStatus?.status === 'PENDING' || jobStatus?.status === 'RUNNING')

  const taggingResult = jobStatus?.status === 'COMPLETED' || jobStatus?.status === 'FAILED'
    ? {
        processed: jobStatus.taggedCount,
        skipped: jobStatus.skippedCount,
        failed: jobStatus.failedCount,
        errors: jobStatus.errors || [],
        status: jobStatus.status,
      }
    : null

  const handleStartTagging = () => {
    if (taggingScope === 'round' && selectedRoundForTagging) {
      // Router only accepts programId; resolve from the selected round's parent program
      const parentProgram = programs?.find((p) =>
        ((p.stages ?? []) as Array<{ id: string }>)?.some((s: { id: string }) => s.id === selectedRoundForTagging)
      )
      if (parentProgram) {
        startTaggingJob.mutate({ programId: parentProgram.id })
      }
    } else if (taggingScope === 'program' && selectedProgramForTagging) {
      startTaggingJob.mutate({ programId: selectedProgramForTagging })
    }
  }

  const handleCloseTaggingDialog = () => {
    setAiTagDialogOpen(false)
    // Only reset job state if not in progress (preserve polling for background jobs)
    if (!taggingInProgress) {
      setActiveTaggingJobId(null)
      setSelectedRoundForTagging('')
      setSelectedProgramForTagging('')
    }
  }

  // Get selected program's rounds (flattened from pipelines -> tracks -> stages)
  const selectedProgram = programs?.find(p => p.id === selectedProgramForTagging)
  const programRounds = selectedProgram?.stages ?? []

  // Calculate stats for display
  const displayProgram = taggingScope === 'program'
    ? selectedProgram
    : (selectedRoundForTagging ? programs?.find(p => (p.stages as Array<{ id: string }>)?.some(s => s.id === selectedRoundForTagging)) : null)

  // Calculate progress percentage
  const taggingProgressPercent = jobStatus && jobStatus.totalProjects > 0
    ? Math.round((jobStatus.processedCount / jobStatus.totalProjects) * 100)
    : 0

  // Bulk selection state
  const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set())
  const [allMatchingSelected, setAllMatchingSelected] = useState(false)
  const [bulkStatus, setBulkStatus] = useState<string>('')
  const [bulkConfirmOpen, setBulkConfirmOpen] = useState(false)
  const [bulkNotificationsConfirmed, setBulkNotificationsConfirmed] = useState(false)
  const [bulkAction, setBulkAction] = useState<'status' | 'assign' | 'delete'>('status')
  const [bulkAssignRoundId, setBulkAssignRoundId] = useState('')
  const [bulkAssignDialogOpen, setBulkAssignDialogOpen] = useState(false)
  const [bulkDeleteConfirmOpen, setBulkDeleteConfirmOpen] = useState(false)

  const bulkStatusTriggersNotifications = ['SEMIFINALIST', 'FINALIST', 'REJECTED'].includes(bulkStatus)

  // Query for fetching all matching IDs (used for "select all across pages")
  const allIdsQuery = trpc.project.listAllIds.useQuery(
    {
      search: filters.search || undefined,
      statuses:
        filters.statuses.length > 0
          ? (filters.statuses as Array<
              | 'SUBMITTED'
              | 'ELIGIBLE'
              | 'ASSIGNED'
              | 'SEMIFINALIST'
              | 'FINALIST'
              | 'REJECTED'
            >)
          : undefined,
      roundId: filters.roundId || undefined,
      competitionCategory:
        (filters.competitionCategory as 'STARTUP' | 'BUSINESS_CONCEPT') ||
        undefined,
      oceanIssue: filters.oceanIssue
        ? (filters.oceanIssue as
            | 'POLLUTION_REDUCTION'
            | 'CLIMATE_MITIGATION'
            | 'TECHNOLOGY_INNOVATION'
            | 'SUSTAINABLE_SHIPPING'
            | 'BLUE_CARBON'
            | 'HABITAT_RESTORATION'
            | 'COMMUNITY_CAPACITY'
            | 'SUSTAINABLE_FISHING'
            | 'CONSUMER_AWARENESS'
            | 'OCEAN_ACIDIFICATION'
            | 'OTHER')
        : undefined,
      country: filters.country || undefined,
      wantsMentorship: filters.wantsMentorship,
      hasFiles: filters.hasFiles,
      hasAssignments: filters.hasAssignments,
    },
    { enabled: false } // Only fetch on demand
  )

  const bulkUpdateStatus = trpc.project.bulkUpdateStatus.useMutation({
    onSuccess: (result) => {
      toast.success(`${result.updated} project${result.updated !== 1 ? 's' : ''} updated successfully`)
      setSelectedIds(new Set())
      setAllMatchingSelected(false)
      setBulkStatus('')
      setBulkConfirmOpen(false)
      utils.project.list.invalidate()
    },
    onError: (error) => {
      toast.error(error.message || 'Failed to update projects')
    },
  })

  const bulkNotificationPreview = trpc.project.previewStatusNotificationRecipients.useQuery(
    {
      ids: Array.from(selectedIds),
      status: (bulkStatus || 'SUBMITTED') as
        | 'SUBMITTED'
        | 'ELIGIBLE'
        | 'ASSIGNED'
        | 'SEMIFINALIST'
        | 'FINALIST'
        | 'REJECTED',
    },
    {
      enabled:
        bulkConfirmOpen &&
        selectedIds.size > 0 &&
        bulkStatusTriggersNotifications,
      staleTime: 30_000,
    }
  )

  const bulkAssignToRound = trpc.projectPool.assignToRound.useMutation({
    onSuccess: (result) => {
      toast.success(`${result.assignedCount} project${result.assignedCount !== 1 ? 's' : ''} assigned to round`)
      setSelectedIds(new Set())
      setAllMatchingSelected(false)
      setBulkAssignRoundId('')
      setBulkAssignDialogOpen(false)
      utils.project.list.invalidate()
    },
    onError: (error) => {
      toast.error(error.message || 'Failed to assign projects')
    },
  })

  const bulkDeleteProjects = trpc.project.bulkDelete.useMutation({
    onSuccess: (result) => {
      toast.success(`${result.deleted} project${result.deleted !== 1 ? 's' : ''} deleted`)
      setSelectedIds(new Set())
      setAllMatchingSelected(false)
      setBulkDeleteConfirmOpen(false)
      utils.project.list.invalidate()
    },
    onError: (error) => {
      toast.error(error.message || 'Failed to delete projects')
    },
  })

  const handleToggleSelect = (id: string) => {
    setAllMatchingSelected(false)
    setSelectedIds((prev) => {
      const next = new Set(prev)
      if (next.has(id)) {
        next.delete(id)
      } else {
        next.add(id)
      }
      return next
    })
  }

  const handleSelectAll = () => {
    if (!data) return
    setAllMatchingSelected(false)
    const allVisible = data.projects.map((p) => p.id)
    const allSelected = allVisible.every((id) => selectedIds.has(id))
    if (allSelected) {
      setSelectedIds((prev) => {
        const next = new Set(prev)
        allVisible.forEach((id) => next.delete(id))
        return next
      })
    } else {
      setSelectedIds((prev) => {
        const next = new Set(prev)
        allVisible.forEach((id) => next.add(id))
        return next
      })
    }
  }

  const handleSelectAllMatching = async () => {
    const result = await allIdsQuery.refetch()
    if (result.data) {
      setSelectedIds(new Set(result.data.ids))
      setAllMatchingSelected(true)
    }
  }

  const handleClearSelection = () => {
    setSelectedIds(new Set())
    setAllMatchingSelected(false)
    setBulkStatus('')
    setBulkNotificationsConfirmed(false)
  }

  const handleBulkApply = () => {
    if (!bulkStatus || selectedIds.size === 0) return
    setBulkNotificationsConfirmed(false)
    setBulkConfirmOpen(true)
  }

  const handleBulkConfirm = () => {
    if (!bulkStatus || selectedIds.size === 0) return
    if (bulkStatusTriggersNotifications && !bulkNotificationsConfirmed) {
      toast.error('Confirm participant recipients before sending notifications')
      return
    }
    bulkUpdateStatus.mutate({
      ids: Array.from(selectedIds),
      status: bulkStatus as 'SUBMITTED' | 'ELIGIBLE' | 'ASSIGNED' | 'SEMIFINALIST' | 'FINALIST' | 'REJECTED',
    })
  }

  // Determine if all visible projects are selected
  const allVisibleSelected = data
    ? data.projects.length > 0 && data.projects.every((p) => selectedIds.has(p.id))
    : false
  const someVisibleSelected = data
    ? data.projects.some((p) => selectedIds.has(p.id)) && !allVisibleSelected
    : false

  const assignToRound = trpc.projectPool.assignToRound.useMutation({
    onSuccess: () => {
      toast.success('Project assigned to round')
      utils.project.list.invalidate()
      setAssignDialogOpen(false)
      setProjectToAssign(null)
      setAssignRoundId('')
    },
    onError: (error) => {
      toast.error(error.message || 'Failed to assign project')
    },
  })

  const deleteProject = trpc.project.delete.useMutation({
    onSuccess: () => {
      toast.success('Project deleted successfully')
      utils.project.list.invalidate()
      setDeleteDialogOpen(false)
      setProjectToDelete(null)
    },
    onError: (error) => {
      toast.error(error.message || 'Failed to delete project')
    },
  })

  const handleDeleteClick = (project: { id: string; title: string }) => {
    setProjectToDelete(project)
    setDeleteDialogOpen(true)
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-2xl font-semibold tracking-tight">Projects</h1>
          <p className="text-muted-foreground">
            {data ? `${data.total} projects across all stages` : 'Manage submitted projects across all stages'}
          </p>
        </div>
        <div className="flex flex-wrap gap-2">
          <Button
            variant="outline"
            onClick={() => setAiTagDialogOpen(true)}
            className={taggingInProgress ? 'border-amber-400 bg-amber-50 dark:bg-amber-950/20' : ''}
          >
            {taggingInProgress ? (
              <Loader2 className="mr-2 h-4 w-4 animate-spin text-amber-600" />
            ) : (
              <Bot className="mr-2 h-4 w-4" />
            )}
            AI Tags
            {taggingInProgress && (
              <span className="ml-1.5 text-[10px] text-amber-600 font-medium">
                {taggingProgressPercent}%
              </span>
            )}
          </Button>
          <Button variant="outline" asChild>
            <Link href="/admin/projects/pool">
              <Layers className="mr-2 h-4 w-4" />
              Assign to Round
            </Link>
          </Button>
          <Button variant="outline" asChild>
            <Link href="/admin/projects/bulk-upload">
              <FileUp className="mr-2 h-4 w-4" />
              Bulk Upload
            </Link>
          </Button>
          <Button variant="outline" asChild>
            <Link href="/admin/projects/import">
              <FileUp className="mr-2 h-4 w-4" />
              Import
            </Link>
          </Button>
          <Button asChild>
            <Link href="/admin/projects/new">
              <Plus className="mr-2 h-4 w-4" />
              Add Project
            </Link>
          </Button>
        </div>
      </div>

      {/* Search */}
      <div className="space-y-1">
        <div className="relative">
          <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
          <Input
            value={searchInput}
            onChange={(e) => setSearchInput(e.target.value)}
            placeholder="Search projects by title, team, or description..."
            className="pl-10 pr-10"
          />
          {searchInput && (
            <button
              type="button"
              onClick={() => setSearchInput('')}
              className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
            >
              <X className="h-4 w-4" />
            </button>
          )}
        </div>
        {filters.search && data && (
          <p className="text-xs text-muted-foreground pl-1">
            {data.total} result{data.total !== 1 ? 's' : ''} for &ldquo;{filters.search}&rdquo;
          </p>
        )}
      </div>

      {/* Filters */}
      <ProjectFiltersBar
        filters={filters}
        filterOptions={filterOptions ? {
          ...filterOptions,
          rounds: programs?.flatMap(p =>
            (p.stages as Array<{ id: string; name: string }>)?.map(s => ({
              id: s.id,
              name: s.name,
              programName: p.name,
              programYear: p.year,
            })) ?? []
          ) ?? [],
        } satisfies FilterOptions : undefined}
        onChange={handleFiltersChange}
      />

      {/* Stats Summary + View Toggle */}
      {data && data.projects.length > 0 && (
        <div className="flex items-center justify-between gap-4">
          <div className="flex flex-wrap items-center gap-2 text-sm">
            {Object.entries(data.statusCounts ?? {})
              .sort(([a], [b]) => {
                const order = ['SUBMITTED', 'ELIGIBLE', 'ASSIGNED', 'SEMIFINALIST', 'FINALIST', 'WINNER', 'REJECTED', 'WITHDRAWN']
                return order.indexOf(a) - order.indexOf(b)
              })
              .map(([status, count]) => (
                <Badge
                  key={status}
                  variant={statusColors[status] || 'secondary'}
                  className="text-xs font-normal"
                >
                  {count} {status.charAt(0) + status.slice(1).toLowerCase().replace('_', ' ')}
                </Badge>
              ))}
            {data.total > data.projects.length && (
              <span className="text-xs text-muted-foreground ml-1">
                (page {data.page} of {data.totalPages})
              </span>
            )}
          </div>
          <div className="flex items-center gap-1 shrink-0">
            <Button
              variant={viewMode === 'table' ? 'secondary' : 'ghost'}
              size="icon"
              className="h-8 w-8"
              onClick={() => setViewMode('table')}
              aria-label="Table view"
            >
              <LayoutList className="h-4 w-4" />
            </Button>
            <Button
              variant={viewMode === 'card' ? 'secondary' : 'ghost'}
              size="icon"
              className="h-8 w-8"
              onClick={() => setViewMode('card')}
              aria-label="Card view"
            >
              <LayoutGrid className="h-4 w-4" />
            </Button>
          </div>
        </div>
      )}

      {/* Select All Banner */}
      {data && allVisibleSelected && data.total > data.projects.length && !allMatchingSelected && (
        <div className="flex items-center justify-center gap-2 rounded-lg border border-primary/20 bg-primary/5 px-4 py-2.5 text-sm">
          <span>
            All <strong>{data.projects.length}</strong> projects on this page are selected.
          </span>
          <Button
            variant="link"
            size="sm"
            className="h-auto p-0 font-semibold"
            onClick={handleSelectAllMatching}
            disabled={allIdsQuery.isFetching}
          >
            {allIdsQuery.isFetching ? (
              <>
                <Loader2 className="mr-1 h-3 w-3 animate-spin" />
                Loading...
              </>
            ) : (
              `Select all ${data.total} matching projects`
            )}
          </Button>
        </div>
      )}
      {allMatchingSelected && data && (
        <div className="flex items-center justify-center gap-2 rounded-lg border border-primary/20 bg-primary/5 px-4 py-2.5 text-sm">
          <CheckCircle2 className="h-4 w-4 text-primary" />
          <span>
            All <strong>{selectedIds.size}</strong> matching projects are selected.
          </span>
          <Button
            variant="link"
            size="sm"
            className="h-auto p-0"
            onClick={handleClearSelection}
          >
            Clear selection
          </Button>
        </div>
      )}

      {/* Content */}
      {isLoading ? (
        <Card>
          <CardContent className="p-6">
            <div className="space-y-4">
              {[...Array(5)].map((_, i) => (
                <div key={i} className="flex items-center justify-between">
                  <div className="space-y-2">
                    <Skeleton className="h-5 w-64" />
                    <Skeleton className="h-4 w-32" />
                  </div>
                  <Skeleton className="h-9 w-9" />
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      ) : data && data.projects.length === 0 ? (
        <Card>
          <CardContent className="flex flex-col items-center justify-center py-12 text-center">
            <ClipboardList className="h-12 w-12 text-muted-foreground/50" />
            <p className="mt-2 font-medium">No projects found</p>
            <p className="text-sm text-muted-foreground">
              {filters.search ||
              filters.statuses.length > 0 ||
              filters.roundId ||
              filters.competitionCategory ||
              filters.oceanIssue ||
              filters.country
                ? 'Try adjusting your filters'
                : 'Import projects via CSV or create them manually'}
            </p>
            {!filters.search && filters.statuses.length === 0 && (
              <div className="mt-4 flex gap-2">
                <Button asChild>
                  <Link href="/admin/projects/import">
                    <FileUp className="mr-2 h-4 w-4" />
                    Import CSV
                  </Link>
                </Button>
                <Button variant="outline" asChild>
                  <Link href="/admin/projects/new">
                    <Plus className="mr-2 h-4 w-4" />
                    Add Project
                  </Link>
                </Button>
              </div>
            )}
          </CardContent>
        </Card>
      ) : data ? (
        <>
          {/* Table View */}
          {viewMode === 'table' ? (
            <>
              {/* Desktop table */}
              <Card className="hidden md:block">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead className="w-10">
                        <Checkbox
                          checked={allVisibleSelected ? true : someVisibleSelected ? 'indeterminate' : false}
                          onCheckedChange={handleSelectAll}
                          aria-label="Select all projects"
                        />
                      </TableHead>
                      <TableHead className="min-w-[280px]">Project</TableHead>
                      <TableHead>Category</TableHead>
                      <TableHead>Program</TableHead>
                      <TableHead>Tags</TableHead>
                      <TableHead>Assignments</TableHead>
                      <TableHead>Status</TableHead>
                      <TableHead className="text-right">Actions</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {data.projects.map((project) => {
                      const isEliminated = project.status === 'REJECTED'
                      return (
                      <TableRow
                        key={project.id}
                        className={`group relative cursor-pointer hover:bg-muted/50 ${isEliminated ? 'opacity-60 bg-destructive/5' : ''}`}
                      >
                        <TableCell className="relative z-10">
                          <Checkbox
                            checked={selectedIds.has(project.id)}
                            onCheckedChange={() => handleToggleSelect(project.id)}
                            aria-label={`Select ${project.title}`}
                            onClick={(e) => e.stopPropagation()}
                          />
                        </TableCell>
                        <TableCell>
                          <Link
                            href={`/admin/projects/${project.id}`}
                            className="flex items-center gap-3 after:absolute after:inset-0 after:content-['']"
                          >
                            <ProjectLogo
                              project={project}
                              size="sm"
                              fallback="initials"
                            />
                            <div>
                              <p className={`font-medium hover:text-primary ${uppercaseNames ? 'uppercase' : ''}`}>
                                {truncate(project.title, 40)}
                              </p>
                              <p className="text-sm text-muted-foreground">
                                {project.teamName}
                                {project.country && (() => {
                                  const code = normalizeCountryToCode(project.country)
                                  const flag = code ? getCountryFlag(code) : null
                                  const name = code ? getCountryName(code) : project.country
                                  return (
                                    <span className="text-xs text-muted-foreground/70"> · {flag && <span className="text-sm">{flag}</span>} {name}</span>
                                  )
                                })()}
                              </p>
                            </div>
                          </Link>
                        </TableCell>
                        <TableCell>
                          {project.competitionCategory ? (
                            <Badge variant="outline" className="text-xs whitespace-nowrap">
                              {project.competitionCategory === 'STARTUP' ? 'Startup' : 'Business Concept'}
                            </Badge>
                          ) : (
                            <span className="text-xs text-muted-foreground">-</span>
                          )}
                        </TableCell>
                        <TableCell>
                          <div>
                            <div className="flex items-center gap-2">
                              {project.program ? (
                                <p>{project.program.name}</p>
                              ) : (
                                <Badge variant="outline" className="text-xs text-amber-600 border-amber-300 bg-amber-50">
                                  Unassigned
                                </Badge>
                              )}
                            </div>
                            <p className="text-sm text-muted-foreground">
                              {project.program?.year}
                            </p>
                          </div>
                        </TableCell>
                        <TableCell>
                          {project.tags && project.tags.length > 0 ? (
                            <div className="flex flex-wrap gap-1 max-w-[200px]">
                              {project.tags.slice(0, 3).map((tag) => (
                                <Badge
                                  key={tag}
                                  variant="secondary"
                                  className="text-[10px] px-1.5 py-0 font-normal"
                                >
                                  {tag}
                                </Badge>
                              ))}
                              {project.tags.length > 3 && (
                                <Badge
                                  variant="secondary"
                                  className="text-[10px] px-1.5 py-0 font-normal"
                                >
                                  +{project.tags.length - 3}
                                </Badge>
                              )}
                            </div>
                          ) : (
                            <span className="text-xs text-muted-foreground">-</span>
                          )}
                        </TableCell>
                        <TableCell>
                          <div className="flex items-center gap-1">
                            <Users className="h-4 w-4 text-muted-foreground" />
                            {project._count.assignments}
                          </div>
                        </TableCell>
                        <TableCell>
                          <StatusBadge status={project.status ?? 'SUBMITTED'} />
                        </TableCell>
                        <TableCell className="relative z-10 text-right">
                          <DropdownMenu>
                            <DropdownMenuTrigger asChild>
                              <Button variant="ghost" size="icon">
                                <MoreHorizontal className="h-4 w-4" />
                                <span className="sr-only">Actions</span>
                              </Button>
                            </DropdownMenuTrigger>
                            <DropdownMenuContent align="end">
                              <DropdownMenuItem asChild>
                                <Link href={`/admin/projects/${project.id}`}>
                                  <Eye className="mr-2 h-4 w-4" />
                                  View Details
                                </Link>
                              </DropdownMenuItem>
                              <DropdownMenuItem asChild>
                                <Link href={`/admin/projects/${project.id}/edit`}>
                                  <Pencil className="mr-2 h-4 w-4" />
                                  Edit
                                </Link>
                              </DropdownMenuItem>
                              {project._count.assignments === 0 && (
                                <DropdownMenuItem
                                  onClick={(e) => {
                                    e.stopPropagation()
                                    setProjectToAssign({ id: project.id, title: project.title })
                                    setAssignDialogOpen(true)
                                  }}
                                >
                                  <FolderOpen className="mr-2 h-4 w-4" />
                                  Assign to Round
                                </DropdownMenuItem>
                              )}
                              <DropdownMenuSeparator />
                              <DropdownMenuItem
                                className="text-destructive focus:text-destructive"
                                onClick={(e) => {
                                  e.stopPropagation()
                                  handleDeleteClick({ id: project.id, title: project.title })
                                }}
                              >
                                <Trash2 className="mr-2 h-4 w-4" />
                                Delete
                              </DropdownMenuItem>
                            </DropdownMenuContent>
                          </DropdownMenu>
                        </TableCell>
                      </TableRow>
                    )})}
                  </TableBody>
                </Table>
              </Card>

              {/* Mobile card view (table mode fallback) */}
              <div className="space-y-4 md:hidden">
                {data.projects.map((project) => (
                  <div key={project.id} className="relative">
                    <div className="absolute left-3 top-4 z-10">
                      <Checkbox
                        checked={selectedIds.has(project.id)}
                        onCheckedChange={() => handleToggleSelect(project.id)}
                        aria-label={`Select ${project.title}`}
                      />
                    </div>
                    <Link href={`/admin/projects/${project.id}`} className="block">
                      <Card className="transition-all duration-200 hover:bg-muted/50 hover:-translate-y-0.5 hover:shadow-md">
                        <CardHeader className="pb-3">
                          <div className="flex items-start gap-3 pl-8">
                            <ProjectLogo project={project} size="md" fallback="initials" />
                            <div className="flex-1 min-w-0">
                              <div className="flex items-start justify-between gap-2">
                                <CardTitle className={`text-base line-clamp-2 ${uppercaseNames ? 'uppercase' : ''}`}>
                                  {project.title}
                                </CardTitle>
                                <StatusBadge status={project.status ?? 'SUBMITTED'} className="shrink-0" />
                              </div>
                              <CardDescription>{project.teamName}</CardDescription>
                            </div>
                          </div>
                        </CardHeader>
                        <CardContent className="space-y-3">
                          <div className="flex items-center justify-between text-sm">
                            <span className="text-muted-foreground">Program</span>
                            <span>{project.program?.name ?? 'Unassigned'}</span>
                          </div>
                          {project.competitionCategory && (
                            <div className="flex items-center justify-between text-sm">
                              <span className="text-muted-foreground">Category</span>
                              <Badge variant="outline" className="text-xs">
                                {project.competitionCategory === 'STARTUP' ? 'Startup' : 'Business Concept'}
                              </Badge>
                            </div>
                          )}
                          <div className="flex items-center justify-between text-sm">
                            <span className="text-muted-foreground">Assignments</span>
                            <span>{project._count.assignments} jurors</span>
                          </div>
                          {project.tags && project.tags.length > 0 && (
                            <div className="flex flex-wrap gap-1">
                              {project.tags.slice(0, 4).map((tag) => (
                                <Badge key={tag} variant="secondary" className="text-[10px] px-1.5 py-0 font-normal">
                                  {tag}
                                </Badge>
                              ))}
                              {project.tags.length > 4 && (
                                <Badge variant="secondary" className="text-[10px] px-1.5 py-0 font-normal">
                                  +{project.tags.length - 4}
                                </Badge>
                              )}
                            </div>
                          )}
                        </CardContent>
                      </Card>
                    </Link>
                  </div>
                ))}
              </div>
            </>
          ) : (
            /* Card View */
            <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-3">
              {data.projects.map((project) => {
                const isEliminated = project.status === 'REJECTED'
                return (
                  <div key={project.id} className="relative">
                    <div className="absolute left-3 top-3 z-10">
                      <Checkbox
                        checked={selectedIds.has(project.id)}
                        onCheckedChange={() => handleToggleSelect(project.id)}
                        aria-label={`Select ${project.title}`}
                      />
                    </div>
                    <Link href={`/admin/projects/${project.id}`} className="block">
                      <Card className={`transition-all duration-200 hover:bg-muted/50 hover:-translate-y-0.5 hover:shadow-md h-full ${isEliminated ? 'opacity-60 bg-destructive/5' : ''}`}>
                        <CardHeader className="pb-3">
                          <div className="flex items-start gap-3 pl-7">
                            <ProjectLogo project={project} size="lg" fallback="initials" />
                            <div className="flex-1 min-w-0">
                              <div className="flex items-start justify-between gap-2">
                                <CardTitle className={`text-base line-clamp-2 ${uppercaseNames ? 'uppercase' : ''}`}>
                                  {project.title}
                                </CardTitle>
                                <DropdownMenu>
                                  <DropdownMenuTrigger asChild>
                                    <Button variant="ghost" size="icon" className="h-7 w-7 shrink-0 relative z-10" onClick={(e) => e.preventDefault()}>
                                      <MoreHorizontal className="h-4 w-4" />
                                    </Button>
                                  </DropdownMenuTrigger>
                                  <DropdownMenuContent align="end">
                                    <DropdownMenuItem asChild>
                                      <Link href={`/admin/projects/${project.id}`}>
                                        <Eye className="mr-2 h-4 w-4" />
                                        View Details
                                      </Link>
                                    </DropdownMenuItem>
                                    <DropdownMenuItem asChild>
                                      <Link href={`/admin/projects/${project.id}/edit`}>
                                        <Pencil className="mr-2 h-4 w-4" />
                                        Edit
                                      </Link>
                                    </DropdownMenuItem>
                                    {project._count.assignments === 0 && (
                                      <DropdownMenuItem
                                        onClick={(e) => {
                                          e.stopPropagation()
                                          setProjectToAssign({ id: project.id, title: project.title })
                                          setAssignDialogOpen(true)
                                        }}
                                      >
                                        <FolderOpen className="mr-2 h-4 w-4" />
                                        Assign to Round
                                      </DropdownMenuItem>
                                    )}
                                    <DropdownMenuSeparator />
                                    <DropdownMenuItem
                                      className="text-destructive focus:text-destructive"
                                      onClick={(e) => {
                                        e.stopPropagation()
                                        handleDeleteClick({ id: project.id, title: project.title })
                                      }}
                                    >
                                      <Trash2 className="mr-2 h-4 w-4" />
                                      Delete
                                    </DropdownMenuItem>
                                  </DropdownMenuContent>
                                </DropdownMenu>
                              </div>
                              <CardDescription className="mt-0.5">
                                {project.teamName}
                                {project.country && (() => {
                                  const code = normalizeCountryToCode(project.country)
                                  const flag = code ? getCountryFlag(code) : null
                                  const name = code ? getCountryName(code) : project.country
                                  return (
                                    <span className="text-xs text-muted-foreground/70"> · {flag && <span className="text-sm">{flag}</span>} {name}</span>
                                  )
                                })()}
                              </CardDescription>
                            </div>
                          </div>
                        </CardHeader>
                        <CardContent className="space-y-3 pt-0">
                          <div className="flex items-center justify-between gap-2">
                            <StatusBadge status={project.status ?? 'SUBMITTED'} />
                            {project.competitionCategory && (
                              <Badge variant="outline" className="text-xs">
                                {project.competitionCategory === 'STARTUP' ? 'Startup' : 'Business Concept'}
                              </Badge>
                            )}
                          </div>
                          <div className="flex items-center justify-between text-sm">
                            <span className="text-muted-foreground">Program</span>
                            <span className="text-right">
                              {project.program ? (
                                <>{project.program.name}</>
                              ) : (
                                <Badge variant="outline" className="text-xs text-amber-600 border-amber-300 bg-amber-50">
                                  Unassigned
                                </Badge>
                              )}
                            </span>
                          </div>
                          <div className="flex items-center justify-between text-sm">
                            <span className="text-muted-foreground">Jurors</span>
                            <span>{project._count.assignments}</span>
                          </div>
                          <div className="flex items-center justify-between text-sm">
                            <span className="text-muted-foreground">Files</span>
                            <span>{project._count?.files ?? 0}</span>
                          </div>
                          {project.createdAt && (
                            <div className="flex items-center justify-between text-sm">
                              <span className="text-muted-foreground">Submitted</span>
                              <span className="text-xs">{new Date(project.createdAt).toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: 'numeric' })}</span>
                            </div>
                          )}
                          {project.tags && project.tags.length > 0 && (
                            <div className="flex flex-wrap gap-1 pt-1 border-t">
                              {project.tags.slice(0, 5).map((tag) => (
                                <Badge key={tag} variant="secondary" className="text-[10px] px-1.5 py-0 font-normal">
                                  {tag}
                                </Badge>
                              ))}
                              {project.tags.length > 5 && (
                                <Badge variant="secondary" className="text-[10px] px-1.5 py-0 font-normal">
                                  +{project.tags.length - 5}
                                </Badge>
                              )}
                            </div>
                          )}
                        </CardContent>
                      </Card>
                    </Link>
                  </div>
                )
              })}
            </div>
          )}

          {/* Pagination */}
          <Pagination
            page={data.page}
            totalPages={data.totalPages}
            total={data.total}
            perPage={perPage}
            onPageChange={setPage}
            onPerPageChange={handlePerPageChange}
          />
        </>
      ) : null}

      {/* Bulk Action Floating Toolbar */}
      {selectedIds.size > 0 && (
        <div className="fixed bottom-6 left-1/2 z-50 -translate-x-1/2 w-[95vw] max-w-xl">
          <Card className="border-2 shadow-lg">
            <CardContent className="flex flex-col gap-3 p-4 sm:flex-row sm:items-center">
              <Badge variant="secondary" className="shrink-0 text-sm">
                {selectedIds.size} selected
              </Badge>
              <div className="flex flex-wrap gap-2 flex-1">
                {/* Assign to Stage */}
                <Button
                  size="sm"
                  variant="outline"
                  onClick={() => setBulkAssignDialogOpen(true)}
                >
                  <ArrowRightCircle className="mr-1.5 h-4 w-4" />
                  Assign to Round
                </Button>
                {/* Change Status (only when filtered by round) */}
                {filters.roundId && (
                  <>
                    <Select value={bulkStatus} onValueChange={setBulkStatus}>
                      <SelectTrigger className="w-[160px] h-9 text-sm">
                        <SelectValue placeholder="Set status..." />
                      </SelectTrigger>
                      <SelectContent>
                        {['SUBMITTED', 'ELIGIBLE', 'ASSIGNED', 'SEMIFINALIST', 'FINALIST', 'REJECTED'].map((s) => (
                          <SelectItem key={s} value={s}>
                            {s.replace('_', ' ')}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                    <Button
                      size="sm"
                      onClick={handleBulkApply}
                      disabled={!bulkStatus || bulkUpdateStatus.isPending}
                    >
                      {bulkUpdateStatus.isPending && (
                        <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                      )}
                      Apply
                    </Button>
                  </>
                )}
                {/* Delete */}
                <Button
                  size="sm"
                  variant="destructive"
                  onClick={() => setBulkDeleteConfirmOpen(true)}
                >
                  <Trash2 className="mr-1.5 h-4 w-4" />
                  Delete
                </Button>
              </div>
              <Button
                size="sm"
                variant="ghost"
                onClick={handleClearSelection}
                className="shrink-0"
              >
                <X className="mr-1 h-4 w-4" />
                Clear
              </Button>
            </CardContent>
          </Card>
        </div>
      )}

      {/* Bulk Status Update Confirmation Dialog */}
      <AlertDialog
        open={bulkConfirmOpen}
        onOpenChange={(open) => {
          setBulkConfirmOpen(open)
          if (!open) {
            setBulkNotificationsConfirmed(false)
          }
        }}
      >
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Update Project Status</AlertDialogTitle>
            <AlertDialogDescription asChild>
              <div className="space-y-2">
                <p>
                  You are about to change the status of{' '}
                  <strong>{selectedIds.size} project{selectedIds.size !== 1 ? 's' : ''}</strong>{' '}
                  to <Badge variant={statusColors[bulkStatus] || 'secondary'}>{bulkStatus.replace('_', ' ')}</Badge>.
                </p>
                {bulkStatus === 'REJECTED' && (
                  <div className="flex items-start gap-2 rounded-md bg-destructive/10 p-3 text-destructive">
                    <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" />
                    <p className="text-sm">
                      Warning: Rejected projects will be marked as eliminated. This will send notifications to the project teams.
                    </p>
                  </div>
                )}

                {bulkStatusTriggersNotifications && (
                  <div className="space-y-3 rounded-md border bg-muted/20 p-3">
                    <p className="text-sm font-medium">Participant Notification Check</p>
                    <p className="text-xs text-muted-foreground">
                      Review recipients before automated emails are sent.
                    </p>

                    {bulkNotificationPreview.isLoading ? (
                      <div className="flex items-center gap-2 text-xs text-muted-foreground">
                        <Loader2 className="h-3.5 w-3.5 animate-spin" />
                        Loading recipients...
                      </div>
                    ) : bulkNotificationPreview.data ? (
                      <div className="space-y-2">
                        <p className="text-xs text-muted-foreground">
                          {bulkNotificationPreview.data.totalRecipients} recipient
                          {bulkNotificationPreview.data.totalRecipients !== 1 ? 's' : ''} across{' '}
                          {bulkNotificationPreview.data.projectsWithRecipients} project
                          {bulkNotificationPreview.data.projectsWithRecipients !== 1 ? 's' : ''}.
                        </p>

                        <div className="max-h-44 space-y-2 overflow-auto rounded-md border bg-background p-2">
                          {bulkNotificationPreview.data.projects
                            .filter((project) => project.recipientCount > 0)
                            .slice(0, 8)
                            .map((project) => (
                              <div key={project.id} className="text-xs">
                                <p className="font-medium">
                                  {project.title} ({project.recipientCount})
                                </p>
                                <p className="text-muted-foreground">
                                  {project.recipientsPreview.join(', ')}
                                  {project.hasMoreRecipients ? ', ...' : ''}
                                </p>
                              </div>
                            ))}
                          {bulkNotificationPreview.data.projectsWithRecipients === 0 && (
                            <p className="text-xs text-amber-700">
                              No linked participant accounts found. Status will update, but no team notifications will be sent.
                            </p>
                          )}
                        </div>
                      </div>
                    ) : null}

                    <div className="flex items-start gap-2">
                      <Checkbox
                        id="bulk-notification-confirm"
                        checked={bulkNotificationsConfirmed}
                        onCheckedChange={(checked) => setBulkNotificationsConfirmed(checked === true)}
                      />
                      <Label htmlFor="bulk-notification-confirm" className="text-sm font-normal leading-5">
                        I verified the recipient list and want to send these automated notifications.
                      </Label>
                    </div>
                  </div>
                )}
              </div>
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel disabled={bulkUpdateStatus.isPending}>Cancel</AlertDialogCancel>
            <AlertDialogAction
              onClick={handleBulkConfirm}
              className={bulkStatus === 'REJECTED' ? 'bg-destructive text-destructive-foreground hover:bg-destructive/90' : ''}
              disabled={bulkUpdateStatus.isPending || (bulkStatusTriggersNotifications && !bulkNotificationsConfirmed)}
            >
              {bulkUpdateStatus.isPending ? (
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
              ) : null}
              {bulkStatusTriggersNotifications ? 'Update + Notify' : 'Update'} {selectedIds.size} Project{selectedIds.size !== 1 ? 's' : ''}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* Delete Confirmation Dialog */}
      <AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Delete Project</AlertDialogTitle>
            <AlertDialogDescription>
              Are you sure you want to delete &quot;{projectToDelete?.title}&quot;? This will
              permanently remove the project, all its files, assignments, and evaluations.
              This action cannot be undone.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <AlertDialogAction
              onClick={() => projectToDelete && deleteProject.mutate({ id: projectToDelete.id })}
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
            >
              {deleteProject.isPending ? (
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
              ) : null}
              Delete
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* Assign to Round Dialog */}
      <Dialog open={assignDialogOpen} onOpenChange={(open) => {
        setAssignDialogOpen(open)
        if (!open) { setProjectToAssign(null); setAssignRoundId('') }
      }}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle>Assign to Round</DialogTitle>
            <DialogDescription>
              Assign &quot;{projectToAssign?.title}&quot; to a round.
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label>Select Round</Label>
              <Select value={assignRoundId} onValueChange={setAssignRoundId}>
                <SelectTrigger>
                  <SelectValue placeholder="Choose a round..." />
                </SelectTrigger>
                <SelectContent>
                  {programs?.flatMap((p) =>
                    ((p.stages || []) as Array<{ id: string; name: string }>).map((s) => (
                      <SelectItem key={s.id} value={s.id}>
                        {p.name} {p.year} - {s.name}
                      </SelectItem>
                    ))
                  )}
                </SelectContent>
              </Select>
            </div>
          </div>
          <div className="flex justify-end gap-2">
            <Button variant="outline" onClick={() => setAssignDialogOpen(false)}>
              Cancel
            </Button>
            <Button
              onClick={() => {
                if (projectToAssign && assignRoundId) {
                  assignToRound.mutate({
                    projectIds: [projectToAssign.id],
                    roundId: assignRoundId,
                  })
                }
              }}
              disabled={!assignRoundId || assignToRound.isPending}
            >
              {assignToRound.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
              Assign
            </Button>
          </div>
        </DialogContent>
      </Dialog>

      {/* Bulk Assign to Round Dialog */}
      <Dialog open={bulkAssignDialogOpen} onOpenChange={(open) => {
        setBulkAssignDialogOpen(open)
        if (!open) setBulkAssignRoundId('')
      }}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle>Assign to Round</DialogTitle>
            <DialogDescription>
              Assign {selectedIds.size} selected project{selectedIds.size !== 1 ? 's' : ''} to a round. Projects will have their status set to &quot;Assigned&quot;.
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label>Select Round</Label>
              <Select value={bulkAssignRoundId} onValueChange={setBulkAssignRoundId}>
                <SelectTrigger>
                  <SelectValue placeholder="Choose a round..." />
                </SelectTrigger>
                <SelectContent>
                  {programs?.flatMap((p) =>
                    ((p.stages || []) as Array<{ id: string; name: string }>).map((s) => (
                      <SelectItem key={s.id} value={s.id}>
                        {p.name} {p.year} - {s.name}
                      </SelectItem>
                    ))
                  )}
                </SelectContent>
              </Select>
            </div>
          </div>
          <div className="flex justify-end gap-2">
            <Button variant="outline" onClick={() => setBulkAssignDialogOpen(false)}>
              Cancel
            </Button>
            <Button
              onClick={() => {
                if (bulkAssignRoundId && selectedIds.size > 0) {
                  bulkAssignToRound.mutate({
                    projectIds: Array.from(selectedIds),
                    roundId: bulkAssignRoundId,
                  })
                }
              }}
              disabled={!bulkAssignRoundId || bulkAssignToRound.isPending}
            >
              {bulkAssignToRound.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
              Assign {selectedIds.size} Project{selectedIds.size !== 1 ? 's' : ''}
            </Button>
          </div>
        </DialogContent>
      </Dialog>

      {/* Bulk Delete Confirmation Dialog */}
      <AlertDialog open={bulkDeleteConfirmOpen} onOpenChange={setBulkDeleteConfirmOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Delete {selectedIds.size} Project{selectedIds.size !== 1 ? 's' : ''}</AlertDialogTitle>
            <AlertDialogDescription asChild>
              <div className="space-y-2">
                <p>
                  Are you sure you want to permanently delete{' '}
                  <strong>{selectedIds.size} project{selectedIds.size !== 1 ? 's' : ''}</strong>?
                  This will remove all associated files, assignments, and evaluations.
                </p>
                <div className="flex items-start gap-2 rounded-md bg-destructive/10 p-3 text-destructive">
                  <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" />
                  <p className="text-sm">
                    This action cannot be undone. All project data will be permanently lost.
                  </p>
                </div>
              </div>
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel disabled={bulkDeleteProjects.isPending}>Cancel</AlertDialogCancel>
            <AlertDialogAction
              onClick={() => {
                bulkDeleteProjects.mutate({ ids: Array.from(selectedIds) })
              }}
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
              disabled={bulkDeleteProjects.isPending}
            >
              {bulkDeleteProjects.isPending ? (
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
              ) : null}
              Delete {selectedIds.size} Project{selectedIds.size !== 1 ? 's' : ''}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* AI Tagging Dialog */}
      <Dialog open={aiTagDialogOpen} onOpenChange={handleCloseTaggingDialog}>
        <DialogContent className="sm:max-w-lg">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <div className="flex h-10 w-10 items-center justify-center rounded-full bg-gradient-to-br from-amber-400 to-orange-500">
                <Tags className="h-5 w-5 text-white" />
              </div>
              <div>
                <span>AI Tag Generator</span>
                <p className="text-sm font-normal text-muted-foreground">
                  Automatically categorize projects with expertise tags
                </p>
              </div>
            </DialogTitle>
          </DialogHeader>

          <div className="space-y-6 py-4">
            {/* Progress Indicator (when running) */}
            {taggingInProgress && (
              <div className="p-4 rounded-lg bg-blue-50 dark:bg-blue-950/20 border border-blue-200 dark:border-blue-900">
                <div className="space-y-3">
                  <div className="flex items-center gap-3">
                    <Loader2 className="h-5 w-5 animate-spin text-blue-600" />
                    <div className="flex-1">
                      <p className="font-medium text-blue-900 dark:text-blue-100">
                        AI Tagging in Progress
                      </p>
                      <p className="text-sm text-blue-700 dark:text-blue-300">
                        {jobStatus?.status === 'PENDING'
                          ? 'Initializing...'
                          : `Processing ${jobStatus?.totalProjects || 0} projects with AI...`}
                      </p>
                    </div>
                    {jobStatus && jobStatus.totalProjects > 0 && (
                      <Badge variant="outline" className="border-blue-300 text-blue-700">
                        <Clock className="mr-1 h-3 w-3" />
                        {jobStatus.processedCount} / {jobStatus.totalProjects}
                      </Badge>
                    )}
                  </div>
                  <div className="space-y-1">
                    <div className="flex justify-between text-sm">
                      <span className="text-blue-700 dark:text-blue-300">
                        {jobStatus?.processedCount || 0} of {jobStatus?.totalProjects || '?'} projects processed
                        {jobStatus?.taggedCount ? ` (${jobStatus.taggedCount} tagged)` : ''}
                      </span>
                      {jobStatus && jobStatus.totalProjects > 0 && (
                        <span className="font-medium text-blue-900 dark:text-blue-100">
                          {taggingProgressPercent}%
                        </span>
                      )}
                    </div>
                    <Progress
                      value={jobStatus?.totalProjects ? taggingProgressPercent : undefined}
                      className={`h-2 ${!jobStatus?.totalProjects ? 'animate-pulse' : ''}`}
                    />
                  </div>
                  {jobStatus?.failedCount ? (
                    <p className="text-xs text-amber-600">
                      {jobStatus.failedCount} projects failed so far
                    </p>
                  ) : null}
                </div>
              </div>
            )}

            {/* Result Display */}
            {taggingResult && !taggingInProgress && (
              <div className={`p-4 rounded-lg border ${
                taggingResult.failed > 0
                  ? 'bg-amber-50 dark:bg-amber-950/20 border-amber-200 dark:border-amber-900'
                  : taggingResult.processed > 0
                    ? 'bg-green-50 dark:bg-green-950/20 border-green-200 dark:border-green-900'
                    : 'bg-muted border-border'
              }`}>
                <div className="flex items-center gap-3 mb-3">
                  {taggingResult.processed > 0 ? (
                    <CheckCircle2 className="h-5 w-5 text-green-600" />
                  ) : taggingResult.errors.length > 0 ? (
                    <AlertCircle className="h-5 w-5 text-amber-600" />
                  ) : (
                    <Tags className="h-5 w-5 text-muted-foreground" />
                  )}
                  <span className="font-medium">
                    {taggingResult.processed > 0
                      ? 'Tagging Complete'
                      : taggingResult.errors.length > 0
                        ? 'Tagging Issue'
                        : 'No Projects to Tag'}
                  </span>
                </div>
                <div className="grid grid-cols-3 gap-3 text-center">
                  <div className="p-2 rounded bg-background">
                    <p className="text-2xl font-bold text-green-600">{taggingResult.processed}</p>
                    <p className="text-xs text-muted-foreground">Tagged</p>
                  </div>
                  <div className="p-2 rounded bg-background">
                    <p className="text-2xl font-bold text-muted-foreground">{taggingResult.skipped}</p>
                    <p className="text-xs text-muted-foreground">Already Tagged</p>
                  </div>
                  <div className="p-2 rounded bg-background">
                    <p className="text-2xl font-bold text-red-600">{taggingResult.failed}</p>
                    <p className="text-xs text-muted-foreground">Failed</p>
                  </div>
                </div>
                {taggingResult.errors.length > 0 && (
                  <div className="mt-3 space-y-2">
                    <p className="text-sm font-medium text-amber-700 dark:text-amber-300">
                      {taggingResult.errors.length} project{taggingResult.errors.length > 1 ? 's' : ''} failed:
                    </p>
                    <div className="max-h-32 overflow-y-auto rounded bg-background/50 p-2 text-xs space-y-1">
                      {taggingResult.errors.map((error, i) => (
                        <p key={i} className="text-amber-700 dark:text-amber-300">
                          • {error}
                        </p>
                      ))}
                    </div>
                  </div>
                )}
              </div>
            )}

            {/* Scope Selection */}
            {!taggingInProgress && !taggingResult && (
              <>
                <div className="space-y-3">
                  <Label className="text-sm font-medium">Tagging Scope</Label>
                  <div className="grid grid-cols-2 gap-3">
                    <button
                      type="button"
                      onClick={() => setTaggingScope('round')}
                      className={`flex flex-col items-center gap-2 p-4 rounded-lg border-2 transition-colors ${
                        taggingScope === 'round'
                          ? 'border-primary bg-primary/5'
                          : 'border-border hover:border-muted-foreground/30'
                      }`}
                    >
                      <FolderOpen className={`h-6 w-6 ${taggingScope === 'round' ? 'text-primary' : 'text-muted-foreground'}`} />
                      <span className={`text-sm font-medium ${taggingScope === 'round' ? 'text-primary' : ''}`}>
                        Single Round
                      </span>
                      <span className="text-xs text-muted-foreground text-center">
                        Tag projects in one specific round
                      </span>
                    </button>
                    <button
                      type="button"
                      onClick={() => setTaggingScope('program')}
                      className={`flex flex-col items-center gap-2 p-4 rounded-lg border-2 transition-colors ${
                        taggingScope === 'program'
                          ? 'border-primary bg-primary/5'
                          : 'border-border hover:border-muted-foreground/30'
                      }`}
                    >
                      <Layers className={`h-6 w-6 ${taggingScope === 'program' ? 'text-primary' : 'text-muted-foreground'}`} />
                      <span className={`text-sm font-medium ${taggingScope === 'program' ? 'text-primary' : ''}`}>
                        Entire Edition
                      </span>
                      <span className="text-xs text-muted-foreground text-center">
                        Tag all projects across all rounds
                      </span>
                    </button>
                  </div>
                </div>

                {/* Selection */}
                <div className="space-y-2">
                  {taggingScope === 'round' ? (
                    <>
                      <Label htmlFor="round-select">Select Round</Label>
                      <Select
                        value={selectedRoundForTagging}
                        onValueChange={setSelectedRoundForTagging}
                      >
                        <SelectTrigger id="round-select">
                          <SelectValue placeholder="Choose a round..." />
                        </SelectTrigger>
                        <SelectContent>
                          {programs?.flatMap(p =>
                            (p.stages as Array<{ id: string; name: string }>)?.map(s => (
                              <SelectItem key={s.id} value={s.id}>
                                {s.name} ({p.name})
                              </SelectItem>
                            )) ?? []
                          )}
                        </SelectContent>
                      </Select>
                    </>
                  ) : (
                    <>
                      <Label htmlFor="program-select">Select Edition</Label>
                      <Select
                        value={selectedProgramForTagging}
                        onValueChange={setSelectedProgramForTagging}
                      >
                        <SelectTrigger id="program-select">
                          <SelectValue placeholder="Choose an edition..." />
                        </SelectTrigger>
                        <SelectContent>
                          {programs?.map((program) => (
                            <SelectItem key={program.id} value={program.id}>
                              {program.name} ({program.year})
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </>
                  )}
                </div>

                {/* Info Note */}
                <div className="flex items-start gap-2 p-3 rounded-lg bg-muted/50">
                  <Tags className="h-4 w-4 mt-0.5 text-muted-foreground shrink-0" />
                  <p className="text-sm text-muted-foreground">
                    Only projects without existing tags will be processed. AI will analyze project descriptions and assign relevant expertise tags for jury matching.
                  </p>
                </div>
              </>
            )}
          </div>

          {/* Footer */}
          <div className="flex justify-end gap-3 pt-2 border-t">
            {taggingResult ? (
              <Button onClick={handleCloseTaggingDialog}>
                Done
              </Button>
            ) : (
              <>
                <Button
                  variant="outline"
                  onClick={handleCloseTaggingDialog}
                >
                  {taggingInProgress ? 'Run in Background' : 'Cancel'}
                </Button>
                <Button
                  onClick={handleStartTagging}
                  disabled={
                    taggingInProgress ||
                    (taggingScope === 'round' && !selectedRoundForTagging) ||
                    (taggingScope === 'program' && !selectedProgramForTagging)
                  }
                >
                  {taggingInProgress ? (
                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  ) : (
                    <Tags className="mr-2 h-4 w-4" />
                  )}
                  {taggingInProgress ? 'Processing...' : 'Generate Tags'}
                </Button>
              </>
            )}
          </div>
        </DialogContent>
      </Dialog>
    </div>
  )
}
