'use client'

import { useParams, useRouter } from 'next/navigation'
import Link from 'next/link'
import type { Route } from 'next'
import { trpc } from '@/lib/trpc/client'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Skeleton } from '@/components/ui/skeleton'
import { MultiWindowDocViewer } from '@/components/jury/multi-window-doc-viewer'
import { ArrowLeft, FileText, Users, MapPin, Target, Tag } from 'lucide-react'
import { CountryDisplay } from '@/components/shared/country-display'

export default function JuryProjectDetailPage() {
  const params = useParams()
  const router = useRouter()
  const roundId = params.roundId as string
  const projectId = params.projectId as string

  const { data: project, isLoading } = trpc.project.get.useQuery(
    { id: projectId },
    { enabled: !!projectId }
  )

  const { data: round } = trpc.round.getById.useQuery(
    { id: roundId },
    { enabled: !!roundId }
  )

  // Round status is the primary gate for evaluations
  const isVotingOpen = round?.status === 'ROUND_ACTIVE'

  if (isLoading) {
    return (
      <div className="space-y-6">
        <Skeleton className="h-8 w-64" />
        <Skeleton className="h-48" />
        <Skeleton className="h-64" />
      </div>
    )
  }

  if (!project) {
    return (
      <div className="space-y-6">
        <Button variant="ghost" size="sm" onClick={() => router.back()}>
          <ArrowLeft className="mr-2 h-4 w-4" />
          Back
        </Button>
        <Card>
          <CardContent className="flex flex-col items-center justify-center py-12">
            <FileText className="h-12 w-12 text-muted-foreground/50 mb-3" />
            <p className="font-medium">Project not found</p>
          </CardContent>
        </Card>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center gap-4">
        <Button variant="ghost" size="sm" onClick={() => router.back()}>
          <ArrowLeft className="mr-2 h-4 w-4" />
          Back
        </Button>
      </div>

      <Card>
        <CardHeader>
          <div className="flex items-start justify-between flex-wrap gap-4">
            <div>
              <CardTitle className="text-2xl">{project.title}</CardTitle>
              {project.teamName && (
                <p className="text-muted-foreground mt-1">{project.teamName}</p>
              )}
            </div>
            {isVotingOpen ? (
              <Button asChild className="bg-brand-blue hover:bg-brand-blue-light">
                <Link href={`/jury/competitions/${roundId}/projects/${projectId}/evaluate` as Route}>
                  <Target className="mr-2 h-4 w-4" />
                  Evaluate Project
                </Link>
              </Button>
            ) : (
              <Badge variant="outline" className="text-muted-foreground">
                Voting not open
              </Badge>
            )}
          </div>
        </CardHeader>
        <CardContent className="space-y-6">
          {/* Project metadata */}
          <div className="flex flex-wrap gap-3">
            {project.competitionCategory && (
              <Badge
                variant="secondary"
                className={
                  project.competitionCategory === 'STARTUP'
                    ? 'bg-violet-100 text-violet-700 border-violet-200'
                    : 'bg-sky-100 text-sky-700 border-sky-200'
                }
              >
                {project.competitionCategory === 'STARTUP' ? 'Startup' : 'Business Concept'}
              </Badge>
            )}
            {project.country && (
              <Badge variant="outline" className="gap-1">
                <MapPin className="h-3 w-3" />
                <CountryDisplay country={project.country} />
              </Badge>
            )}
          </div>

          {/* Project tags */}
          {((project.projectTags && project.projectTags.length > 0) ||
            (project.tags && project.tags.length > 0)) && (
            <div>
              <h3 className="font-semibold mb-2 flex items-center gap-2">
                <Tag className="h-4 w-4" />
                Tags
              </h3>
              <div className="flex flex-wrap gap-2">
                {project.projectTags && project.projectTags.length > 0
                  ? project.projectTags.map((pt: any) => (
                      <Badge
                        key={pt.id}
                        variant="secondary"
                        style={pt.tag.color ? { backgroundColor: pt.tag.color + '20', borderColor: pt.tag.color, color: pt.tag.color } : undefined}
                        className="text-xs"
                      >
                        {pt.tag.name}
                        {pt.tag.category && (
                          <span className="ml-1 opacity-60">({pt.tag.category})</span>
                        )}
                      </Badge>
                    ))
                  : project.tags.map((tag: string) => (
                      <Badge key={tag} variant="secondary" className="text-xs">
                        {tag}
                      </Badge>
                    ))
                }
              </div>
            </div>
          )}

          {/* Description */}
          {project.description && (
            <div>
              <h3 className="font-semibold mb-2">Description</h3>
              <p className="text-muted-foreground whitespace-pre-wrap">
                {project.description}
              </p>
            </div>
          )}

          {/* Team members */}
          {project.teamMembers && project.teamMembers.length > 0 && (
            <div>
              <h3 className="font-semibold mb-3 flex items-center gap-2">
                <Users className="h-4 w-4" />
                Team Members ({project.teamMembers.length})
              </h3>
              <div className="grid gap-2 sm:grid-cols-2">
                {project.teamMembers.map((member: any) => (
                  <div
                    key={member.id}
                    className="flex items-center gap-3 p-3 rounded-lg border"
                  >
                    <div className="flex h-8 w-8 items-center justify-center rounded-full bg-brand-blue/10 text-brand-blue font-semibold text-sm">
                      {member.user.name?.charAt(0).toUpperCase() || '?'}
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="font-medium text-sm truncate">
                        {member.user.name || member.user.email}
                      </p>
                      <p className="text-xs text-muted-foreground">
                        {member.role === 'LEAD' ? 'Team Lead' : member.role}
                      </p>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Documents */}
      <MultiWindowDocViewer roundId={roundId} projectId={projectId} />
    </div>
  )
}
