'use client'

import Link from 'next/link'
import type { Route } from 'next'
import { trpc } from '@/lib/trpc/client'
import {
  Card,
  CardContent,
  CardDescription,
  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 { Avatar, AvatarFallback } from '@/components/ui/avatar'
import {
  Users,
  Briefcase,
  ArrowRight,
  Mail,
  MapPin,
  GraduationCap,
  Waves,
  Crown,
} from 'lucide-react'
import { getInitials, formatDateOnly } from '@/lib/utils'

// Status badge colors
const statusColors: Record<string, 'default' | 'secondary' | 'destructive' | 'outline'> = {
  SUBMITTED: 'secondary',
  ELIGIBLE: 'default',
  ASSIGNED: 'default',
  SEMIFINALIST: 'default',
  FINALIST: 'default',
  REJECTED: 'destructive',
}

function DashboardSkeleton() {
  return (
    <div className="space-y-6">
      <div>
        <Skeleton className="h-8 w-48" />
        <Skeleton className="h-4 w-64 mt-2" />
      </div>

      <div className="grid gap-4 md:grid-cols-2">
        <Skeleton className="h-24" />
        <Skeleton className="h-24" />
      </div>

      <Skeleton className="h-6 w-32" />
      <div className="grid gap-4">
        <Skeleton className="h-40" />
        <Skeleton className="h-40" />
      </div>
    </div>
  )
}

export default function MentorDashboard() {
  const { data: assignments, isLoading } = trpc.mentor.getMyProjects.useQuery()

  if (isLoading) {
    return <DashboardSkeleton />
  }

  const projects = assignments || []

  return (
    <div className="space-y-6">
      {/* Header */}
      <div>
        <h1 className="text-2xl font-semibold tracking-tight">
          Mentor Dashboard
        </h1>
        <p className="text-muted-foreground">
          View and manage your assigned mentee projects
        </p>
      </div>

      {/* Stats */}
      <div className="grid gap-4 md:grid-cols-2">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">
              Assigned Projects
            </CardTitle>
            <Briefcase className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{projects.length}</div>
            <p className="text-xs text-muted-foreground">
              Projects you are mentoring
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">
              Total Team Members
            </CardTitle>
            <Users className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {projects.reduce(
                (acc, a) => acc + (a.project.teamMembers?.length || 0),
                0
              )}
            </div>
            <p className="text-xs text-muted-foreground">
              Across all assigned projects
            </p>
          </CardContent>
        </Card>
      </div>

      {/* Projects List */}
      <div>
        <h2 className="text-lg font-semibold mb-4">Your Mentees</h2>

        {projects.length === 0 ? (
          <Card>
            <CardContent className="flex flex-col items-center justify-center py-12 text-center">
              <div className="flex h-12 w-12 items-center justify-center rounded-full bg-muted">
                <Users className="h-6 w-6 text-muted-foreground" />
              </div>
              <p className="mt-4 font-medium">No assigned projects yet</p>
              <p className="text-sm text-muted-foreground mt-1">
                You will see your mentee projects here once they are assigned to
                you.
              </p>
            </CardContent>
          </Card>
        ) : (
          <div className="grid gap-4">
            {projects.map((assignment) => {
              const project = assignment.project
              const teamLead = project.teamMembers?.find(
                (m) => m.role === 'LEAD'
              )

              return (
                <Card key={assignment.id}>
                  <CardHeader>
                    <div className="flex flex-col gap-2 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>
                            {project.program.year} Edition
                          </span>
                          {project.roundProjects?.[0]?.round && (
                            <>
                              <span>•</span>
                              <span>{project.roundProjects[0].round.name}</span>
                            </>
                          )}
                        </div>
                        <CardTitle className="flex items-center gap-2">
                          {project.title}
                          {project.roundProjects?.[0]?.status && (
                            <Badge
                              variant={statusColors[project.roundProjects[0].status] || 'secondary'}
                            >
                              {project.roundProjects[0].status.replace('_', ' ')}
                            </Badge>
                          )}
                        </CardTitle>
                        {project.teamName && (
                          <CardDescription>{project.teamName}</CardDescription>
                        )}
                      </div>
                      <Button variant="outline" size="sm" asChild>
                        <Link href={`/mentor/projects/${project.id}` as Route}>
                          View Details
                          <ArrowRight className="ml-2 h-4 w-4" />
                        </Link>
                      </Button>
                    </div>
                  </CardHeader>
                  <CardContent className="space-y-4">
                    {/* Category badges */}
                    <div className="flex flex-wrap gap-2">
                      {project.competitionCategory && (
                        <Badge variant="outline" className="gap-1">
                          <GraduationCap className="h-3 w-3" />
                          {project.competitionCategory === 'STARTUP'
                            ? 'Start-up'
                            : 'Business Concept'}
                        </Badge>
                      )}
                      {project.oceanIssue && (
                        <Badge variant="outline" className="gap-1">
                          <Waves className="h-3 w-3" />
                          {project.oceanIssue.replace(/_/g, ' ')}
                        </Badge>
                      )}
                      {project.country && (
                        <Badge variant="outline" className="gap-1">
                          <MapPin className="h-3 w-3" />
                          {project.country}
                        </Badge>
                      )}
                    </div>

                    {/* Description preview */}
                    {project.description && (
                      <p className="text-sm text-muted-foreground line-clamp-2">
                        {project.description}
                      </p>
                    )}

                    {/* Team Lead Info */}
                    {teamLead && (
                      <div className="flex items-center gap-3 pt-2 border-t">
                        <Avatar className="h-8 w-8">
                          <AvatarFallback className="text-xs">
                            <Crown className="h-4 w-4 text-yellow-500" />
                          </AvatarFallback>
                        </Avatar>
                        <div className="flex-1 min-w-0">
                          <p className="text-sm font-medium">
                            {teamLead.user.name || 'Unnamed'}{' '}
                            <span className="text-muted-foreground font-normal">
                              (Team Lead)
                            </span>
                          </p>
                          <a
                            href={`mailto:${teamLead.user.email}`}
                            className="text-xs text-muted-foreground hover:text-primary flex items-center gap-1"
                          >
                            <Mail className="h-3 w-3" />
                            {teamLead.user.email}
                          </a>
                        </div>
                        <div className="text-xs text-muted-foreground">
                          {project.teamMembers?.length || 0} team member
                          {(project.teamMembers?.length || 0) !== 1 ? 's' : ''}
                        </div>
                      </div>
                    )}

                    {/* Assignment date */}
                    <p className="text-xs text-muted-foreground">
                      Assigned {formatDateOnly(assignment.assignedAt)}
                    </p>
                  </CardContent>
                </Card>
              )
            })}
          </div>
        )}
      </div>
    </div>
  )
}
