'use client'

import { useMemo, useState } from 'react'
import Link from 'next/link'
import { trpc } from '@/lib/trpc/client'
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Checkbox } from '@/components/ui/checkbox'
import { Badge } from '@/components/ui/badge'
import { Skeleton } from '@/components/ui/skeleton'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import {
  ArrowLeft,
  GitCompare,
  MapPin,
  Users,
  FileText,
  CheckCircle2,
  Clock,
} from 'lucide-react'

export default function CompareProjectsPage() {
  const [selectedRoundId, setSelectedRoundId] = useState<string>('')
  const [selectedIds, setSelectedIds] = useState<string[]>([])
  const [comparing, setComparing] = useState(false)

  // Fetch all assigned projects
  const { data: assignments, isLoading: loadingAssignments } =
    trpc.assignment.myAssignments.useQuery({})

  // Derive unique rounds from assignments
  const rounds = useMemo(() => {
    if (!assignments) return []
    const roundMap = new Map<string, { id: string; name: string }>()
    for (const a of assignments as Array<{ round: { id: string; name: string } }>) {
      if (a.round && !roundMap.has(a.round.id)) {
        roundMap.set(a.round.id, { id: a.round.id, name: String(a.round.name) })
      }
    }
    return Array.from(roundMap.values())
  }, [assignments])

  // Auto-select the first round if none selected
  const activeRoundId = selectedRoundId || (rounds.length > 0 ? rounds[0].id : '')

  // Filter assignments to current round
  const roundProjects = useMemo(() => {
    if (!assignments || !activeRoundId) return []
    return (assignments as Array<{
      project: Record<string, unknown>
      round: { id: string; name: string }
      evaluation?: Record<string, unknown>
    }>)
      .filter((a) => a.round.id === activeRoundId)
      .map((a) => ({
        ...a.project,
        roundName: a.round.name,
        evaluation: a.evaluation,
      }))
  }, [assignments, activeRoundId])

  // Fetch comparison data when comparing
  const { data: comparisonData, isLoading: loadingComparison } =
    trpc.evaluation.getMultipleForComparison.useQuery(
      { projectIds: selectedIds, roundId: activeRoundId },
      { enabled: comparing && selectedIds.length >= 2 && !!activeRoundId }
    )

  const toggleProject = (projectId: string) => {
    setSelectedIds((prev) => {
      if (prev.includes(projectId)) {
        return prev.filter((id) => id !== projectId)
      }
      if (prev.length >= 3) return prev
      return [...prev, projectId]
    })
    setComparing(false)
  }

  const handleCompare = () => {
    if (selectedIds.length >= 2) {
      setComparing(true)
    }
  }

  const handleReset = () => {
    setComparing(false)
    setSelectedIds([])
  }

  const handleRoundChange = (roundId: string) => {
    setSelectedRoundId(roundId)
    setSelectedIds([])
    setComparing(false)
  }

  if (loadingAssignments) {
    return <CompareSkeleton />
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center gap-4">
        <Button variant="ghost" asChild className="-ml-4">
          <Link href="/jury/assignments">
            <ArrowLeft className="mr-2 h-4 w-4" />
            Back to Assignments
          </Link>
        </Button>
      </div>

      <div className="flex items-center justify-between flex-wrap gap-4">
        <div>
          <h1 className="text-2xl font-semibold tracking-tight">Compare Projects</h1>
          <p className="text-muted-foreground">
            Select 2-3 projects from the same round to compare side by side
          </p>
        </div>
        <div className="flex items-center gap-2">
          {comparing && (
            <Button variant="outline" onClick={handleReset}>
              Reset
            </Button>
          )}
          {!comparing && (
            <Button
              onClick={handleCompare}
              disabled={selectedIds.length < 2}
            >
              <GitCompare className="mr-2 h-4 w-4" />
              Compare ({selectedIds.length})
            </Button>
          )}
        </div>
      </div>

      {/* Round selector */}
      {rounds.length > 1 && !comparing && (
        <div className="flex items-center gap-3">
          <span className="text-sm font-medium text-muted-foreground">Round:</span>
          <Select value={activeRoundId} onValueChange={handleRoundChange}>
            <SelectTrigger className="w-[280px]">
              <SelectValue placeholder="Select a round" />
            </SelectTrigger>
            <SelectContent>
              {rounds.map((r) => (
                <SelectItem key={r.id} value={r.id}>
                  {r.name}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
      )}

      {/* Project selector */}
      {!comparing && (
        <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
          {roundProjects.map((project: Record<string, unknown>) => {
            const projectId = project.id as string
            const isSelected = selectedIds.includes(projectId)
            const isDisabled = !isSelected && selectedIds.length >= 3

            return (
              <Card
                key={projectId}
                className={`cursor-pointer transition-colors ${
                  isSelected
                    ? 'border-primary ring-2 ring-primary/20'
                    : isDisabled
                    ? 'opacity-50'
                    : 'hover:border-primary/50'
                }`}
                onClick={() => !isDisabled && toggleProject(projectId)}
              >
                <CardContent className="p-4">
                  <div className="flex items-start gap-3">
                    <Checkbox
                      checked={isSelected}
                      disabled={isDisabled}
                      onCheckedChange={() => toggleProject(projectId)}
                      className="mt-1"
                    />
                    <div className="flex-1 min-w-0">
                      <p className="font-medium truncate">
                        {String(project.title || 'Untitled')}
                      </p>
                      <p className="text-sm text-muted-foreground truncate">
                        {String(project.teamName || '')}
                      </p>
                      {!!project.roundName && (
                        <Badge variant="secondary" className="mt-1 text-xs">
                          {String(project.roundName)}
                        </Badge>
                      )}
                    </div>
                    {project.evaluation ? (
                      <CheckCircle2 className="h-4 w-4 text-green-500 shrink-0" />
                    ) : (
                      <Clock className="h-4 w-4 text-muted-foreground shrink-0" />
                    )}
                  </div>
                </CardContent>
              </Card>
            )
          })}
        </div>
      )}

      {roundProjects.length === 0 && !loadingAssignments && (
        <Card>
          <CardContent className="flex flex-col items-center justify-center py-12 text-center">
            <GitCompare className="h-12 w-12 text-muted-foreground/50" />
            <p className="mt-2 font-medium">No projects assigned</p>
            <p className="text-sm text-muted-foreground">
              You need at least 2 assigned projects to use the comparison feature.
            </p>
          </CardContent>
        </Card>
      )}

      {/* Comparison view */}
      {comparing && loadingComparison && <CompareSkeleton />}

      {comparing && comparisonData && (
        <div
          className={`grid gap-4 grid-cols-1 ${
            selectedIds.length === 2 ? 'md:grid-cols-2' : 'md:grid-cols-2 lg:grid-cols-3'
          }`}
        >
          {(comparisonData as Array<{
            project: Record<string, unknown>
            evaluation: Record<string, unknown> | null
            assignmentId: string
          }>).map((item) => (
            <ComparisonCard
              key={String(item.project.id)}
              project={item.project}
              evaluation={item.evaluation}
            />
          ))}
        </div>
      )}
    </div>
  )
}

function ComparisonCard({
  project,
  evaluation,
}: {
  project: Record<string, unknown>
  evaluation: Record<string, unknown> | null
}) {
  const tags = Array.isArray(project.tags) ? project.tags : []
  const files = Array.isArray(project.files) ? project.files : []
  const scores = evaluation?.scores as Record<string, unknown> | undefined

  return (
    <Card>
      <CardHeader>
        <CardTitle className="text-lg">{String(project.title || 'Untitled')}</CardTitle>
        <CardDescription className="flex items-center gap-1">
          <Users className="h-3 w-3" />
          {String(project.teamName || 'N/A')}
        </CardDescription>
      </CardHeader>
      <CardContent className="space-y-4">
        {/* Country */}
        {!!project.country && (
          <div className="flex items-center gap-2 text-sm">
            <MapPin className="h-4 w-4 text-muted-foreground" />
            {String(project.country)}
          </div>
        )}

        {/* Description */}
        {!!project.description && (
          <div>
            <p className="text-xs font-medium text-muted-foreground mb-1">Description</p>
            <p className="text-sm line-clamp-4">{String(project.description)}</p>
          </div>
        )}

        {/* Tags */}
        {tags.length > 0 && (
          <div>
            <p className="text-xs font-medium text-muted-foreground mb-1">Tags</p>
            <div className="flex flex-wrap gap-1">
              {tags.map((tag: unknown, i: number) => (
                <Badge key={i} variant="secondary" className="text-xs">
                  {String(tag)}
                </Badge>
              ))}
            </div>
          </div>
        )}

        {/* Files */}
        {files.length > 0 && (
          <div>
            <p className="text-xs font-medium text-muted-foreground mb-1">
              Files ({files.length})
            </p>
            <div className="space-y-1">
              {files.map((file: unknown, i: number) => {
                const f = file as Record<string, unknown>
                return (
                  <div key={i} className="flex items-center gap-2 text-sm">
                    <FileText className="h-3 w-3 text-muted-foreground" />
                    <span className="truncate">{String(f.fileName || f.fileType || 'File')}</span>
                  </div>
                )
              })}
            </div>
          </div>
        )}

        {/* Evaluation scores */}
        {evaluation && (
          <div className="border-t pt-3">
            <p className="text-xs font-medium text-muted-foreground mb-2">Your Evaluation</p>
            {scores && typeof scores === 'object' ? (
              <div className="space-y-1">
                {Object.entries(scores).map(([criterion, score]) => (
                  <div key={criterion} className="flex items-center justify-between text-sm">
                    <span className="text-muted-foreground truncate">{criterion}</span>
                    <span className="font-medium tabular-nums">{String(score)}</span>
                  </div>
                ))}
              </div>
            ) : (
              <Badge variant="outline">
                <CheckCircle2 className="mr-1 h-3 w-3" />
                Submitted
              </Badge>
            )}
            {evaluation.globalScore != null && (
              <div className="mt-2 flex items-center justify-between font-medium text-sm border-t pt-2">
                <span>Overall Score</span>
                <span className="text-primary">{String(evaluation.globalScore)}</span>
              </div>
            )}
          </div>
        )}

        {!evaluation && (
          <div className="border-t pt-3">
            <Badge variant="outline">
              <Clock className="mr-1 h-3 w-3" />
              Not yet evaluated
            </Badge>
          </div>
        )}
      </CardContent>
    </Card>
  )
}

function CompareSkeleton() {
  return (
    <div className="space-y-6">
      <div className="flex items-center gap-4">
        <Skeleton className="h-9 w-36" />
      </div>
      <Skeleton className="h-8 w-64" />
      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
        {[1, 2, 3].map((i) => (
          <Card key={i}>
            <CardHeader>
              <Skeleton className="h-5 w-32" />
              <Skeleton className="h-4 w-24" />
            </CardHeader>
            <CardContent className="space-y-3">
              <Skeleton className="h-4 w-full" />
              <Skeleton className="h-4 w-3/4" />
              <Skeleton className="h-16 w-full" />
            </CardContent>
          </Card>
        ))}
      </div>
    </div>
  )
}
