import { Suspense } from 'react'
import Link from 'next/link'
import { notFound, redirect } from 'next/navigation'
import { auth } from '@/lib/auth'
import { prisma } from '@/lib/prisma'

export const dynamic = 'force-dynamic'
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Separator } from '@/components/ui/separator'
import { Skeleton } from '@/components/ui/skeleton'
import {
  ArrowLeft,
  CheckCircle2,
  ThumbsUp,
  ThumbsDown,
  Calendar,
  Users,
  Star,
  AlertCircle,
} from 'lucide-react'
import { format } from 'date-fns'

interface PageProps {
  params: Promise<{ id: string }>
}

interface Criterion {
  id: string
  label: string
  description?: string
  scale: number
  weight?: number
  required?: boolean
}

async function EvaluationContent({ projectId }: { projectId: string }) {
  const session = await auth()
  const userId = session?.user?.id

  if (!userId) {
    redirect('/login')
  }

  // Check if user is assigned to this project
  const assignment = await prisma.assignment.findFirst({
    where: {
      projectId,
      userId,
    },
    include: {
      evaluation: {
        include: {
          form: true,
        },
      },
      round: {
        include: {
          program: {
            select: { name: true },
          },
          evaluationForms: {
            where: { isActive: true },
            take: 1,
          },
        },
      },
    },
  })

  // Get project details
  const project = await prisma.project.findUnique({
    where: { id: projectId },
    select: {
      id: true,
      title: true,
      teamName: true,
    },
  })

  if (!project) {
    notFound()
  }

  if (!assignment) {
    return (
      <div className="space-y-6">
        <Button variant="ghost" asChild className="-ml-4">
          <Link href="/jury/assignments">
            <ArrowLeft className="mr-2 h-4 w-4" />
            Back to Assignments
          </Link>
        </Button>

        <Card>
          <CardContent className="flex flex-col items-center justify-center py-12 text-center">
            <AlertCircle className="h-12 w-12 text-destructive/50" />
            <p className="mt-2 font-medium text-destructive">Access Denied</p>
            <p className="text-sm text-muted-foreground">
              You are not assigned to evaluate this project
            </p>
          </CardContent>
        </Card>
      </div>
    )
  }

  const evaluation = assignment.evaluation

  if (!evaluation || evaluation.status === 'NOT_STARTED') {
    return (
      <div className="space-y-6">
        <Button variant="ghost" asChild className="-ml-4">
          <Link href={`/jury/projects/${projectId}`}>
            <ArrowLeft className="mr-2 h-4 w-4" />
            Back to Project
          </Link>
        </Button>

        <Card>
          <CardContent className="flex flex-col items-center justify-center py-12 text-center">
            <Star className="h-12 w-12 text-muted-foreground/50" />
            <p className="mt-2 font-medium">No Evaluation Found</p>
            <p className="text-sm text-muted-foreground">
              You haven&apos;t submitted an evaluation for this project yet.
            </p>
            <Button asChild className="mt-4">
              <Link href={`/jury/projects/${projectId}/evaluate`}>
                Start Evaluation
              </Link>
            </Button>
          </CardContent>
        </Card>
      </div>
    )
  }

  // Parse criteria from the evaluation form
  const criteria: Criterion[] =
    (evaluation.form.criteriaJson as unknown as Criterion[]) || []
  const criterionScores =
    (evaluation.criterionScoresJson as unknown as Record<string, number>) || {}

  const round = assignment.round

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

      {/* Header */}
      <div className="space-y-4">
        <div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
          <div className="space-y-1">
            <div className="flex items-center gap-2 text-sm text-muted-foreground">
              <span>{round.program.name}</span>
              <span>/</span>
              <span>{round.name}</span>
            </div>
            <h1 className="text-2xl font-semibold tracking-tight">
              My Evaluation: {project.title}
            </h1>
            {project.teamName && (
              <div className="flex items-center gap-2 text-muted-foreground">
                <Users className="h-4 w-4" />
                <span>{project.teamName}</span>
              </div>
            )}
          </div>

          <Badge
            variant="default"
            className="w-fit bg-green-600 hover:bg-green-700"
          >
            <CheckCircle2 className="mr-1 h-3 w-3" />
            {evaluation.status === 'LOCKED' ? 'Locked' : 'Submitted'}
          </Badge>
        </div>

        {evaluation.submittedAt && (
          <div className="flex items-center gap-2 text-sm text-muted-foreground">
            <Calendar className="h-4 w-4" />
            Submitted on {format(new Date(evaluation.submittedAt), 'PPP')} at{' '}
            {format(new Date(evaluation.submittedAt), 'p')}
          </div>
        )}
      </div>

      <Separator />

      {/* Criteria scores */}
      {criteria.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle className="text-lg">Criteria Scores</CardTitle>
            <CardDescription>
              Your ratings for each evaluation criterion
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            {criteria.map((criterion) => {
              const score = criterionScores[criterion.id]
              return (
                <div key={criterion.id} className="space-y-2">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="font-medium">{criterion.label}</p>
                      {criterion.description && (
                        <p className="text-sm text-muted-foreground">
                          {criterion.description}
                        </p>
                      )}
                    </div>
                    <div className="flex items-center gap-2">
                      <span className="text-2xl font-bold">{score}</span>
                      <span className="text-muted-foreground">
                        / {criterion.scale}
                      </span>
                    </div>
                  </div>
                  {/* Visual score bar */}
                  <div className="flex gap-1">
                    {Array.from(
                      { length: criterion.scale },
                      (_, i) => i + 1
                    ).map((num) => (
                      <div
                        key={num}
                        className={`h-2 flex-1 rounded-full ${
                          num <= score
                            ? 'bg-primary'
                            : 'bg-muted'
                        }`}
                      />
                    ))}
                  </div>
                </div>
              )
            })}
          </CardContent>
        </Card>
      )}

      {/* Global score */}
      <Card>
        <CardHeader>
          <CardTitle className="text-lg">Overall Score</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="flex items-center gap-4">
            <div className="flex h-20 w-20 items-center justify-center rounded-full bg-primary/10">
              <span className="text-3xl font-bold text-primary">
                {evaluation.globalScore}
              </span>
            </div>
            <div>
              <p className="text-lg font-medium">out of 10</p>
              <p className="text-sm text-muted-foreground">
                {evaluation.globalScore && evaluation.globalScore >= 8
                  ? 'Excellent'
                  : evaluation.globalScore && evaluation.globalScore >= 6
                    ? 'Good'
                    : evaluation.globalScore && evaluation.globalScore >= 4
                      ? 'Average'
                      : 'Below Average'}
              </p>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Recommendation */}
      <Card>
        <CardHeader>
          <CardTitle className="text-lg">Recommendation</CardTitle>
        </CardHeader>
        <CardContent>
          <div
            className={`flex items-center gap-3 rounded-lg p-4 ${
              evaluation.binaryDecision
                ? 'bg-green-500/10 text-green-700 dark:text-green-400'
                : 'bg-red-500/10 text-red-700 dark:text-red-400'
            }`}
          >
            {evaluation.binaryDecision ? (
              <>
                <ThumbsUp className="h-8 w-8" />
                <div>
                  <p className="font-semibold">Recommended to Advance</p>
                  <p className="text-sm opacity-80">
                    You voted YES for this project to advance to the next round
                  </p>
                </div>
              </>
            ) : (
              <>
                <ThumbsDown className="h-8 w-8" />
                <div>
                  <p className="font-semibold">Not Recommended</p>
                  <p className="text-sm opacity-80">
                    You voted NO for this project to advance
                  </p>
                </div>
              </>
            )}
          </div>
        </CardContent>
      </Card>

      {/* Feedback */}
      <Card>
        <CardHeader>
          <CardTitle className="text-lg">Written Feedback</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="rounded-lg bg-muted p-4">
            <p className="whitespace-pre-wrap">{evaluation.feedbackText}</p>
          </div>
        </CardContent>
      </Card>

      {/* Navigation */}
      <div className="flex justify-between">
        <Button variant="outline" asChild>
          <Link href={`/jury/projects/${projectId}`}>View Project Details</Link>
        </Button>
        <Button asChild>
          <Link href="/jury/assignments">Back to All Assignments</Link>
        </Button>
      </div>
    </div>
  )
}

function EvaluationSkeleton() {
  return (
    <div className="space-y-6">
      <Skeleton className="h-9 w-36" />

      <div className="space-y-2">
        <Skeleton className="h-4 w-48" />
        <Skeleton className="h-8 w-96" />
        <Skeleton className="h-4 w-32" />
      </div>

      <Skeleton className="h-px w-full" />

      <Card>
        <CardHeader>
          <Skeleton className="h-5 w-32" />
        </CardHeader>
        <CardContent className="space-y-4">
          {[1, 2, 3].map((i) => (
            <div key={i} className="space-y-2">
              <div className="flex justify-between">
                <Skeleton className="h-5 w-40" />
                <Skeleton className="h-8 w-16" />
              </div>
              <Skeleton className="h-2 w-full" />
            </div>
          ))}
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <Skeleton className="h-5 w-32" />
        </CardHeader>
        <CardContent>
          <Skeleton className="h-20 w-32 rounded-full" />
        </CardContent>
      </Card>
    </div>
  )
}

export default async function EvaluationViewPage({ params }: PageProps) {
  const { id } = await params

  return (
    <Suspense fallback={<EvaluationSkeleton />}>
      <EvaluationContent projectId={id} />
    </Suspense>
  )
}
