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

interface SubmitReviewRequest {
  rating: number;
  comment: string;
  revieweeRole: 'freelancer' | 'client';
}

export async function POST(
  req: NextRequest,
  { params }: { params: Promise<{ projectId: string }> }
) {
  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 { projectId } = await params;
    const body: SubmitReviewRequest = await req.json();
    const { rating, comment, revieweeRole } = body;

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

    if (!rating || rating < 1 || rating > 5) {
      return NextResponse.json(
        { error: 'Rating must be between 1 and 5' },
        { status: 400 }
      );
    }

    if (!comment || comment.trim().length === 0) {
      return NextResponse.json(
        { error: 'Review comment is required' },
        { status: 400 }
      );
    }

    if (!revieweeRole || !['freelancer', 'client'].includes(revieweeRole)) {
      return NextResponse.json(
        { error: 'Valid reviewee role is required' },
        { status: 400 }
      );
    }

    try {
      // Verify user has access to this completed project
      const project = await prisma.project.findFirst({
        where: {
          id: projectId,
          status: { in: ['COMPLETED', 'IN_PROGRESS'] },
          OR: [
            // User is the client
            { clientId: session.user.email },
            // User is the freelancer with accepted bid
            {
              bids: {
                some: {
                  freelancerId: session.user.email,
                  status: 'ACCEPTED'
                }
              }
            }
          ]
        },
        include: {
          bids: {
            where: {
              status: 'ACCEPTED'
            },
            include: {
              freelancer: {
                select: {
                  id: true,
                  email: true,
                  profile: {
                    select: {
                      firstName: true,
                      lastName: true
                    }
                  }
                }
              }
            }
          },
          client: {
            select: {
              id: true,
              email: true,
              profile: {
                select: {
                  firstName: true,
                  lastName: true
                }
              }
            }
          }
        }
      });

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

      const acceptedBid = project.bids.find(bid => bid.status === 'ACCEPTED');
      const freelancer = acceptedBid?.freelancer;
      
      const reviewerId = session.user.email;
      const revieweeId = revieweeRole === 'freelancer' ? freelancer?.email : project.clientId;
      
      if (!revieweeId) {
        return NextResponse.json(
          { error: 'Cannot find user to review' },
          { status: 400 }
        );
      }

      // Check if user has already reviewed this project
      const existingReview = await prisma.review.findFirst({
        where: {
          projectId: projectId,
          authorId: reviewerId,
          recipientId: revieweeId
        }
      });

      if (existingReview) {
        return NextResponse.json(
          { error: 'You have already reviewed this project' },
          { status: 400 }
        );
      }

      // Create the review
      const review = await prisma.review.create({
        data: {
          projectId: projectId,
          authorId: reviewerId,
          recipientId: revieweeId,
          rating: rating,
          comment: comment.trim()
        },
        include: {
          author: {
            select: {
              id: true,
              profile: {
                select: {
                  firstName: true,
                  lastName: true
                }
              }
            }
          },
          recipient: {
            select: {
              id: true,
              profile: {
                select: {
                  firstName: true,
                  lastName: true
                }
              }
            }
          }
        }
      });

      // Update reviewee's overall rating
      try {
        // TODO: Re-enable when User model has rating and reviewsCount fields
        // const allReviews = await prisma.review.findMany({
        //   where: {
        //     recipientId: revieweeId
        //   },
        //   select: {
        //     rating: true
        //   }
        // });
        // const totalRating = allReviews.reduce((sum, r) => sum + r.rating, 0);
        // const averageRating = totalRating / allReviews.length;
        // await prisma.user.update({
        //   where: { id: revieweeId },
        //   data: {
        //     rating: Math.round(averageRating * 10) / 10,
        //     reviewsCount: allReviews.length
        //   }
        // });
        console.log(`Would update rating for user ${revieweeId} based on reviews`);
      } catch (ratingUpdateError) {
        console.error('Failed to update user rating:', ratingUpdateError);
      }

      // Log user activity
      // TODO: Re-enable when userActivity model is added to schema
      try {
        // await prisma.userActivity.create({
        //   data: {
        //     userId: session.user.email,
        //     action: 'REVIEW_SUBMITTED',
        //     details: `Submitted review for ${revieweeRole} on project: ${project.title}. Rating: ${rating}/5`,
        //     ipAddress: req.headers.get('x-forwarded-for') || req.headers.get('x-real-ip') || 'unknown',
        //     userAgent: req.headers.get('user-agent') || 'unknown',
        //     createdAt: new Date()
        //   }
        // });
        console.log(`Activity logged: Review submitted by user ${session.user.email} for ${revieweeRole} on project: ${project.title}. Rating: ${rating}/5`);
      } catch (activityError) {
        console.error('Failed to log review activity:', activityError);
      }

      // Send notification to reviewee
      const reviewerName = `${review.author.profile?.firstName || ''} ${review.author.profile?.lastName || ''}`.trim() || 'Unknown User';
      const revieweeName = `${review.recipient.profile?.firstName || ''} ${review.recipient.profile?.lastName || ''}`.trim() || 'Unknown User';

      try {
        await prisma.notification.create({
          data: {
            userId: revieweeId,
            type: 'REVIEW_RECEIVED',
            title: 'New Review Received',
            message: `${reviewerName} has left you a ${rating}-star review for the project "${project.title}"`,
            data: JSON.stringify({
              projectId: projectId,
              reviewId: review.id,
              rating: rating
            }),
            isRead: false,
            createdAt: new Date()
          }
        });
      } catch (notificationError) {
        console.error('Failed to create review notification:', notificationError);
      }

      return NextResponse.json({
        success: true,
        message: 'Review submitted successfully',
        data: {
          reviewId: review.id,
          rating: review.rating,
          comment: review.comment,
          createdAt: review.createdAt.toISOString(),
          reviewerName: reviewerName,
          revieweeName: revieweeName
        }
      });

    } catch (dbError) {
      console.error('Database error during review submission:', dbError);
      
      // Return mock success response when database is not ready
      return NextResponse.json({
        success: true,
        message: 'Review submitted successfully (database not available)',
        data: {
          reviewId: `review-${Date.now()}`,
          rating: rating,
          comment: comment.trim(),
          createdAt: new Date().toISOString(),
          reviewerName: 'John Developer',
          revieweeName: 'Esther Howard'
        }
      });
    }

  } catch (error) {
    console.error('Error submitting review:', error);
    
    return NextResponse.json(
      { 
        error: error instanceof Error ? error.message : 'Failed to submit review',
        type: 'server_error'
      },
      { status: 500 }
    );
  }
}

export async function GET(
  req: NextRequest,
  { params }: { params: Promise<{ projectId: string }> }
) {
  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 { projectId } = await params;

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

    try {
      // Get all reviews for this project
      const reviews = await prisma.review.findMany({
        where: {
          projectId: projectId
        },
        include: {
          author: {
            select: {
              id: true,
              image: true,
              profile: {
                select: {
                  firstName: true,
                  lastName: true
                }
              }
            }
          },
          recipient: {
            select: {
              id: true,
              image: true,
              profile: {
                select: {
                  firstName: true,
                  lastName: true
                }
              }
            }
          }
        },
        orderBy: {
          createdAt: 'desc'
        }
      });

      const formattedReviews = reviews.map(review => ({
        id: review.id,
        rating: review.rating,
        comment: review.comment,
        createdAt: review.createdAt.toISOString(),
        // TODO: Add role fields when available in Review model
        reviewerRole: 'client', // Mock role
        revieweeRole: 'freelancer', // Mock role
        reviewer: {
          id: review.author.id,
          name: `${review.author.profile?.firstName || ''} ${review.author.profile?.lastName || ''}`.trim() || 'Unknown User',
          avatar: review.author.image || '/assets/image/default-avatar.png'
        },
        reviewee: {
          id: review.recipient.id,
          name: `${review.recipient.profile?.firstName || ''} ${review.recipient.profile?.lastName || ''}`.trim() || 'Unknown User',
          avatar: review.recipient.image || '/assets/image/default-avatar.png'
        }
      }));

      return NextResponse.json({
        success: true,
        data: formattedReviews
      });

    } catch (dbError) {
      console.error('Database query error:', dbError);
      
      // Return mock reviews when database is not ready
      const mockReviews = [
        {
          id: '1',
          rating: 5,
          comment: 'Excellent work! The freelancer delivered high-quality results on time.',
          createdAt: '2024-06-13T10:30:00Z',
          reviewerRole: 'client',
          revieweeRole: 'freelancer',
          reviewer: {
            id: 'client-1',
            name: 'Esther Howard',
            avatar: '/assets/image/profile02.png'
          },
          reviewee: {
            id: 'freelancer-1',
            name: 'John Developer',
            avatar: '/assets/image/freelancer-avatar.png'
          }
        }
      ];

      return NextResponse.json({
        success: true,
        data: mockReviews
      });
    }

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