
import { Suspense } from 'react';
import { getServerSession } from 'next-auth';
import { redirect } from 'next/navigation';
import { authOptions } from '@/lib/auth';
import ContractorPerformanceDashboard from '@/components/contractors/performance-dashboard';
import ContractorLeaderboard from '@/components/contractors/contractor-leaderboard';
import { Card } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';

export const metadata = {
  title: 'Contractor Performance | Quote2Contract',
  description: 'Track contractor performance, revenue, and leaderboards',
};

async function LoadingSkeleton() {
  return (
    <div className="space-y-6">
      <Skeleton className="h-12 w-64" />
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        {[1, 2, 3, 4].map((i) => (
          <Card key={i} className="p-6">
            <Skeleton className="h-4 w-24 mb-2" />
            <Skeleton className="h-8 w-32" />
          </Card>
        ))}
      </div>
      <Skeleton className="h-96 w-full" />
    </div>
  );
}

export default async function ContractorPerformancePage() {
  const session = await getServerSession(authOptions);

  if (!session?.user) {
    redirect('/auth/signin');
  }

  // Only admins, sales, and contractors can access this page
  const allowedRoles = ['ADMIN', 'SALES', 'CONTRACTOR'];
  if (!allowedRoles.includes(session.user.role || '')) {
    redirect('/dashboard');
  }

  return (
    <div className="container mx-auto px-4 py-8">
      <Suspense fallback={<LoadingSkeleton />}>
        <Tabs defaultValue="leaderboard" className="space-y-6">
          <TabsList>
            <TabsTrigger value="leaderboard">Leaderboard</TabsTrigger>
            <TabsTrigger value="performance">Performance Dashboard</TabsTrigger>
          </TabsList>

          <TabsContent value="leaderboard" className="space-y-6">
            <ContractorLeaderboard />
          </TabsContent>

          <TabsContent value="performance" className="space-y-6">
            <ContractorPerformanceDashboard userRole={session.user.role} userId={session.user.id} />
          </TabsContent>
        </Tabs>
      </Suspense>
    </div>
  );
}
