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(request: NextRequest) {
  try {
    const session = await getServerSession(authOptions);

    if (!session || !session.user) {
      return NextResponse.json(
        { error: 'Unauthorized' },
        { status: 401 }
      );
    }

    const user = session.user as any;

    // if (user.role !== 'FREELANCER') {
    //   return NextResponse.json(
    //     { error: 'Access denied. Freelancer role required.' },
    //     { status: 403 }
    //   );
    // }

    const { searchParams } = new URL(request.url);
    const page = parseInt(searchParams.get('page') || '1');
    const limit = parseInt(searchParams.get('limit') || '12');
    const status = searchParams.get('status')?.toLowerCase() || 'recommended';
    const search = searchParams.get('search') || '';
    const category = searchParams.get('category') || '';
    
    const skip = (page - 1) * limit;

    if (!prisma) {
      return NextResponse.json({
        success: true,
        data: {
          projects: [],
          pagination: { currentPage: 1, totalPages: 1, totalItems: 0, itemsPerPage: limit, hasNextPage: false, hasPrevPage: false }
        }
      });
    }

    // Build where clause based on user role and status
    let whereClause: any = {};

    if (user.role === 'CLIENT') {
      // For clients, show their own projects
      whereClause.clientId = user.id;
    } else if (user.role === 'FREELANCER') {
      // For freelancers, show projects based on their relationship to them
      switch (status.toUpperCase()) {
        case 'RECOMMENDED':
          whereClause = {
            status: 'OPEN',
            NOT: {
              bids: {
                some: {
                  freelancerId: user.id
                }
              }
            }
          };
          break;
        
        case 'PROPOSED':
          whereClause = {
            bids: {
              some: {
                freelancerId: user.id,
                status: 'PENDING'
              }
            }
          };
          break;
        
        case 'AWARDED':
          whereClause = {
            bids: {
              some: {
                freelancerId: user.id,
                status: 'ACCEPTED'
              }
            }
          };
          break;
        
        case 'CANCELLED':
          whereClause = {
            OR: [
              { status: 'CANCELLED' },
              {
                bids: {
                  some: {
                    freelancerId: user.id,
                    status: 'REJECTED'
                  }
                }
              }
            ]
          };
          break;
        
        case 'COMPLETED':
          whereClause = {
            status: 'COMPLETED',
            bids: {
              some: {
                freelancerId: user.id,
                status: 'ACCEPTED'
              }
            }
          };
          break;
      }
    } else {
      return NextResponse.json(
        { error: 'Access denied. Client or Freelancer role required.' },
        { status: 403 }
      );
    }

    // Add search filter if provided
    if (search) {
      whereClause.AND = whereClause.AND || [];
      whereClause.AND.push({
        OR: [
          { title: { contains: search } },
          { description: { contains: search } }
        ]
      });
    }

    // Add category filter if provided
    if (category) {
      whereClause.AND = whereClause.AND || [];
      whereClause.AND.push({
        category: {
          OR: [
            { name: { contains: category } },
            { slug: { equals: category } }
          ]
        }
      });
    }

    try {
      // Get projects
      const [projects, totalCount] = await Promise.all([
        prisma.project.findMany({
          where: whereClause,
          skip,
          take: limit,
          include: {
            client: {
              select: {
                id: true,
                email: true,
                image: true,
                profile: {
                  select: {
                    firstName: true,
                    lastName: true
                  }
                },
                _count: {
                  select: {
                    receivedReviews: true
                  }
                }
              }
            },
            category: {
              select: {
                id: true,
                name: true,
                slug: true,
                icon: true
              }
            },
            _count: {
              select: {
                bids: true
              }
            },
            bids: user.role === 'FREELANCER' && status !== 'recommended' ? {
              where: {
                freelancerId: user.id
              },
              select: {
                id: true,
                status: true,
                amount: true,
                duration: true,
                createdAt: true
              }
            } : user.role === 'CLIENT' ? {
              select: {
                id: true,
                status: true,
                amount: true,
                duration: true,
                createdAt: true,
                freelancer: {
                  select: {
                    id: true,
                    email: true,
                    image: true,
                    profile: {
                      select: {
                        firstName: true,
                        lastName: true
                      }
                    }
                  }
                }
              }
            } : false
          },
          orderBy: {
            createdAt: 'desc'
          }
        }),
        prisma.project.count({ where: whereClause })
      ]);

      // Transform the data to match frontend interface
      const transformedProjects = await Promise.all(projects.map(async (project) => {
        // Get the accepted freelancer (if any)
        const acceptedBid = project.bids?.find(bid => bid.status === 'ACCEPTED');
        const freelancer = acceptedBid?.freelancer;

        // Get client ratings
        const clientReviews = await prisma.review.aggregate({
          where: { recipientId: project.client?.id },
          _avg: { rating: true },
          _count: { rating: true }
        });

        // Get freelancer ratings (if freelancer exists)
        let freelancerReviews = null;
        if (freelancer) {
          freelancerReviews = await prisma.review.aggregate({
            where: { recipientId: freelancer.id },
            _avg: { rating: true },
            _count: { rating: true }
          });
        }

        return {
          id: project.id,
          title: project.title,
          description: project.description,
          budget: project.budget,
          duration: project.duration,
          status: project.status, // Use actual project status, not the filter status
          category: project.category?.name || 'General',
          createdAt: project.createdAt.toISOString(),
          updatedAt: project.updatedAt.toISOString(),
          bidsCount: project._count.bids,
          clientId: project.client?.id || 'unknown',
          clientName: project.client?.profile ? 
            `${project.client.profile.firstName || ''} ${project.client.profile.lastName || ''}`.trim() || project.client.email || 'Unknown Client' :
            project.client?.email || 'Unknown Client',
          clientRating: clientReviews._avg.rating || 0,
          clientReviewCount: clientReviews._count.rating || 0,
          freelancerId: freelancer?.id,
          freelancerName: freelancer?.profile ? 
            `${freelancer.profile.firstName || ''} ${freelancer.profile.lastName || ''}`.trim() || freelancer.email || 'Unknown Freelancer' :
            freelancer?.email,
          freelancerRating: freelancerReviews?._avg.rating || 0,
          freelancerReviewCount: freelancerReviews?._count.rating || 0,
          bidAmount: acceptedBid?.amount, // Deal price from accepted bid
          currency: project.currency || 'CHF' // Add currency field
        };
      }));

      const totalPages = Math.ceil(totalCount / limit);

      return NextResponse.json({
        success: true,
        data: {
          projects: transformedProjects,
          pagination: {
            currentPage: page,
            totalPages,
            totalItems: totalCount,
            itemsPerPage: limit,
            hasNextPage: page < totalPages,
            hasPrevPage: page > 1
          }
        }
      });

    } catch (dbError) {
      console.error('Database query error:', dbError);
      
      return NextResponse.json({
        success: true,
        data: {
          projects: [],
          pagination: { currentPage: 1, totalPages: 1, totalItems: 0, itemsPerPage: limit, hasNextPage: false, hasPrevPage: false }
        }
      });
    }

  } catch (error) {
    console.error('Error fetching my projects:', error);
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    );
  }
}

export async function DELETE(request: NextRequest) {
  try {
    const session = await getServerSession(authOptions);

    if (!session || !session.user) {
      return NextResponse.json(
        { error: 'Unauthorized' },
        { status: 401 }
      );
    }

    const user = session.user as any;

    if (user.role !== 'CLIENT') {
      return NextResponse.json(
        { error: 'Access denied. Client role required.' },
        { status: 403 }
      );
    }

    const { searchParams } = new URL(request.url);
    const projectId = searchParams.get('id');

    if (!projectId) {
      return NextResponse.json(
        { error: 'Project ID is required' },
        { status: 400 }
      );
    }

    // Verify the project belongs to the current client
    const project = await prisma.project.findFirst({
      where: {
        id: projectId,
        clientId: user.id,
      },
    });

    if (!project) {
      return NextResponse.json(
        { error: 'Project not found or access denied' },
        { status: 404 }
      );
    }

    // Only allow deletion of draft projects
    if (project.status !== 'DRAFT') {
      return NextResponse.json(
        { error: 'Only draft projects can be deleted' },
        { status: 400 }
      );
    }

    // Delete the project
    await prisma.project.delete({
      where: {
        id: projectId,
      },
    });

    return NextResponse.json({
      success: true,
      message: 'Project deleted successfully',
    });

  } catch (error) {
    console.error('Error deleting project:', error);
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    );
  }
}
