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,
  { params }: { params: Promise<{ bidId: string }> }
) {
  try {
    const session = await getServerSession(authOptions);
    
    if (!session?.user?.email) {
      return NextResponse.json(
        { error: 'Unauthorized' },
        { status: 401 }
      );
    }

    const { bidId } = await params;

    const bid = await prisma.bid.findFirst({
      where: {
        id: bidId,
        freelancerId: session.user.email
      },
      include: {
        project: {
          select: {
            id: true,
            title: true,
            description: true,
            category: true,
            budget: true,
            status: true,
            client: {
              select: {
                id: true,
                email: true,
                image: true
              }
            }
          }
        }
      }
    });

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

    const formattedBid = {
      id: bid.id,
      amount: bid.amount,
      proposal: bid.proposal,
      status: bid.status,
      createdAt: bid.createdAt.toISOString(),
      updatedAt: bid.updatedAt.toISOString(),
      project: {
        id: bid.project.id,
        title: bid.project.title,
        description: bid.project.description,
        category: bid.project.category,
        budget: bid.project.budget,
        status: bid.project.status,
        client: {
          id: bid.project.client.id,
          name: bid.project.client.email,
          profileImage: bid.project.client.image || '/assets/image/user.png'
        }
      }
    };

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

  } catch (error) {
    console.error('Error fetching bid:', error);
    return NextResponse.json(
      { error: 'Failed to fetch bid' },
      { status: 500 }
    );
  }
}

export async function PUT(
  req: NextRequest,
  { params }: { params: Promise<{ bidId: string }> }
) {
  try {
    const session = await getServerSession(authOptions);
    
    if (!session?.user?.email) {
      return NextResponse.json(
        { error: 'Unauthorized' },
        { status: 401 }
      );
    }

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

    // Check if bid exists and belongs to the freelancer
    const existingBid = await prisma.bid.findFirst({
      where: {
        id: bidId,
        freelancerId: session.user.email
      },
      include: {
        project: {
          select: {
            status: true
          }
        }
      }
    });

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

    // Check if bid can be updated (only pending bids on open projects)
    if (existingBid.status !== 'PENDING') {
      return NextResponse.json(
        { error: 'Cannot update bid that is not pending' },
        { status: 400 }
      );
    }

    if (existingBid.project.status !== 'OPEN') {
      return NextResponse.json(
        { error: 'Cannot update bid on closed project' },
        { status: 400 }
      );
    }

    // Validate fields if provided
    const updateData: any = {};
    
    if (amount !== undefined) {
      if (typeof amount !== 'number' || amount <= 0) {
        return NextResponse.json(
          { error: 'Amount must be a positive number' },
          { status: 400 }
        );
      }
      updateData.amount = parseFloat(amount.toString());
    }


    if (proposal !== undefined) {
      if (typeof proposal !== 'string' || proposal.trim().length < 10) {
        return NextResponse.json(
          { error: 'Proposal must be at least 10 characters long' },
          { status: 400 }
        );
      }
      updateData.proposal = proposal.trim();
    }

    if (Object.keys(updateData).length === 0) {
      return NextResponse.json(
        { error: 'No valid fields to update' },
        { status: 400 }
      );
    }

    // Update the bid
    const updatedBid = await prisma.bid.update({
      where: { id: bidId },
      data: updateData,
      include: {
        project: {
          select: {
            id: true,
            title: true
          }
        }
      }
    });

    return NextResponse.json({
      success: true,
      data: {
        bid: {
          id: updatedBid.id,
          amount: updatedBid.amount,
          proposal: updatedBid.proposal,
          status: updatedBid.status,
          updatedAt: updatedBid.updatedAt.toISOString(),
          project: {
            id: updatedBid.project.id,
            title: updatedBid.project.title
          }
        }
      },
      message: 'Bid updated successfully'
    });

  } catch (error) {
    console.error('Error updating bid:', error);
    return NextResponse.json(
      { error: 'Failed to update bid' },
      { status: 500 }
    );
  }
}

export async function DELETE(
  req: NextRequest,
  { params }: { params: Promise<{ bidId: string }> }
) {
  try {
    const session = await getServerSession(authOptions);
    
    if (!session?.user?.email) {
      return NextResponse.json(
        { error: 'Unauthorized' },
        { status: 401 }
      );
    }

    const { bidId } = await params;

    // Check if bid exists and belongs to the freelancer
    const existingBid = await prisma.bid.findFirst({
      where: {
        id: bidId,
        freelancerId: session.user.email
      },
      include: {
        project: {
          select: {
            status: true,
            title: true
          }
        }
      }
    });

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

    // Check if bid can be withdrawn (only pending bids)
    if (existingBid.status !== 'PENDING') {
      return NextResponse.json(
        { error: 'Cannot withdraw bid that is not pending' },
        { status: 400 }
      );
    }

    // Delete the bid (withdraw)
    await prisma.bid.delete({
      where: { id: bidId }
    });

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

  } catch (error) {
    console.error('Error withdrawing bid:', error);
    return NextResponse.json(
      { error: 'Failed to withdraw bid' },
      { status: 500 }
    );
  }
}