'use client'

import Link from 'next/link'
import { useSession } from 'next-auth/react'
import { trpc } from '@/lib/trpc/client'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card'
import { Skeleton } from '@/components/ui/skeleton'
import { StatusTracker } from '@/components/shared/status-tracker'
import {
  FileText,
  Calendar,
  Clock,
  AlertCircle,
  CheckCircle,
  LogIn,
  Eye,
  Users,
  Crown,
  UserPlus,
} from 'lucide-react'

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',
}

export function MySubmissionClient() {
  const { data: session, status: sessionStatus } = useSession()

  const { data: submissions, isLoading } = trpc.applicant.listMySubmissions.useQuery(
    undefined,
    { enabled: session?.user?.role === 'APPLICANT' }
  )

  // Not authenticated
  if (sessionStatus === 'unauthenticated') {
    return (
      <div className="max-w-2xl mx-auto">
        <Card>
          <CardContent className="flex flex-col items-center justify-center py-12">
            <LogIn className="h-12 w-12 text-muted-foreground/50 mb-4" />
            <h2 className="text-xl font-semibold mb-2">Sign In Required</h2>
            <p className="text-muted-foreground text-center mb-6">
              Please sign in to view your submissions.
            </p>
            <Button asChild>
              <Link href="/login">Sign In</Link>
            </Button>
          </CardContent>
        </Card>
      </div>
    )
  }

  // Loading session
  if (sessionStatus === 'loading' || isLoading) {
    return (
      <div className="max-w-4xl mx-auto space-y-6">
        <Skeleton className="h-8 w-48" />
        <Skeleton className="h-4 w-96" />
        <div className="space-y-4">
          {[1, 2].map((i) => (
            <Card key={i}>
              <CardContent className="p-6">
                <div className="flex justify-between">
                  <div className="space-y-2">
                    <Skeleton className="h-6 w-64" />
                    <Skeleton className="h-4 w-32" />
                  </div>
                  <Skeleton className="h-8 w-24" />
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      </div>
    )
  }

  // Not an applicant
  if (session?.user?.role !== 'APPLICANT') {
    return (
      <div className="max-w-2xl mx-auto">
        <Card>
          <CardContent className="flex flex-col items-center justify-center py-12">
            <AlertCircle className="h-12 w-12 text-warning mb-4" />
            <h2 className="text-xl font-semibold mb-2">Access Restricted</h2>
            <p className="text-muted-foreground text-center">
              This page is only available to applicants.
            </p>
          </CardContent>
        </Card>
      </div>
    )
  }

  return (
    <div className="max-w-4xl mx-auto space-y-6">
      {/* Header */}
      <div>
        <h1 className="text-2xl font-semibold tracking-tight">My Submissions</h1>
        <p className="text-muted-foreground">
          Track the status of your project submissions
        </p>
      </div>

      {/* Submissions list */}
      {!submissions || submissions.length === 0 ? (
        <Card>
          <CardContent className="flex flex-col items-center justify-center py-12">
            <FileText className="h-12 w-12 text-muted-foreground/50 mb-4" />
            <h2 className="text-xl font-semibold mb-2">No Submissions Yet</h2>
            <p className="text-muted-foreground text-center">
              You haven&apos;t submitted any projects yet.
            </p>
          </CardContent>
        </Card>
      ) : (
        <div className="space-y-4">
          {submissions.map((project) => {
            const projectStatus = project.status ?? 'SUBMITTED'
            const roundName = project.round?.name
            const programYear = project.round?.program?.year

            return (
            <Card key={project.id}>
              <CardHeader className="pb-3">
                <div className="flex items-start justify-between">
                  <div>
                    <CardTitle className="text-lg">{project.title}</CardTitle>
                    <CardDescription>
                      {programYear ? `${programYear} Edition` : ''}{roundName ? ` - ${roundName}` : ''}
                    </CardDescription>
                  </div>
                  <Badge variant={statusColors[projectStatus] || 'secondary'}>
                    {projectStatus.replace('_', ' ')}
                  </Badge>
                </div>
              </CardHeader>
              <CardContent className="space-y-4">
                {/* Meta info */}
                <div className="flex flex-wrap gap-4 text-sm text-muted-foreground">
                  <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">
                      <Clock className="h-4 w-4 text-orange-500" />
                      Draft - Not submitted
                    </div>
                  )}
                  <div className="flex items-center gap-1">
                    <FileText className="h-4 w-4" />
                    {project.files.length} file(s) uploaded
                  </div>
                  {'teamMembers' in project && project.teamMembers && (
                    <div className="flex items-center gap-1">
                      <Users className="h-4 w-4" />
                      {project.teamMembers.length} team member(s)
                    </div>
                  )}
                  {'isTeamLead' in project && project.isTeamLead && (
                    <div className="flex items-center gap-1">
                      <Crown className="h-4 w-4 text-yellow-500" />
                      Team Lead
                    </div>
                  )}
                </div>

                {/* Status timeline */}
                {project.submittedAt && (
                  <div className="pt-2">
                    <StatusTracker
                      timeline={[
                        {
                          status: 'SUBMITTED',
                          label: 'Submitted',
                          date: project.submittedAt,
                          completed: true,
                        },
                        {
                          status: 'UNDER_REVIEW',
                          label: 'Under Review',
                          date: null,
                          completed: ['UNDER_REVIEW', 'SEMIFINALIST', 'FINALIST', 'WINNER'].includes(projectStatus),
                        },
                        {
                          status: 'SEMIFINALIST',
                          label: 'Semi-finalist',
                          date: null,
                          completed: ['SEMIFINALIST', 'FINALIST', 'WINNER'].includes(projectStatus),
                        },
                        {
                          status: 'FINALIST',
                          label: 'Finalist',
                          date: null,
                          completed: ['FINALIST', 'WINNER'].includes(projectStatus),
                        },
                      ]}
                      currentStatus={projectStatus}
                      className="mt-4"
                    />
                  </div>
                )}

                {/* Actions */}
                <div className="flex gap-2 pt-2">
                  <Button variant="outline" size="sm" asChild>
                    <Link href={`/my-submission/${project.id}`}>
                      <Eye className="mr-2 h-4 w-4" />
                      View Details
                    </Link>
                  </Button>
                </div>
              </CardContent>
            </Card>
            )
          })}
        </div>
      )}
    </div>
  )
}
