import { Suspense } from 'react'
import Link from 'next/link'
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 { Skeleton } from '@/components/ui/skeleton'
import { UserAvatar } from '@/components/shared/user-avatar'
import { getUserAvatarUrl } from '@/server/utils/avatar-url'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import type { Route } from 'next'
import { Plus, GraduationCap, Eye } from 'lucide-react'
import { formatDate } from '@/lib/utils'

async function MentorsContent() {
  const mentors = await prisma.user.findMany({
    where: {
      role: 'MENTOR',
    },
    include: {
      _count: {
        select: {
          mentorAssignments: true,
        },
      },
    },
    orderBy: [{ status: 'asc' }, { name: 'asc' }],
  })

  // Generate avatar URLs
  const mentorsWithAvatars = await Promise.all(
    mentors.map(async (mentor) => ({
      ...mentor,
      avatarUrl: await getUserAvatarUrl(mentor.profileImageKey, mentor.profileImageProvider),
    }))
  )

  if (mentorsWithAvatars.length === 0) {
    return (
      <Card>
        <CardContent className="flex flex-col items-center justify-center py-12 text-center">
          <GraduationCap className="h-12 w-12 text-muted-foreground/50" />
          <p className="mt-2 font-medium">No mentors yet</p>
          <p className="text-sm text-muted-foreground">
            Invite mentors to start matching them with projects
          </p>
          <Button asChild className="mt-4">
            <Link href="/admin/users/invite">
              <Plus className="mr-2 h-4 w-4" />
              Invite Mentor
            </Link>
          </Button>
        </CardContent>
      </Card>
    )
  }

  const statusColors: Record<string, 'default' | 'success' | 'secondary' | 'destructive'> = {
    ACTIVE: 'success',
    INVITED: 'secondary',
    SUSPENDED: 'destructive',
  }

  return (
    <>
      {/* Desktop table view */}
      <Card className="hidden md:block">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>Mentor</TableHead>
              <TableHead>Expertise</TableHead>
              <TableHead>Assigned Projects</TableHead>
              <TableHead>Status</TableHead>
              <TableHead>Last Login</TableHead>
              <TableHead className="text-right">Actions</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {mentorsWithAvatars.map((mentor) => (
              <TableRow key={mentor.id}>
                <TableCell>
                  <div className="flex items-center gap-3">
                    <UserAvatar user={mentor} avatarUrl={mentor.avatarUrl} size="sm" />
                    <div>
                      <p className="font-medium">{mentor.name || 'Unnamed'}</p>
                      <p className="text-sm text-muted-foreground">
                        {mentor.email}
                      </p>
                    </div>
                  </div>
                </TableCell>
                <TableCell>
                  {mentor.expertiseTags && mentor.expertiseTags.length > 0 ? (
                    <div className="flex flex-wrap gap-1">
                      {mentor.expertiseTags.slice(0, 3).map((tag) => (
                        <Badge key={tag} variant="outline" className="text-xs">
                          {tag}
                        </Badge>
                      ))}
                      {mentor.expertiseTags.length > 3 && (
                        <Badge variant="outline" className="text-xs">
                          +{mentor.expertiseTags.length - 3}
                        </Badge>
                      )}
                    </div>
                  ) : (
                    <span className="text-sm text-muted-foreground">-</span>
                  )}
                </TableCell>
                <TableCell>
                  <span className="font-medium">{mentor._count.mentorAssignments}</span>
                  <span className="text-muted-foreground"> project{mentor._count.mentorAssignments !== 1 ? 's' : ''}</span>
                </TableCell>
                <TableCell>
                  <Badge variant={statusColors[mentor.status] || 'secondary'}>
                    {mentor.status}
                  </Badge>
                </TableCell>
                <TableCell>
                  {mentor.lastLoginAt ? (
                    formatDate(mentor.lastLoginAt)
                  ) : (
                    <span className="text-muted-foreground">Never</span>
                  )}
                </TableCell>
                <TableCell className="text-right">
                  <Button variant="ghost" size="sm" asChild>
                    <Link href={`/admin/mentors/${mentor.id}` as Route}>
                      <Eye className="mr-2 h-4 w-4" />
                      View
                    </Link>
                  </Button>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </Card>

      {/* Mobile card view */}
      <div className="space-y-4 md:hidden">
        {mentorsWithAvatars.map((mentor) => (
          <Card key={mentor.id}>
            <CardHeader className="pb-3">
              <div className="flex items-start justify-between">
                <div className="flex items-center gap-3">
                  <UserAvatar user={mentor} avatarUrl={mentor.avatarUrl} size="md" />
                  <div>
                    <CardTitle className="text-base">
                      {mentor.name || 'Unnamed'}
                    </CardTitle>
                    <CardDescription className="text-xs">
                      {mentor.email}
                    </CardDescription>
                  </div>
                </div>
                <Badge variant={statusColors[mentor.status] || 'secondary'}>
                  {mentor.status}
                </Badge>
              </div>
            </CardHeader>
            <CardContent className="space-y-3">
              <div className="flex items-center justify-between text-sm">
                <span className="text-muted-foreground">Assigned Projects</span>
                <span className="font-medium">{mentor._count.mentorAssignments}</span>
              </div>
              {mentor.expertiseTags && mentor.expertiseTags.length > 0 && (
                <div className="flex flex-wrap gap-1">
                  {mentor.expertiseTags.map((tag) => (
                    <Badge key={tag} variant="outline" className="text-xs">
                      {tag}
                    </Badge>
                  ))}
                </div>
              )}
              <Button variant="outline" size="sm" className="w-full" asChild>
                <Link href={`/admin/mentors/${mentor.id}` as Route}>
                  <Eye className="mr-2 h-4 w-4" />
                  View Details
                </Link>
              </Button>
            </CardContent>
          </Card>
        ))}
      </div>
    </>
  )
}

function MentorsSkeleton() {
  return (
    <Card>
      <CardContent className="p-6">
        <div className="space-y-4">
          {[...Array(5)].map((_, i) => (
            <div key={i} className="flex items-center gap-4">
              <Skeleton className="h-10 w-10 rounded-full" />
              <div className="flex-1 space-y-2">
                <Skeleton className="h-5 w-32" />
                <Skeleton className="h-4 w-48" />
              </div>
              <Skeleton className="h-9 w-9" />
            </div>
          ))}
        </div>
      </CardContent>
    </Card>
  )
}

export default function MentorsPage() {
  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-semibold tracking-tight">Mentors</h1>
          <p className="text-muted-foreground">
            Manage mentors and their project assignments
          </p>
        </div>
        <Button asChild>
          <Link href="/admin/users/invite">
            <Plus className="mr-2 h-4 w-4" />
            Invite Mentor
          </Link>
        </Button>
      </div>

      {/* Content */}
      <Suspense fallback={<MentorsSkeleton />}>
        <MentorsContent />
      </Suspense>
    </div>
  )
}
