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 { Avatar, AvatarFallback } from '@/components/ui/avatar'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import { Plus, Users } from 'lucide-react'
import { formatDate, getInitials } from '@/lib/utils'
import { UserActions, UserMobileActions } from '@/components/admin/user-actions'

async function UsersContent() {
  const users = await prisma.user.findMany({
    where: {
      role: { in: ['JURY_MEMBER', 'OBSERVER'] },
    },
    include: {
      _count: {
        select: {
          assignments: true,
        },
      },
      assignments: {
        select: {
          evaluation: {
            select: { status: true },
          },
        },
      },
    },
    orderBy: [{ role: 'asc' }, { name: 'asc' }],
  })

  if (users.length === 0) {
    return (
      <Card>
        <CardContent className="flex flex-col items-center justify-center py-12 text-center">
          <Users className="h-12 w-12 text-muted-foreground/50" />
          <p className="mt-2 font-medium">No jury members yet</p>
          <p className="text-sm text-muted-foreground">
            Invite jury members to start assigning projects for evaluation
          </p>
          <Button asChild className="mt-4">
            <Link href="/admin/users/invite">
              <Plus className="mr-2 h-4 w-4" />
              Invite Member
            </Link>
          </Button>
        </CardContent>
      </Card>
    )
  }

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

  const roleColors: Record<string, 'default' | 'outline' | 'secondary'> = {
    JURY_MEMBER: 'default',
    OBSERVER: 'outline',
  }

  return (
    <>
      {/* Desktop table view */}
      <Card className="hidden md:block">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>Member</TableHead>
              <TableHead>Role</TableHead>
              <TableHead>Expertise</TableHead>
              <TableHead>Assignments</TableHead>
              <TableHead>Status</TableHead>
              <TableHead>Last Login</TableHead>
              <TableHead className="text-right">Actions</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {users.map((user) => (
              <TableRow key={user.id}>
                <TableCell>
                  <div className="flex items-center gap-3">
                    <Avatar className="h-8 w-8">
                      <AvatarFallback className="text-xs">
                        {getInitials(user.name || user.email || 'U')}
                      </AvatarFallback>
                    </Avatar>
                    <div>
                      <p className="font-medium">{user.name || 'Unnamed'}</p>
                      <p className="text-sm text-muted-foreground">
                        {user.email}
                      </p>
                    </div>
                  </div>
                </TableCell>
                <TableCell>
                  <Badge variant={roleColors[user.role] || 'secondary'}>
                    {user.role.replace('_', ' ')}
                  </Badge>
                </TableCell>
                <TableCell>
                  {user.expertiseTags && user.expertiseTags.length > 0 ? (
                    <div className="flex flex-wrap gap-1">
                      {user.expertiseTags.slice(0, 2).map((tag) => (
                        <Badge key={tag} variant="outline" className="text-xs">
                          {tag}
                        </Badge>
                      ))}
                      {user.expertiseTags.length > 2 && (
                        <Badge variant="outline" className="text-xs">
                          +{user.expertiseTags.length - 2}
                        </Badge>
                      )}
                    </div>
                  ) : (
                    <span className="text-sm text-muted-foreground">-</span>
                  )}
                </TableCell>
                <TableCell>
                  <div>
                    <p>{user._count.assignments} assigned</p>
                    <p className="text-sm text-muted-foreground">
                      {user.assignments.filter(a => a.evaluation?.status === 'SUBMITTED').length} completed
                    </p>
                  </div>
                </TableCell>
                <TableCell>
                  <Badge variant={statusColors[user.status] || 'secondary'}>
                    {user.status}
                  </Badge>
                </TableCell>
                <TableCell>
                  {user.lastLoginAt ? (
                    formatDate(user.lastLoginAt)
                  ) : (
                    <span className="text-muted-foreground">Never</span>
                  )}
                </TableCell>
                <TableCell className="text-right">
                  <UserActions
                    userId={user.id}
                    userEmail={user.email}
                    userStatus={user.status}
                  />
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </Card>

      {/* Mobile card view */}
      <div className="space-y-4 md:hidden">
        {users.map((user) => (
          <Card key={user.id}>
            <CardHeader className="pb-3">
              <div className="flex items-start justify-between">
                <div className="flex items-center gap-3">
                  <Avatar className="h-10 w-10">
                    <AvatarFallback>
                      {getInitials(user.name || user.email || 'U')}
                    </AvatarFallback>
                  </Avatar>
                  <div>
                    <CardTitle className="text-base">
                      {user.name || 'Unnamed'}
                    </CardTitle>
                    <CardDescription className="text-xs">
                      {user.email}
                    </CardDescription>
                  </div>
                </div>
                <Badge variant={statusColors[user.status] || 'secondary'}>
                  {user.status}
                </Badge>
              </div>
            </CardHeader>
            <CardContent className="space-y-3">
              <div className="flex items-center justify-between text-sm">
                <span className="text-muted-foreground">Role</span>
                <Badge variant={roleColors[user.role] || 'secondary'}>
                  {user.role.replace('_', ' ')}
                </Badge>
              </div>
              <div className="flex items-center justify-between text-sm">
                <span className="text-muted-foreground">Assignments</span>
                <span>
                  {user.assignments.filter(a => a.evaluation?.status === 'SUBMITTED').length}/{user._count.assignments} completed
                </span>
              </div>
              {user.expertiseTags && user.expertiseTags.length > 0 && (
                <div className="flex flex-wrap gap-1">
                  {user.expertiseTags.map((tag) => (
                    <Badge key={tag} variant="outline" className="text-xs">
                      {tag}
                    </Badge>
                  ))}
                </div>
              )}
              <UserMobileActions
                userId={user.id}
                userEmail={user.email}
                userStatus={user.status}
              />
            </CardContent>
          </Card>
        ))}
      </div>
    </>
  )
}

function UsersSkeleton() {
  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 UsersPage() {
  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-semibold tracking-tight">Jury Members</h1>
          <p className="text-muted-foreground">
            Manage jury members and observers
          </p>
        </div>
        <Button asChild>
          <Link href="/admin/users/invite">
            <Plus className="mr-2 h-4 w-4" />
            Invite Member
          </Link>
        </Button>
      </div>

      {/* Content */}
      <Suspense fallback={<UsersSkeleton />}>
        <UsersContent />
      </Suspense>
    </div>
  )
}
