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<{ projectId: string }> }
) {
  try {
    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 {
      if (!prisma) {
        throw new Error('Database connection not available');
      }

      // Get project details with related data
      const project = await prisma.project.findFirst({
        where: {
          id: projectId,
          status: '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,
                  image: true,
                  profile: {
                    select: {
                      firstName: true,
                      lastName: true
                    }
                  }
                }
              }
            }
          },
          client: {
            select: {
              id: true,
              email: true,
              image: true,
              createdAt: true,
              profile: {
                select: {
                  firstName: true,
                  lastName: true
                }
              },
              _count: {
                select: {
                  receivedReviews: true,
                  clientProjects: true
                }
              }
            }
          },
          category: {
            select: {
              name: true
            }
          }
          // TODO: Add these relations when models are available
          // documents: {
          //   select: {
          //     id: true,
          //     name: true,
          //     type: true,
          //     url: true,
          //     uploadedAt: true,
          //     uploadedBy: true
          //   }
          // },
          // milestones: {
          //   where: {
          //     status: 'IN_PROGRESS'
          //   },
          //   select: {
          //     title: true
          //   },
          //   take: 1
          // }
        }
      });

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

      // TODO: Re-enable when projectMilestone model is available
      // const allMilestones = await prisma.projectMilestone.findMany({
      //   where: { projectId },
      //   select: { progress: true }
      // });
      // const overallProgress = allMilestones.length > 0 
      //   ? Math.round(allMilestones.reduce((sum, m) => sum + m.progress, 0) / allMilestones.length)
      //   : 0;
      
      // Mock progress calculation
      const overallProgress = 65;

      // TODO: Fix when freelancerId field is available
      // Determine user role - for now assume client role
      const acceptedBid = project.bids.find(bid => bid.status === 'ACCEPTED');
      const userRole = acceptedBid && session.user.email === acceptedBid.freelancerId ? 'freelancer' : 'client';

      // Format response
      const formattedProject = {
        id: project.id,
        title: project.title,
        description: project.description,
        status: project.status,
        budget: project.budget,
        currency: 'USD', // Mock currency since Project model doesn't have this field
        deadline: new Date(Date.now() + project.duration * 24 * 60 * 60 * 1000).toISOString(), // Calculate from duration
        createdAt: project.createdAt.toISOString(),
        startedAt: project.publishedAt?.toISOString() || project.createdAt.toISOString(),
        freelancerId: acceptedBid?.freelancerId || null,
        clientId: project.clientId,
        freelancerName: acceptedBid?.freelancer?.profile ? `${acceptedBid.freelancer.profile.firstName || ''} ${acceptedBid.freelancer.profile.lastName || ''}`.trim() : 'Unknown Freelancer',
        clientName: project.client.profile ? `${project.client.profile.firstName || ''} ${project.client.profile.lastName || ''}`.trim() : 'Unknown Client',
        clientAvatar: project.client.image || '/assets/image/default-avatar.png',
        clientRating: 0,
        clientReviewsCount: project.client._count.receivedReviews || 0,
        clientProjectsCount: project.client._count.clientProjects || 0,
        clientMemberSince: new Date(project.client.createdAt).getFullYear().toString(),
        clientLocation: 'Location not specified', // TODO: Add when location field is available
        category: project.category?.name || 'General',
        userRole,
        progress: overallProgress,
        documents: [], // TODO: Add when documents relation is available
        currentMilestone: null // TODO: Add when milestones relation is available
      };

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

    } catch (dbError) {
      console.error('Database query error:', dbError);
      
      // Return mock data when database is not available
      const mockProject = {
        id: projectId,
        title: 'E-commerce Website Development',
        description: 'Develop a modern, responsive e-commerce website with payment integration, user authentication, and admin panel. The website should support multiple product categories, shopping cart functionality, and order management system.',
        status: 'ongoing' as const,
        budget: 2500,
        currency: 'USD',
        deadline: '2024-08-15T00:00:00Z',
        createdAt: '2024-06-01T09:00:00Z',
        startedAt: '2024-06-03T10:30:00Z',
        freelancerId: 'freelancer-123',
        clientId: 'client-456',
        freelancerName: 'John Smith',
        clientName: 'Sarah Johnson',
        clientAvatar: '/assets/image/haroldgunderson.png',
        clientRating: 4.8,
        clientReviewsCount: 24,
        clientProjectsCount: 12,
        clientMemberSince: '2022',
        clientLocation: 'New York, USA',
        category: 'Web Development',
        userRole: 'freelancer' as const,
        progress: 65,
        documents: [
          {
            id: 'doc-1',
            name: 'Project Requirements.pdf',
            type: 'pdf',
            url: '/assets/documents/requirements.pdf',
            uploadedAt: '2024-06-01T09:15:00Z',
            uploadedBy: 'Sarah Johnson (Client)'
          },
          {
            id: 'doc-2',
            name: 'Brand Guidelines.zip',
            type: 'zip',
            url: '/assets/documents/brand-guidelines.zip',
            uploadedAt: '2024-06-02T14:20:00Z',
            uploadedBy: 'Sarah Johnson (Client)'
          },
          {
            id: 'doc-3',
            name: 'Technical Specification.docx',
            type: 'docx',
            url: '/assets/documents/tech-spec.docx',
            uploadedAt: '2024-06-03T11:45:00Z',
            uploadedBy: 'John Smith (Freelancer)'
          }
        ],
        currentMilestone: 'Development Phase 2'
      };

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

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

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

    const { projectId } = await params;
    const body = await req.json();
    const { status, progress } = body;

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

    try {
      if (!prisma) {
        throw new Error('Database connection not available');
      }

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

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

      // Update project
      const updatedProject = await prisma.project.update({
        where: { id: projectId },
        data: {
          ...(status && { status }),
          ...(progress !== undefined && { progress }),
          updatedAt: new Date()
        }
      });

      return NextResponse.json({
        success: true,
        message: 'Project updated successfully',
        data: {
          id: updatedProject.id,
          status: updatedProject.status,
          progress: 50 // Mock progress since Project model doesn't have this field
        }
      });

    } catch (dbError) {
      console.error('Database error during project update:', dbError);
      
      return NextResponse.json({
        success: true,
        message: 'Project update request received (database not available)',
        data: {
          id: projectId,
          status,
          progress
        }
      });
    }

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