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

export async function POST(
  req: NextRequest,
  { params }: { params: Promise<{ projectId: string }> }
) {
  try {
    const { projectId } = await params;
    const session = await getServerSession(authOptions);

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

    // Check if the user is a freelancer
    if (session.user.role !== 'FREELANCER') {
      return NextResponse.json(
        {
          error: 'Forbidden',
          message: 'Only freelancers can place bids on projects.'
        },
        { status: 403 }
      );
    }

    const body = await req.json();
    const { amount, deliveryTime, proposal } = body;

    // Detailed validation with specific error messages
    if (!amount) {
      return NextResponse.json(
        { 
          error: 'Validation failed',
          message: 'Bid amount is required. Please enter a valid amount.' 
        },
        { status: 400 }
      );
    }

    if (!deliveryTime) {
      return NextResponse.json(
        { 
          error: 'Validation failed',
          message: 'Delivery time is required. Please specify how many days you need.' 
        },
        { status: 400 }
      );
    }

    if (!proposal || proposal.trim().length === 0) {
      return NextResponse.json(
        { 
          error: 'Validation failed',
          message: 'Proposal description is required. Please describe your approach.' 
        },
        { status: 400 }
      );
    }

    const bidPrice = parseFloat(amount);
    const bidDays = parseInt(deliveryTime);

    if (isNaN(bidPrice) || bidPrice <= 0) {
      return NextResponse.json(
        { 
          error: 'Validation failed',
          message: 'Please enter a valid bid amount greater than 0.' 
        },
        { status: 400 }
      );
    }

    if (isNaN(bidDays) || bidDays <= 0) {
      return NextResponse.json(
        { 
          error: 'Validation failed',
          message: 'Please enter a valid delivery time greater than 0 days.' 
        },
        { status: 400 }
      );
    }

    if (proposal.trim().length < 10) {
      return NextResponse.json(
        { 
          error: 'Validation failed',
          message: 'Proposal must be at least 10 characters long.' 
        },
        { status: 400 }
      );
    }

    if (!prisma) {
      return NextResponse.json(
        { 
          error: 'Service unavailable',
          message: 'Database service is currently unavailable. Please try again later.'
        },
        { status: 503 }
      );
    }

    try {
      const freelancerId = session.user.id;

      const existingBid = await prisma.bid.findFirst({
        where: {
          projectId,
          freelancerId
        }
      });

      if (existingBid) {
        return NextResponse.json(
          { 
            error: 'Duplicate bid',
            message: 'You have already submitted a bid for this project. You can update your existing bid instead.' 
          },
          { status: 409 }
        );
      }

      const project = await prisma.project.findUnique({
        where: { id: projectId },
        include: {
          category: true,
          client: {
            include: {
              profile: true
            }
          }
        }
      });

      if (!project) {
        return NextResponse.json(
          { 
            error: 'Project not found',
            message: 'The project you are trying to bid on does not exist or has been removed.' 
          },
          { status: 404 }
        );
      }

      if (project.status !== 'OPEN') {
        let statusMessage = 'This project is no longer accepting bids.';
        if (project.status === 'IN_PROGRESS') {
          statusMessage = 'This project has already been awarded to another freelancer.';
        } else if (project.status === 'COMPLETED') {
          statusMessage = 'This project has been completed.';
        } else if (project.status === 'CANCELLED') {
          statusMessage = 'This project has been cancelled by the client.';
        }

        return NextResponse.json(
          { 
            error: 'Project unavailable',
            message: statusMessage
          },
          { status: 400 }
        );
      }

      // Check if freelancer has active subscription for this category
      const subscription = await prisma.categorySubscription.findFirst({
        where: {
          userId: freelancerId,
          categoryId: project.categoryId,
          status: 'ACTIVE',
          endDate: {
            gte: new Date()
          }
        }
      });

      if (!subscription) {
        return NextResponse.json(
          { 
            error: 'Subscription required',
            message: `You need an active subscription for the "${project.category.name}" category to place bids on this project. Please purchase a subscription first.`,
            requiresSubscription: true,
            categoryId: project.categoryId,
            categoryName: project.category.name
          },
          { status: 403 }
        );
      }

      const bid = await prisma.bid.create({
        data: {
          projectId,
          freelancerId,
          amount: bidPrice,
          duration: bidDays,
          proposal: proposal,
          status: 'PENDING'
        },
        include: {
          freelancer: {
            select: {
              id: true,
              email: true,
              image: true,
              profile: {
                select: {
                  firstName: true,
                  lastName: true
                }
              }
            }
          }
        }
      });

      // Initialize chat with welcome message
      try {
        const welcomeMessage = await prisma.message.create({
          data: {
            content: `Hi! I've placed a bid on your project "${project.title}". I'd be happy to discuss the requirements in more detail.`,
            senderId: freelancerId,
            receiverId: project.clientId,
            projectId: projectId,
            bidId: bid.id,
            messageType: 'text'
          }
        });
        console.log('Chat initialized with welcome message for bid:', bid.id);
      } catch (chatError) {
        console.error('Failed to initialize chat:', chatError);
        // Don't fail the bid creation if chat initialization fails
      }

      // Send notification and email to client about new bid
      try {
        await prisma.notification.create({
          data: {
            userId: project.clientId,
            type: 'bid_received',
            title: 'New Bid Received',
            message: `${bid.freelancer.profile?.firstName || 'A freelancer'} placed a bid on your project "${project.title}"`,
            data: JSON.stringify({
              projectId: projectId,
              bidId: bid.id,
              freelancerId: freelancerId,
              amount: bidPrice
            })
          }
        });

        // Send email to client
        try {
          await EmailService.sendBidReceivedEmail(project.clientId, {
            clientName: `${project.client.profile?.firstName || ''} ${project.client.profile?.lastName || ''}`.trim() || 'Client',
            projectTitle: project.title,
            freelancerName: `${bid.freelancer.profile?.firstName || ''} ${bid.freelancer.profile?.lastName || ''}`.trim() || 'Freelancer',
            bidAmount: bidPrice,
            projectUrl: `${process.env.NEXT_PUBLIC_APP_URL || 'http://46.202.162.227:3003'}/client/project-details?id=${projectId}`
          });
        } catch (emailError) {
          console.error('Failed to send bid received email:', emailError);
        }
      } catch (notificationError) {
        console.error('Failed to create notification:', notificationError);
      }

      return NextResponse.json({
        success: true,
        message: 'Bid submitted successfully',
        bid: {
          id: bid.id,
          projectId: bid.projectId,
          freelancerId: bid.freelancerId,
          amount: bid.amount,
          days: bid.duration,
          proposal: bid.proposal,
          status: bid.status,
          createdAt: bid.createdAt.toISOString(),
          freelancer: bid.freelancer
        }
      });

    } catch (dbError: any) {
      console.error('Database error:', dbError);
      
      // Return proper error response
      return NextResponse.json(
        { 
          error: 'Database operation failed',
          message: 'Unable to submit bid due to a database error. Please try again later.',
          details: process.env.NODE_ENV === 'development' ? dbError.message : undefined
        },
        { status: 500 }
      );
    }

  } catch (error: any) {
    console.error('Error submitting bid:', error);
    return NextResponse.json(
      { 
        error: 'Server error',
        message: 'An unexpected error occurred while submitting your bid. Please try again later.',
        details: process.env.NODE_ENV === 'development' ? error.message : undefined
      },
      { status: 500 }
    );
  }
}