'use client'

import { useState, useEffect } from 'react'
import { useSession } from 'next-auth/react'
import Link from 'next/link'
import type { Route } from 'next'
import { trpc } from '@/lib/trpc/client'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from '@/components/ui/card'
import { Skeleton } from '@/components/ui/skeleton'
import { Textarea } from '@/components/ui/textarea'
import { CompetitionTimelineSidebar } from '@/components/applicant/competition-timeline'
import { MentoringRequestCard } from '@/components/applicant/mentoring-request-card'
import { MentorConversationCard } from '@/components/applicant/mentor-conversation-card'
import { AttendingMembersCard } from '@/components/applicant/attending-members-card'
import { LunchBanner } from '@/components/applicant/lunch-banner'
import { ExternalAttendeesStrip } from '@/components/applicant/external-attendees-strip'
import { AnimatedCard } from '@/components/shared/animated-container'
import { ProjectLogoUpload } from '@/components/shared/project-logo-upload'
import { Progress } from '@/components/ui/progress'
import {
  FileText,
  Calendar,
  CheckCircle,
  Users,
  Crown,
  MessageSquare,
  Upload,
  ArrowRight,
  Star,
  AlertCircle,
  Pencil,
  Loader2,
  Check,
  X,
  UserCircle,
  Trophy,
  Vote,
  Clock,
} from 'lucide-react'
import { toast } from 'sonner'

function formatCountdown(ms: number): string {
  if (ms <= 0) return 'Closed'
  const days = Math.floor(ms / (1000 * 60 * 60 * 24))
  const hours = Math.floor((ms % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
  const minutes = Math.floor((ms % (1000 * 60 * 60)) / (1000 * 60))
  const parts: string[] = []
  if (days > 0) parts.push(`${days}d`)
  if (hours > 0) parts.push(`${hours}h`)
  parts.push(`${minutes}m`)
  return parts.join(' ')
}

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

// Keys to hide from the metadata display (shown elsewhere or internal)
const HIDDEN_METADATA_KEYS = new Set(['TeamMembers', 'teammembers', 'team_members'])

export default function ApplicantDashboardPage() {
  const { data: session, status: sessionStatus } = useSession()
  const isAuthenticated = sessionStatus === 'authenticated'
  const utils = trpc.useUtils()

  const { data, isLoading } = trpc.applicant.getMyDashboard.useQuery(undefined, {
    enabled: isAuthenticated,
  })

  const { data: deadlines } = trpc.applicant.getUpcomingDeadlines.useQuery(undefined, {
    enabled: isAuthenticated,
  })

  const { data: docCompleteness } = trpc.applicant.getDocumentCompleteness.useQuery(undefined, {
    enabled: isAuthenticated,
  })

  const { data: evaluations } = trpc.applicant.getMyEvaluations.useQuery(undefined, {
    enabled: isAuthenticated,
  })

  const { data: flags } = trpc.settings.getFeatureFlags.useQuery(undefined, {
    enabled: isAuthenticated,
  })

  // Live countdown timer for open rounds
  const [now, setNow] = useState(() => Date.now())
  useEffect(() => {
    const interval = setInterval(() => setNow(Date.now()), 60_000)
    return () => clearInterval(interval)
  }, [])

  if (sessionStatus === 'loading' || (isAuthenticated && isLoading)) {
    return (
      <div className="space-y-6">
        <div className="space-y-2">
          <Skeleton className="h-8 w-64" />
          <Skeleton className="h-4 w-96" />
        </div>
        <div className="grid gap-6 lg:grid-cols-3">
          <div className="lg:col-span-2 space-y-6">
            <Skeleton className="h-48 w-full" />
            <Skeleton className="h-32 w-full" />
          </div>
          <div className="space-y-6">
            <Skeleton className="h-64 w-full" />
            <Skeleton className="h-48 w-full" />
          </div>
        </div>
      </div>
    )
  }

  // No project yet
  if (!data?.project) {
    return (
      <div className="space-y-6">
        <div>
          <h1 className="text-2xl font-semibold tracking-tight">My Project</h1>
          <p className="text-muted-foreground">
            Your applicant dashboard
          </p>
        </div>
        <AnimatedCard index={0}>
          <Card>
            <CardContent className="flex flex-col items-center justify-center py-12">
              <div className="rounded-2xl bg-muted/60 p-4 mb-4">
                <FileText className="h-8 w-8 text-muted-foreground/70" />
              </div>
              <h2 className="text-xl font-semibold mb-2">No Project Yet</h2>
              <p className="text-muted-foreground text-center max-w-md">
                You haven&apos;t submitted a project yet. Check for open application rounds
                on the MOPC website.
              </p>
            </CardContent>
          </Card>
        </AnimatedCard>
      </div>
    )
  }

  const { project, timeline, currentStatus, openRounds, hasPassedIntake, isRejected } = data
  const programYear = project.program?.year
  const programName = project.program?.name
  const totalEvaluations = evaluations?.reduce((sum, r) => sum + r.evaluationCount, 0) ?? 0
  const canEditDescription = flags?.applicantAllowDescriptionEdit && !isRejected

  return (
    <div className="space-y-6">
      {/* Header — no withdraw button here */}
      <div className="flex items-start justify-between flex-wrap gap-4">
        <div className="flex items-center gap-4">
          {/* Project logo — clickable for any team member to change */}
          <ProjectLogoUpload
            projectId={project.id}
            currentLogoUrl={data.logoUrl}
            onUploadComplete={() => utils.applicant.getMyDashboard.invalidate()}
          >
            <button
              type="button"
              className="group relative shrink-0 flex flex-col items-center gap-1 cursor-pointer"
            >
              <div className="relative h-14 w-14 rounded-xl border bg-muted/50 flex items-center justify-center overflow-hidden hover:ring-2 hover:ring-primary/30 transition-all">
                {data.logoUrl ? (
                  <img src={data.logoUrl} alt={project.title} className="h-full w-full object-cover" />
                ) : (
                  <FileText className="h-7 w-7 text-muted-foreground/60" />
                )}
                <div className="absolute inset-0 bg-black/0 group-hover:bg-black/40 transition-colors flex items-center justify-center">
                  <Pencil className="h-4 w-4 text-white opacity-0 group-hover:opacity-100 transition-opacity" />
                </div>
              </div>
              <span className="text-[10px] text-primary/70 group-hover:text-primary transition-colors">
                {data.logoUrl ? 'Change' : 'Add logo'}
              </span>
            </button>
          </ProjectLogoUpload>
          <div>
            <div className="flex items-center gap-3">
              <h1 className="text-2xl font-semibold tracking-tight">{project.title}</h1>
              {currentStatus && (
                <Badge variant={statusColors[currentStatus] || 'secondary'}>
                  {currentStatus.replace('_', ' ')}
                </Badge>
              )}
            </div>
            <p className="text-muted-foreground">
              {programYear ? `${programYear} Edition` : ''}{programName ? ` - ${programName}` : ''}
            </p>
          </div>
        </div>
      </div>

      {/* Active round deadline banner */}
      {!isRejected && openRounds.length > 0 && (() => {
        const submissionTypes = new Set(['INTAKE', 'SUBMISSION', 'MENTORING'])
        const roundsWithDeadline = openRounds.filter((r) => r.windowCloseAt && submissionTypes.has(r.roundType))
        if (roundsWithDeadline.length === 0) return null
        return roundsWithDeadline.map((round) => {
          const closeAt = new Date(round.windowCloseAt!).getTime()
          const remaining = closeAt - now
          const isUrgent = remaining > 0 && remaining < 1000 * 60 * 60 * 24 * 3 // < 3 days
          return (
            <div
              key={round.id}
              className={`flex flex-col sm:flex-row items-start sm:items-center gap-3 rounded-lg border px-4 py-3 ${
                isUrgent
                  ? 'border-amber-500/50 bg-amber-50 dark:bg-amber-950/20'
                  : 'border-primary/20 bg-primary/5'
              }`}
            >
              <div className="flex items-center gap-2 min-w-0">
                <Clock className={`h-4 w-4 shrink-0 ${isUrgent ? 'text-amber-600 dark:text-amber-400' : 'text-primary'}`} />
                <span className="font-medium text-sm truncate">{round.name}</span>
                <Badge variant={isUrgent ? 'warning' : 'default'} className="shrink-0">
                  {remaining > 0 ? formatCountdown(remaining) + ' left' : 'Closed'}
                </Badge>
              </div>
              <span className="text-xs text-muted-foreground sm:ml-auto shrink-0">
                Closes {new Date(round.windowCloseAt!).toLocaleDateString(undefined, {
                  weekday: 'short',
                  month: 'short',
                  day: 'numeric',
                  year: 'numeric',
                })}{' '}
                at {new Date(round.windowCloseAt!).toLocaleTimeString(undefined, {
                  hour: '2-digit',
                  minute: '2-digit',
                })}
              </span>
            </div>
          )
        })
      })()}

      <div className="grid gap-6 lg:grid-cols-3">
        {/* Main content */}
        <div className="lg:col-span-2 space-y-6">
          {/* Project details */}
          <AnimatedCard index={0}>
          <Card>
            <CardHeader>
              <CardTitle>Project Details</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              {project.teamName && (
                <div>
                  <p className="text-sm font-medium text-muted-foreground">Team/Organization</p>
                  <p>{project.teamName}</p>
                </div>
              )}
              {/* Description — editable if admin allows */}
              {project.description && !canEditDescription && (
                <div>
                  <p className="text-sm font-medium text-muted-foreground">Description</p>
                  <p className="whitespace-pre-wrap">{project.description}</p>
                </div>
              )}
              {canEditDescription && (
                <EditableDescription
                  projectId={project.id}
                  initialDescription={project.description || ''}
                />
              )}
              {project.tags && project.tags.length > 0 && (
                <div>
                  <p className="text-sm font-medium text-muted-foreground mb-2">Tags</p>
                  <div className="flex flex-wrap gap-2">
                    {project.tags.map((tag) => (
                      <Badge key={tag} variant="outline">
                        {tag}
                      </Badge>
                    ))}
                  </div>
                </div>
              )}

              {/* Metadata — filter out team members (shown in sidebar) */}
              {project.metadataJson && (() => {
                const entries = Object.entries(project.metadataJson as Record<string, unknown>)
                  .filter(([key]) => !HIDDEN_METADATA_KEYS.has(key))
                if (entries.length === 0) return null
                return (
                  <div className="border-t pt-4 mt-4">
                    <p className="text-sm font-medium text-muted-foreground mb-3">Additional Information</p>
                    <dl className="space-y-2">
                      {entries.map(([key, value]) => (
                        <div key={key} className="flex justify-between gap-4">
                          <dt className="text-sm text-muted-foreground capitalize shrink-0">
                            {key.replace(/_/g, ' ')}
                          </dt>
                          <dd className="text-sm font-medium text-right">{String(value)}</dd>
                        </div>
                      ))}
                    </dl>
                  </div>
                )
              })()}

              {/* Meta info row */}
              <div className="flex flex-wrap gap-4 text-sm text-muted-foreground border-t pt-4 mt-4">
                <div className="flex items-center gap-1">
                  <Calendar className="h-4 w-4" />
                  Created {new Date(project.createdAt).toLocaleDateString()}
                </div>
                {project.submittedAt && (
                  <div className="flex items-center gap-1">
                    <CheckCircle className="h-4 w-4 text-green-500" />
                    Submitted {new Date(project.submittedAt).toLocaleDateString()}
                  </div>
                )}
                <div className="flex items-center gap-1">
                  <FileText className="h-4 w-4" />
                  {project.files.length} file(s)
                </div>
              </div>
            </CardContent>
          </Card>
          </AnimatedCard>

          {/* Rejected banner */}
          {isRejected && (
            <AnimatedCard index={1}>
              <Card className="border-destructive/50 bg-destructive/5">
                <CardContent className="flex items-center gap-3 py-4">
                  <AlertCircle className="h-5 w-5 text-destructive shrink-0" />
                  <p className="text-sm text-destructive">
                    Your project was not selected to advance. Your project space is now read-only.
                  </p>
                </CardContent>
              </Card>
            </AnimatedCard>
          )}


          {/* Document Completeness */}
          {docCompleteness && docCompleteness.length > 0 && (
            <AnimatedCard index={2}>
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <FileText className="h-5 w-5" />
                    Document Progress
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  {docCompleteness.map((dc) => (
                    <div key={dc.roundId}>
                      <div className="flex items-center justify-between text-sm mb-1.5">
                        <span className="font-medium">{dc.roundName}</span>
                        <span className="text-muted-foreground">
                          {dc.uploaded}/{dc.required} files
                        </span>
                      </div>
                      <div className="h-2 rounded-full bg-muted overflow-hidden">
                        <div
                          className="h-full rounded-full bg-primary transition-all"
                          style={{ width: `${dc.required > 0 ? Math.round((dc.uploaded / dc.required) * 100) : 0}%` }}
                        />
                      </div>
                    </div>
                  ))}
                </CardContent>
              </Card>
            </AnimatedCard>
          )}
        </div>

        {/* Sidebar */}
        <div className="space-y-6">
          {/* Competition timeline */}
          <AnimatedCard index={3}>
          <Card>
            <CardHeader>
              <CardTitle>Status Timeline</CardTitle>
            </CardHeader>
            <CardContent>
              <CompetitionTimelineSidebar />
            </CardContent>
          </Card>
          </AnimatedCard>

          {/* Mentoring Request Card */}
          {project.isTeamLead && openRounds.filter((r) => r.roundType === 'MENTORING').map((mentoringRound) => (
            <AnimatedCard key={mentoringRound.id} index={4}>
              <MentoringRequestCard
                projectId={project.id}
                roundId={mentoringRound.id}
                roundName={mentoringRound.name}
              />
            </AnimatedCard>
          ))}

          {/* Lunch banner (auto-hides when lunch event disabled or unconfigured) */}
          <LunchBanner programId={project.programId} />

          {/* External lunch attendees attached to this team (auto-hides if none) */}
          <ExternalAttendeesStrip projectId={project.id} />

          {/* Grand finale attendee roster (auto-hides until confirmation status is CONFIRMED) */}
          <AttendingMembersCard />

          {/* Conversation with assigned mentor (auto-hides when no mentor assigned) */}
          <MentorConversationCard projectId={project.id} />


          {/* Jury Feedback Card */}
          {totalEvaluations > 0 && (
            <AnimatedCard index={4}>
              <Card>
                <CardHeader>
                  <div className="flex items-center justify-between">
                    <CardTitle className="flex items-center gap-2">
                      <div className="rounded-lg bg-yellow-500/10 p-1.5">
                        <Star className="h-4 w-4 text-yellow-500" />
                      </div>
                      Jury Feedback
                    </CardTitle>
                    <Button variant="ghost" size="sm" asChild>
                      <Link href={"/applicant/evaluations" as Route}>
                        View All
                      </Link>
                    </Button>
                  </div>
                </CardHeader>
                <CardContent className="space-y-3">
                  {evaluations?.map((round) => {
                    const scores = round.evaluations
                      .map((ev) => ev.globalScore)
                      .filter((s): s is number => s !== null)
                    const avgScore = scores.length > 0
                      ? scores.reduce((a, b) => a + b, 0) / scores.length
                      : null
                    const maxScore = round.roundType === 'LIVE_FINAL' ? 10 : 100
                    const pct = avgScore !== null ? (avgScore / maxScore) * 100 : 0
                    const roundIcon = round.roundType === 'LIVE_FINAL'
                      ? <Trophy className="h-3.5 w-3.5 text-amber-500" />
                      : round.roundType === 'DELIBERATION'
                        ? <Vote className="h-3.5 w-3.5 text-violet-500" />
                        : <Star className="h-3.5 w-3.5 text-yellow-500" />

                    return (
                      <div key={round.roundId} className="rounded-lg border p-3 space-y-2">
                        <div className="flex items-center justify-between">
                          <span className="flex items-center gap-1.5 text-sm font-medium">
                            {roundIcon}
                            {round.roundName}
                          </span>
                          <Badge variant="secondary" className="text-xs">
                            {round.evaluationCount} review{round.evaluationCount !== 1 ? 's' : ''}
                          </Badge>
                        </div>
                        {avgScore !== null && (
                          <div className="space-y-1">
                            <div className="flex items-center justify-between text-xs text-muted-foreground">
                              <span>Avg Score</span>
                              <span className="font-semibold text-foreground tabular-nums">
                                {avgScore.toFixed(1)}<span className="text-muted-foreground font-normal"> / {maxScore}</span>
                              </span>
                            </div>
                            <Progress value={pct} className="h-1.5" />
                          </div>
                        )}
                      </div>
                    )
                  })}
                </CardContent>
              </Card>
            </AnimatedCard>
          )}

          {/* Team overview — proper cards */}
          <AnimatedCard index={5}>
          <Card>
            <CardHeader>
              <div className="flex items-center justify-between">
                <CardTitle className="flex items-center gap-2">
                  <Users className="h-5 w-5" />
                  Team
                </CardTitle>
                <Button variant="ghost" size="sm" asChild>
                  <Link href={"/applicant/team" as Route}>
                    Manage
                  </Link>
                </Button>
              </div>
            </CardHeader>
            <CardContent className="space-y-2">
              {project.teamMembers.length > 0 ? (
                project.teamMembers.slice(0, 5).map((member) => (
                  <div key={member.id} className="flex items-center gap-3 rounded-lg border p-2.5">
                    <div className="flex h-8 w-8 items-center justify-center rounded-full bg-muted shrink-0">
                      {member.role === 'LEAD' ? (
                        <Crown className="h-4 w-4 text-amber-500" />
                      ) : (
                        <UserCircle className="h-4 w-4 text-muted-foreground" />
                      )}
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="text-sm font-medium truncate">
                        {member.user.name || member.user.email}
                      </p>
                    </div>
                    <Badge variant="outline" className="shrink-0 text-[10px] px-1.5 py-0">
                      {member.role === 'LEAD' ? 'Lead' : member.role === 'ADVISOR' ? 'Advisor' : 'Member'}
                    </Badge>
                  </div>
                ))
              ) : (
                <p className="text-sm text-muted-foreground text-center py-2">
                  No team members yet
                </p>
              )}
              {project.teamMembers.length > 5 && (
                <p className="text-xs text-muted-foreground text-center">
                  +{project.teamMembers.length - 5} more
                </p>
              )}
            </CardContent>
          </Card>
          </AnimatedCard>

          {/* Upcoming Deadlines */}
          {deadlines && deadlines.length > 0 && (
            <AnimatedCard index={6}>
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <AlertCircle className="h-5 w-5" />
                    Upcoming Deadlines
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-3">
                  {deadlines.map((dl, i) => (
                    <div key={i} className="flex items-center justify-between text-sm">
                      <span className="font-medium truncate mr-2">{dl.roundName}</span>
                      <span className="text-muted-foreground shrink-0">
                        {new Date(dl.windowCloseAt).toLocaleDateString()}
                      </span>
                    </div>
                  ))}
                </CardContent>
              </Card>
            </AnimatedCard>
          )}

          {/* Key dates */}
          <AnimatedCard index={7}>
          <Card>
            <CardHeader>
              <CardTitle>Key Dates</CardTitle>
            </CardHeader>
            <CardContent className="space-y-3">
              <div className="flex items-center justify-between text-sm">
                <span className="text-muted-foreground">Created</span>
                <span>{new Date(project.createdAt).toLocaleDateString()}</span>
              </div>
              {project.submittedAt && (
                <div className="flex items-center justify-between text-sm">
                  <span className="text-muted-foreground">Submitted</span>
                  <span>{new Date(project.submittedAt).toLocaleDateString()}</span>
                </div>
              )}
              <div className="flex items-center justify-between text-sm">
                <span className="text-muted-foreground">Last Updated</span>
                <span>{new Date(project.updatedAt).toLocaleDateString()}</span>
              </div>
            </CardContent>
          </Card>
          </AnimatedCard>
        </div>
      </div>
    </div>
  )
}

function EditableDescription({ projectId, initialDescription }: { projectId: string; initialDescription: string }) {
  const [isEditing, setIsEditing] = useState(false)
  const [description, setDescription] = useState(initialDescription)
  const utils = trpc.useUtils()

  const mutation = trpc.applicant.updateDescription.useMutation({
    onSuccess: () => {
      utils.applicant.getMyDashboard.invalidate()
      setIsEditing(false)
      toast.success('Description updated')
    },
    onError: (e) => toast.error(e.message),
  })

  const handleSave = () => {
    mutation.mutate({ projectId, description })
  }

  const handleCancel = () => {
    setDescription(initialDescription)
    setIsEditing(false)
  }

  if (!isEditing) {
    return (
      <div>
        <div className="flex items-center justify-between mb-1">
          <p className="text-sm font-medium text-muted-foreground">Description</p>
          <Button variant="ghost" size="sm" className="h-6 px-2 text-xs gap-1" onClick={() => setIsEditing(true)}>
            <Pencil className="h-3 w-3" />
            Edit
          </Button>
        </div>
        <p className="whitespace-pre-wrap">{initialDescription || <span className="text-muted-foreground italic">No description yet. Click Edit to add one.</span>}</p>
      </div>
    )
  }

  return (
    <div>
      <p className="text-sm font-medium text-muted-foreground mb-1">Description</p>
      <Textarea
        value={description}
        onChange={(e) => setDescription(e.target.value)}
        rows={6}
        className="mb-2"
        disabled={mutation.isPending}
      />
      <div className="flex items-center gap-2 justify-end">
        <Button variant="ghost" size="sm" onClick={handleCancel} disabled={mutation.isPending}>
          <X className="h-3.5 w-3.5 mr-1" />
          Cancel
        </Button>
        <Button size="sm" onClick={handleSave} disabled={mutation.isPending}>
          {mutation.isPending ? (
            <Loader2 className="h-3.5 w-3.5 mr-1 animate-spin" />
          ) : (
            <Check className="h-3.5 w-3.5 mr-1" />
          )}
          Save
        </Button>
      </div>
    </div>
  )
}
