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

    const { searchParams } = new URL(req.url);
    const page = parseInt(searchParams.get('page') || '1');
    const limit = parseInt(searchParams.get('limit') || '10');
    const status = searchParams.get('status');
    
    const skip = (page - 1) * limit;

    // Build where clause
    const whereClause: any = {
      freelancerId: session.user.email
    };

    if (status && status !== 'all') {
      whereClause.status = status.toUpperCase();
    }

    // Get bids
    const [bids, totalCount] = await Promise.all([
      prisma.bid.findMany({
        where: whereClause,
        skip,
        take: limit,
        orderBy: { createdAt: 'desc' },
        include: {
          project: {
            select: {
              id: true,
              title: true,
              description: true,
              category: true,
              budget: true,
              status: true,
              client: {
                select: {
                  id: true,
                  email: true,
                  image: true
                }
              }
            }
          }
        }
      }),
      prisma.bid.count({ where: whereClause })
    ]);

    // Format bids data
    const formattedBids = bids.map((bid: any) => ({
      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'
        }
      }
    }));

    const totalPages = Math.ceil(totalCount / limit);
    const hasNextPage = page < totalPages;
    const hasPrevPage = page > 1;

    return NextResponse.json({
      success: true,
      data: {
        bids: formattedBids,
        pagination: {
          currentPage: page,
          totalPages,
          totalItems: totalCount,
          itemsPerPage: limit,
          hasNextPage,
          hasPrevPage
        }
      }
    });

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

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

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

    // Validate required fields
    if (!projectId || !amount || !proposal) {
      return NextResponse.json(
        { error: 'Missing required fields: projectId, amount, proposal' },
        { status: 400 }
      );
    }

    // Validate field types and values
    if (typeof amount !== 'number' || amount <= 0) {
      return NextResponse.json(
        { error: 'Amount must be a positive number' },
        { status: 400 }
      );
    }


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

    // Check if project exists and is open
    const project = await prisma.project.findUnique({
      where: { id: projectId },
      select: { 
        id: true, 
        title: true,
        status: true,
        clientId: true,
        client: {
          select: {
            id: true,
            email: true
          }
        }
      }
    });

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

    if (project.status !== 'OPEN') {
      return NextResponse.json(
        { error: 'Project is not open for bidding' },
        { status: 400 }
      );
    }

    // Check if freelancer is trying to bid on their own project (if they're also a client)
    if (project.clientId === session.user.email) {
      return NextResponse.json(
        { error: 'You cannot bid on your own project' },
        { status: 400 }
      );
    }

    // Check if freelancer has already bid on this project
    const existingBid = await prisma.bid.findFirst({
      where: {
        projectId,
        freelancerId: session.user.email
      }
    });

    if (existingBid) {
      return NextResponse.json(
        { error: 'You have already submitted a bid for this project' },
        { status: 400 }
      );
    }

    // Create the bid
    const bid = await prisma.bid.create({
      data: {
        amount: parseFloat(amount.toString()),
        proposal: proposal.trim(),
        projectId,
        freelancerId: session.user.email,
        status: 'PENDING',
        duration: 7
      },
      include: {
        project: {
          select: {
            id: true,
            title: true,
            client: {
              select: {
                email: true
              }
            }
          }
        },
        freelancer: {
          select: {
            email: true
          }
        }
      }
    });

    // TODO: Send notification to project owner about new bid
    // You can add email notification logic here

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

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