import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import { redirect } from 'next/navigation'
import { prisma } from '@/lib/db'
import { ManagerPageClient } from '@/components/manager/manager-page-client'

export default async function ManagerPage() {
  const session = await getServerSession(authOptions)
  
  if (!session?.user) {
    redirect('/auth/signin')
  }

  const userRoles = (session.user as any)?.roles || []
  const isManager = userRoles.includes('Manager') || userRoles.includes('Admin')

  if (!isManager) {
    redirect('/dashboard')
  }

  // Fetch team statistics
  const [, activeUsers, totalTasks, completedTasks, overdueTasks, setupQueueCount] = await Promise.all([
    prisma.user.count(),
    prisma.user.count({ where: { isActive: true } }),
    prisma.task.count(),
    prisma.task.count({ where: { status: 'COMPLETED' } }),
    prisma.task.count({ 
      where: { 
        dueDate: { lt: new Date() },
        status: { not: 'COMPLETED' }
      } 
    }),
    prisma.client.count({
      where: {
        designation: { name: { in: ['Shape', 'Shape 2'] } },
        OR: [
          { claimsAdvocateId: null },
          { setupCompletedAt: null },
        ],
      },
    }),
  ])

  // Fetch team members with their task counts
  const teamMembers = await prisma.user.findMany({
    where: { isActive: true },
    select: {
      id: true,
      displayName: true,
      email: true,
      department: true,
      taskAssignments: {
        where: {
          task: {
            status: { not: 'COMPLETED' }
          }
        },
        select: {
          task: {
            select: {
              status: true,
              priority: true,
              dueDate: true,
            }
          }
        }
      },
      userRoles: {
        include: {
          role: {
            select: {
              name: true,
            }
          }
        }
      }
    },
    orderBy: [{ department: 'asc' }, { displayName: 'asc' }],
  })

  // Fetch recent tasks across the team
  const recentTasks = await prisma.task.findMany({
    take: 10,
    orderBy: { createdAt: 'desc' },
    include: {
      client: {
        select: {
          name: true,
        }
      },
      assignments: {
        include: {
          user: {
            select: {
              displayName: true,
            }
          }
        }
      }
    }
  })

  return (
    <ManagerPageClient
      activeUsers={activeUsers}
      totalTasks={totalTasks}
      completedTasks={completedTasks}
      overdueTasks={overdueTasks}
      teamMembers={teamMembers}
      recentTasks={recentTasks}
      setupQueueCount={setupQueueCount}
    />
  )
}
