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 { projectId } = await params;
    console.log(`API Route - projectId: `, projectId);

    if (!projectId) {
      return NextResponse.json(
        { 
          error: 'Project ID is required to fetch project details.',
          details: 'Missing projectId parameter'
        },
        { status: 400 }
      );
    }

    try {
      console.log('Attempting database query...');
      
      // Get session to check user bid status
      const session = await getServerSession(authOptions);
      console.log('session ====', session);
      const currentUserId = session?.user?.id;
      
      // Session can be undefined during SSR or when user is not logged in
      // This is normal and should not cause the request to fail
      
      // Get project details
      const project = await prisma.project.findFirst({
        where: {
          id: projectId,
        },
        include: {
          client: {
            select: {
              id: true,
              email: true,
              image: true,
              createdAt: true,
              profile: {
                select: {
                  firstName: true,
                  lastName: true
                }
              },
              _count: {
                select: {
                  receivedReviews: true
                }
              }
            }
          },
          category: {
            select: {
              id: true,
              name: true,
              icon: true
            }
          },
          bids: {
            include: {
              freelancer: {
                select: {
                  id: true,
                  email: true,
                  image: true,
                  createdAt: true,
                  profile: {
                    select: {
                      firstName: true,
                      lastName: true
                    }
                  },
                  _count: {
                    select: {
                      receivedReviews: true
                    }
                  }
                }
              }
            }
          },
          _count: {
            select: {
              bids: true,
              messages: {
                where: {
                  isRead: false
                }
              }
            }
          }
        }
      });

      if (!project) {
        console.log('Project not found in database, returning mock data');
        return NextResponse.json({
          success: false,
          error: 'Project not found'
        });
      }

      // Get the accepted freelancer (if any)
      const acceptedBid = project.bids.find(bid => bid.status === 'ACCEPTED');
      const freelancer = acceptedBid?.freelancer;
      
      // Get freelancer reviews count and rating
      let freelancerReviews = null;
      if (freelancer) {
        freelancerReviews = await prisma.review.aggregate({
          where: { recipientId: freelancer.id },
          _avg: { rating: true },
          _count: { rating: true }
        });
      }
      
      // Check if current user has already bid on this project
      const currentUserBid = currentUserId ? project.bids.find(bid => bid.freelancerId === currentUserId) : null;

      // Get project documents from attachments field
      let documents: any[] = [];
      console.log('🔍 Processing project attachments...');
      console.log('Raw attachments field:', project.attachments);
      console.log('Attachments type:', typeof project.attachments);
      console.log('Attachments length:', project.attachments?.length || 0);
      
      if (project.attachments) {
        try {
          // Check if the attachments string is properly formatted JSON
          const attachmentsStr = project.attachments.trim();

          // Validate that the JSON string is complete (ends with ] for array or } for object)
          if (!attachmentsStr.endsWith(']') && !attachmentsStr.endsWith('}')) {
            console.warn('⚠️ Attachments JSON appears to be truncated:', attachmentsStr);
            console.warn('⚠️ String length:', attachmentsStr.length);
            console.warn('⚠️ Last 50 characters:', attachmentsStr.slice(-50));

            // Try to repair common truncation cases
            let repairedJson = attachmentsStr;

            // If it looks like a truncated array, try to close it
            if (attachmentsStr.startsWith('[') && !attachmentsStr.endsWith(']')) {
              // Find the last complete object
              const lastCompleteObject = attachmentsStr.lastIndexOf('}');
              if (lastCompleteObject !== -1) {
                repairedJson = attachmentsStr.substring(0, lastCompleteObject + 1) + ']';
                console.log('🔧 Attempting to repair JSON by closing array at last complete object');
              } else {
                // If no complete object found, return empty array
                repairedJson = '[]';
                console.log('🔧 No complete objects found, using empty array');
              }
            }

            // Try parsing the repaired JSON
            try {
              const attachmentsData = JSON.parse(repairedJson);
              console.log('✅ Successfully parsed repaired JSON');
              console.log('📄 Repaired attachments data:', attachmentsData);

              if (Array.isArray(attachmentsData)) {
                documents = attachmentsData.map((doc: any, index: number) => {
                  console.log(`📎 Processing document ${index + 1}:`, doc);
                  return {
                    id: doc.id || `doc-${index + 1}`,
                    name: doc.name || doc.originalName || doc.filename || `Document ${index + 1}`,
                    originalName: doc.originalName || doc.name || doc.filename,
                    size: doc.size || doc.fileSize || 'Unknown size',
                    type: doc.type || doc.fileType || doc.mimeType || 'application/octet-stream',
                    url: doc.url || doc.fileUrl || '#',
                    uploadedBy: project.client?.profile ?
                      `${project.client.profile.firstName || ''} ${project.client.profile.lastName || ''}`.trim() || project.client.email :
                      project.client?.email || 'Client',
                    createdAt: doc.createdAt || project.createdAt.toISOString()
                  };
                });
                console.log('✅ Successfully processed documents from repaired JSON:', documents.length);
              }
            } catch (repairError) {
              console.error('❌ Failed to parse even repaired JSON:', repairError);
              documents = [];
            }
          } else {
            // JSON appears complete, parse normally
            const attachmentsData = JSON.parse(attachmentsStr);
            console.log('📄 Parsed attachments data:', attachmentsData);
            console.log('📄 Is array?', Array.isArray(attachmentsData));
            console.log('📄 Array length:', Array.isArray(attachmentsData) ? attachmentsData.length : 'N/A');

            if (Array.isArray(attachmentsData)) {
              documents = attachmentsData.map((doc: any, index: number) => {
                console.log(`📎 Processing document ${index + 1}:`, doc);
                return {
                  id: doc.id || `doc-${index + 1}`,
                  name: doc.name || doc.originalName || doc.filename || `Document ${index + 1}`,
                  originalName: doc.originalName || doc.name || doc.filename,
                  size: doc.size || doc.fileSize || 'Unknown size',
                  type: doc.type || doc.fileType || doc.mimeType || 'application/octet-stream',
                  url: doc.url || doc.fileUrl || '#',
                  uploadedBy: project.client?.profile ?
                    `${project.client.profile.firstName || ''} ${project.client.profile.lastName || ''}`.trim() || project.client.email :
                    project.client?.email || 'Client',
                  createdAt: doc.createdAt || project.createdAt.toISOString()
                };
              });
              console.log('✅ Successfully processed documents:', documents.length);
            } else {
              console.log('⚠️ Attachments data is not an array:', attachmentsData);
              documents = [];
            }
          }
        } catch (error) {
          console.error('❌ Error parsing project attachments:', error);
          console.log('Raw data that failed to parse:', project.attachments);
          console.log('Data length:', project.attachments?.length);
          console.log('Data ends with:', project.attachments?.slice(-10));
          documents = [];
        }
      } else {
        console.log('ℹ️ No attachments field found on project');
      }
      
      console.log('📊 Final documents array length:', documents.length);

      // Calculate project progress (mock calculation based on status)
      let progress = 0;
      switch (project.status) {
        case 'OPEN':
          progress = 10;
          break;
        case 'IN_PROGRESS':
          progress = 45;
          break;
        case 'COMPLETED':
          progress = 100;
          break;
        case 'CANCELLED':
          progress = 0;
          break;
        case 'DRAFT':
          progress = 0;
          break;
        default:
          progress = 0;
      }

      // Determine user role based on session
      const userRole = currentUserId === project.clientId ? 'client' : 'freelancer';
      
      // Get client reviews count and rating
      const clientReviews = await prisma.review.aggregate({
        where: { recipientId: project.clientId },
        _avg: { rating: true },
        _count: { rating: true }
      });


      // Format response data to match frontend interface
      const responseData = {
        id: project.id,
        title: project.title,
        description: project.description,
        status: project.status === 'IN_PROGRESS' ? 'ongoing' : 
                project.status === 'OPEN' ? 'active' :
                project.status.toLowerCase(),
        budget: project.budget,
        currency: '€',
        duration: project.duration,
        deadline: new Date(Date.now() + project.duration * 24 * 60 * 60 * 1000).toISOString(),
        createdAt: project.createdAt.toISOString(),
        startedAt: project.publishedAt?.toISOString() || null,
        completedAt: project.completedAt?.toISOString() || null,
        cancelledAt: null,
        freelancerId: freelancer?.id || null,
        clientId: project.clientId,
        freelancerName: freelancer && freelancer.profile ? 
          `${freelancer.profile.firstName || ''} ${freelancer.profile.lastName || ''}`.trim() || freelancer.email :
          freelancer?.email || null,
        freelancerAvatar: freelancer?.image || null,
        freelancerRating: freelancerReviews?._avg.rating || null,
        freelancerReviewsCount: freelancerReviews?._count.rating || null,
        clientName: project.client?.profile ? 
          `${project.client.profile.firstName || ''} ${project.client.profile.lastName || ''}`.trim() || project.client.email :
          project.client?.email || 'Unknown Client',
        clientAvatar: project.client?.image || '/assets/image/user.png',
        clientRating: clientReviews._avg.rating || 0,
        clientReviewsCount: clientReviews._count.rating || 0,
        clientProjectsCount: 0, // TODO: Add proper project count calculation
        clientMemberSince: new Date(project.client?.createdAt || new Date()).getFullYear().toString(),
        clientLocation: 'Location not specified',
        category: project.category?.name || 'General',
        categoryIcon: project.category?.icon || '/assets/image/cabinetmaking.svg',
        userRole: userRole,
        progress: progress,
        documents: documents,
        currentMilestone: project.status === 'IN_PROGRESS' ? 'Development Phase' : null,
        // bidAmount: currentUserBid?.amount ?? '00',
        bidAmount: acceptedBid?.amount,
        bidStatus: currentUserBid?.status,
        bidsCount: project._count?.bids || 0,
        hasUserBid: !!currentUserBid,
        userBidStatus: currentUserBid?.status,
        userBidAmount: currentUserBid?.amount,
        userBidId: currentUserBid?.id,
        userBidDuration: currentUserBid?.duration
      };

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

    } catch (dbError) {
      console.error('Database query error:', dbError);
      
      let errorMessage = 'Unable to load project details at this time. Please try again later.';
      let details = 'Unknown database error';
      
      if (dbError instanceof Error) {
        details = dbError.message;
        
        if (dbError.message.includes('connect') || dbError.message.includes('ECONNREFUSED')) {
          errorMessage = 'Database connection failed. Please contact support if this persists.';
        } else if (dbError.message.includes('not found') || dbError.message.includes('P2025')) {
          errorMessage = 'The requested project was not found.';
        } else if (dbError.message.includes('timeout')) {
          errorMessage = 'Request timed out. Please try again.';
        }
      }
      
      return NextResponse.json(
        { 
          error: errorMessage,
          details: details
        },
        { status: 500 }
      );
    }

  } catch (error) {
    console.error('Error fetching project details:', error);
    
    let errorMessage = 'An unexpected error occurred while fetching project details.';
    let details = 'Unknown error';
    
    if (error instanceof Error) {
      details = error.message;
      
      if (error.message.includes('Invalid') || error.message.includes('validation')) {
        errorMessage = 'Invalid project ID provided.';
      }
    }
    
    return NextResponse.json(
      { 
        error: errorMessage,
        details: details
      },
      { status: 500 }
    );
  }
}