import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import { prisma } from '@/lib/prisma';

export async function GET(req: NextRequest) {
  try {
    if (!prisma) {
      return NextResponse.json(
        { error: 'Database connection not available' },
        { status: 503 }
      );
    }

    const session = await getServerSession(authOptions);
    
    if (!session?.user?.email) {
      return NextResponse.json(
        { error: 'Unauthorized' },
        { status: 401 }
      );
    }

    const { searchParams } = new URL(req.url);
    const page = parseInt(searchParams.get('page') || '1');
    const limit = parseInt(searchParams.get('limit') || '10');
    const sortBy = searchParams.get('sortBy') || 'completedAt';
    const sortOrder = searchParams.get('sortOrder') || 'desc';
    const hasReviewed = searchParams.get('hasReviewed'); // 'true', 'false', or null
    const dateFrom = searchParams.get('dateFrom');
    const dateTo = searchParams.get('dateTo');

    const skip = (page - 1) * limit;

    try {
      // Build where clause
      const whereClause: any = {
        status: 'COMPLETED',
        OR: [
          // User is the client
          { clientId: session.user.email },
          // User is the freelancer with accepted bid
          {
            bids: {
              some: {
                freelancerId: session.user.email,
                status: 'ACCEPTED'
              }
            }
          }
        ]
      };

      // Add date filters
      if (dateFrom || dateTo) {
        whereClause.completedAt = {};
        
        if (dateFrom) {
          whereClause.completedAt.gte = new Date(dateFrom);
        }
        
        if (dateTo) {
          whereClause.completedAt.lte = new Date(dateTo);
        }
      }

      // Get completed projects
      const [projects, totalCount] = await Promise.all([
        prisma.project.findMany({
          where: whereClause,
          include: {
            bids: {
              where: {
                status: 'ACCEPTED'
              },
              include: {
                freelancer: {
                  select: {
                    id: true,
                    email: true,
                    image: true,
                    profile: {
                      select: {
                        firstName: true,
                        lastName: true
                      }
                    }
                  }
                }
              }
            },
            client: {
              select: {
                id: true,
                email: true,
                image: true,
                profile: {
                  select: {
                    firstName: true,
                    lastName: true
                  }
                }
              }
            },
            category: {
              select: {
                name: true
              }
            },
            reviews: {
              where: {
                authorId: session.user.email
              },
              select: {
                id: true,
                rating: true,
                createdAt: true
              }
            },
            _count: {
              select: {
                // TODO: Add when ProjectDeliverable model is available
                // projectDeliverables: true,
                reviews: {
                  where: {
                    authorId: session.user.email
                  }
                }
              }
            }
          },
          orderBy: sortBy === 'completedAt' 
            ? { completedAt: sortOrder as 'asc' | 'desc' }
            : { [sortBy]: sortOrder as 'asc' | 'desc' },
          skip,
          take: limit
        }),
        prisma.project.count({ where: whereClause })
      ]);

      // Filter by review status if specified
      let filteredProjects = projects;
      if (hasReviewed !== null) {
        const reviewedFilter = hasReviewed === 'true';
        filteredProjects = projects.filter(project => {
          const userHasReviewed = project._count.reviews > 0;
          return userHasReviewed === reviewedFilter;
        });
      }

      // Format response
      const formattedProjects = filteredProjects.map(project => ({
        id: project.id,
        title: project.title,
        description: project.description.substring(0, 150) + '...',
        status: project.status,
        budget: project.budget,
        // TODO: Add currency field to Project model when available
        currency: 'USD',
        createdAt: project.createdAt.toISOString(),
        completedAt: project.completedAt?.toISOString() || project.updatedAt.toISOString(),
        freelancerName: project.bids.length > 0 && project.bids[0].freelancer.profile ? `${project.bids[0].freelancer.profile.firstName || ''} ${project.bids[0].freelancer.profile.lastName || ''}`.trim() : 'Unknown Freelancer',
        clientName: project.client.profile ? `${project.client.profile.firstName || ''} ${project.client.profile.lastName || ''}`.trim() : 'Unknown Client',
        freelancerAvatar: project.bids.length > 0 ? (project.bids[0].freelancer.image || '/assets/image/freelancer-avatar.png') : '/assets/image/freelancer-avatar.png',
        clientAvatar: project.client?.image || '/assets/image/client-avatar.png',
        category: project.category?.name || 'General',
        userRole: project.bids.length > 0 && project.bids[0].freelancerId === session.user?.email ? 'freelancer' : 'client',
        deliverablesCount: 0, // TODO: Add when ProjectDeliverable model is available
        hasReviewed: project._count.reviews > 0,
        userReview: project.reviews.length > 0 ? {
          id: project.reviews[0].id,
          rating: project.reviews[0].rating,
          createdAt: project.reviews[0].createdAt.toISOString()
        } : null
      }));

      return NextResponse.json({
        success: true,
        data: {
          projects: formattedProjects,
          pagination: {
            page,
            limit,
            total: hasReviewed !== null ? filteredProjects.length : totalCount,
            pages: Math.ceil((hasReviewed !== null ? filteredProjects.length : totalCount) / limit)
          },
          filters: {
            sortBy,
            sortOrder,
            hasReviewed,
            dateFrom,
            dateTo
          }
        }
      });

    } catch (dbError) {
      console.error('Database query error:', dbError);
      
      // Return mock completed projects when database is not ready
      const mockProjects = [
        {
          id: 'completed-1',
          title: 'Laravel E-Commerce Website Development',
          description: 'Develop a modern responsive website with user authentication and payment integration...',
          status: 'completed',
          budget: 2000,
          currency: 'EUR',
          createdAt: '2024-06-01T10:00:00Z',
          completedAt: '2024-06-12T13:12:00Z',
          freelancerName: 'John Developer',
          clientName: 'Esther Howard',
          freelancerAvatar: '/assets/image/freelancer-avatar.png',
          clientAvatar: '/assets/image/profile02.png',
          category: 'Web Development',
          userRole: session.user.email === 'freelancer-1' ? 'freelancer' : 'client',
          deliverablesCount: 3,
          hasReviewed: false,
          userReview: null
        },
        {
          id: 'completed-2',
          title: 'Mobile App UI/UX Design',
          description: 'Design modern mobile application interface with user-friendly experience...',
          status: 'completed',
          budget: 1200,
          currency: 'USD',
          createdAt: '2024-05-20T09:15:00Z',
          completedAt: '2024-05-30T16:45:00Z',
          freelancerName: 'Jane Designer',
          clientName: 'Mike Johnson',
          freelancerAvatar: '/assets/image/freelancer-avatar.png',
          clientAvatar: '/assets/image/client-avatar.png',
          category: 'UI/UX Design',
          userRole: session.user.email === 'freelancer-1' ? 'freelancer' : 'client',
          deliverablesCount: 5,
          hasReviewed: true,
          userReview: {
            id: 'review-1',
            rating: 5,
            createdAt: '2024-05-31T10:00:00Z'
          }
        }
      ];

      // Apply hasReviewed filter to mock data
      let filteredMockProjects = mockProjects;
      if (hasReviewed !== null) {
        const reviewedFilter = hasReviewed === 'true';
        filteredMockProjects = mockProjects.filter(project => project.hasReviewed === reviewedFilter);
      }

      return NextResponse.json({
        success: true,
        data: {
          projects: filteredMockProjects,
          pagination: {
            page: 1,
            limit: 10,
            total: filteredMockProjects.length,
            pages: 1
          },
          filters: {
            sortBy: 'completedAt',
            sortOrder: 'desc',
            hasReviewed,
            dateFrom: null,
            dateTo: null
          }
        }
      });
    }

  } catch (error) {
    console.error('Error fetching completed projects:', error);
    
    return NextResponse.json(
      { 
        error: error instanceof Error ? error.message : 'Failed to fetch completed projects',
        type: 'server_error'
      },
      { status: 500 }
    );
  }
}