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,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const session = await getServerSession(authOptions);

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

    const { id: reviewId } = await params;

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

    // Get review with related data
    const review = await prisma.review.findUnique({
      where: { id: reviewId },
      include: {
        author: {
          include: {
            profile: true
          }
        },
        recipient: {
          include: {
            profile: true
          }
        },
        project: {
          select: {
            title: true,
            description: true
          }
        }
      }
    });

    if (!review) {
      return NextResponse.json(
        { error: 'Review not found' },
        { status: 404 }
      );
    }

    const user = session.user as any;

    // Check if user has access to this review
    if (user.id !== review.authorId && user.id !== review.recipientId && user.role !== 'ADMIN') {
      return NextResponse.json(
        { error: 'Access denied' },
        { status: 403 }
      );
    }

    // Transform review data
    const transformedReview = {
      id: review.id,
      rating: review.rating,
      comment: review.comment,
      createdAt: review.createdAt.toISOString(),
      updatedAt: review.updatedAt.toISOString(),
      project: {
        title: review.project.title,
        description: review.project.description
      },
      author: {
        id: review.author.id,
        name: review.author.profile 
          ? `${review.author.profile.firstName || ''} ${review.author.profile.lastName || ''}`.trim() || 'Anonymous'
          : 'Anonymous',
        profileImage: review.author.profile?.profileImage || '/assets/image/user.png'
      },
      recipient: {
        id: review.recipient.id,
        name: review.recipient.profile 
          ? `${review.recipient.profile.firstName || ''} ${review.recipient.profile.lastName || ''}`.trim() || 'Anonymous'
          : 'Anonymous',
        profileImage: review.recipient.profile?.profileImage || '/assets/image/user.png'
      }
    };

    return NextResponse.json({
      success: true,
      review: transformedReview
    });

  } catch (error) {
    console.error('Error fetching review:', error);
    return NextResponse.json(
      { 
        success: false, 
        error: 'Failed to fetch review',
        message: error instanceof Error ? error.message : 'Unknown error'
      },
      { status: 500 }
    );
  }
}

export async function PUT(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const session = await getServerSession(authOptions);

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

    const user = session.user as any;
    const { id: reviewId } = await params;

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

    const body = await request.json();
    const { rating, review } = body;

    // Validate required fields
    if (!rating || !review) {
      return NextResponse.json(
        { error: 'Rating and review are required' },
        { status: 400 }
      );
    }

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

    // Validate review length
    if (typeof review !== 'string' || review.trim().length < 10) {
      return NextResponse.json(
        { error: 'Review must be at least 10 characters long' },
        { status: 400 }
      );
    }

    // Get existing review
    const existingReview = await prisma.review.findUnique({
      where: { id: reviewId },
      select: {
        id: true,
        authorId: true,
        recipientId: true,
        createdAt: true
      }
    });

    if (!existingReview) {
      return NextResponse.json(
        { error: 'Review not found' },
        { status: 404 }
      );
    }

    // Check if user owns the review
    if (existingReview.authorId !== user.id) {
      return NextResponse.json(
        { error: 'You can only edit your own reviews' },
        { status: 403 }
      );
    }

    // Check if review is recent enough to edit (within 7 days)
    const daysSinceCreation = Math.floor((Date.now() - existingReview.createdAt.getTime()) / (1000 * 60 * 60 * 24));
    if (daysSinceCreation > 7) {
      return NextResponse.json(
        { error: 'Reviews can only be edited within 7 days of creation' },
        { status: 400 }
      );
    }

    // Update the review
    const updatedReview = await prisma.review.update({
      where: { id: reviewId },
      data: {
        rating: parseFloat(rating.toString()),
        comment: review.trim(),
        updatedAt: new Date()
      },
      include: {
        author: {
          include: {
            profile: true
          }
        },
        project: {
          select: {
            title: true
          }
        }
      }
    });

    // Create notification for freelancer about review update
    try {
      await prisma.notification.create({
        data: {
          userId: existingReview.recipientId,
          type: 'REVIEW_UPDATED',
          title: 'Review Updated',
          message: `${updatedReview.author.profile?.firstName || 'A client'} updated their review for "${updatedReview.project.title}".`,
          data: JSON.stringify({
            reviewId: updatedReview.id,
            rating: updatedReview.rating
          }),
          isRead: false,
        }
      });
    } catch (notificationError) {
      console.log('Could not create notification:', notificationError);
    }

    return NextResponse.json({
      success: true,
      message: 'Review updated successfully',
      review: {
        id: updatedReview.id,
        rating: updatedReview.rating,
        review: updatedReview.comment,
        updatedAt: updatedReview.updatedAt.toISOString(),
      }
    });

  } catch (error) {
    console.error('Error updating review:', error);
    return NextResponse.json(
      { 
        success: false,
        error: 'Internal server error',
        message: error instanceof Error ? error.message : 'Unknown error'
      },
      { status: 500 }
    );
  }
}

export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const session = await getServerSession(authOptions);

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

    const user = session.user as any;
    const { id: reviewId } = await params;

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

    // Get existing review
    const existingReview = await prisma.review.findUnique({
      where: { id: reviewId },
      select: {
        id: true,
        authorId: true,
        recipientId: true,
        createdAt: true
      }
    });

    if (!existingReview) {
      return NextResponse.json(
        { error: 'Review not found' },
        { status: 404 }
      );
    }

    // Check if user owns the review or is admin
    if (existingReview.authorId !== user.id && user.role !== 'ADMIN') {
      return NextResponse.json(
        { error: 'You can only delete your own reviews' },
        { status: 403 }
      );
    }

    // Check if review is recent enough to delete (within 7 days)
    if (user.role !== 'ADMIN') {
      const daysSinceCreation = Math.floor((Date.now() - existingReview.createdAt.getTime()) / (1000 * 60 * 60 * 24));
      if (daysSinceCreation > 7) {
        return NextResponse.json(
          { error: 'Reviews can only be deleted within 7 days of creation' },
          { status: 400 }
        );
      }
    }

    // Delete the review
    await prisma.review.delete({
      where: { id: reviewId }
    });

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

  } catch (error) {
    console.error('Error deleting review:', error);
    return NextResponse.json(
      { 
        success: false,
        error: 'Internal server error',
        message: error instanceof Error ? error.message : 'Unknown error'
      },
      { status: 500 }
    );
  }
}