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 {
    if (!prisma) {
      return NextResponse.json(
        { error: 'Database connection not available' },
        { status: 503 }
      );
    }

    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 sortBy = searchParams.get('sortBy') || 'cancelledAt';
    const sortOrder = searchParams.get('sortOrder') || 'desc';
    const reason = searchParams.get('reason');
    const dateFrom = searchParams.get('dateFrom');
    const dateTo = searchParams.get('dateTo');

    const skip = (page - 1) * limit;

    try {
      // Build where clause
      const whereClause: any = {
        status: 'CANCELLED',
        OR: [
          // User is the client
          { clientId: session.user.email },
          // User is the freelancer with bid
          {
            bids: {
              some: {
                freelancerId: session.user.email
              }
            }
          }
        ]
      };

      // Add date filters
      if (dateFrom || dateTo) {
        whereClause.cancellation = {
          cancelledAt: {}
        };
        
        if (dateFrom) {
          whereClause.cancellation.cancelledAt.gte = new Date(dateFrom);
        }
        
        if (dateTo) {
          whereClause.cancellation.cancelledAt.lte = new Date(dateTo);
        }
      }

      // Add reason filter
      if (reason) {
        if (!whereClause.cancellation) {
          whereClause.cancellation = {};
        }
        whereClause.cancellation.reason = reason;
      }

      // Get cancelled projects
      const [projects, totalCount] = await Promise.all([
        prisma.project.findMany({
          where: whereClause,
          include: {
            bids: {
              include: {
                freelancer: {
                  select: {
                    id: true,
                    email: true,
                    image: true,
                    profile: {
                      select: {
                        firstName: true,
                        lastName: true
                      }
                    }
                  }
                }
              }
            },
            client: {
              select: {
                id: true,
                email: true,
                image: true,
                profile: {
                  select: {
                    firstName: true,
                    lastName: true
                  }
                }
              }
            },
            category: {
              select: {
                name: true
              }
            },
            // TODO: Add cancellation relation when model is available
            // cancellation: {
            //   select: {
            //     reason: true,
            //     cancelledBy: true,
            //     cancelledAt: true,
            //     refundAmount: true,
            //     refundStatus: true,
            //     description: true
            //   }
            // },
            _count: {
              select: {
                bids: true
              }
            }
          },
          orderBy: sortBy === 'cancelledAt' 
            ? { updatedAt: sortOrder as 'asc' | 'desc' } // Use updatedAt as proxy for cancellation date
            : { [sortBy]: sortOrder as 'asc' | 'desc' },
          skip,
          take: limit
        }),
        prisma.project.count({ where: whereClause })
      ]);

      // Format response
      const formattedProjects = projects.map(project => ({
        id: project.id,
        title: project.title,
        description: project.description.substring(0, 150) + '...',
        status: project.status,
        budget: project.budget,
        currency: 'USD', // Mock currency since Project model doesn't have this field
        createdAt: project.createdAt.toISOString(),
        cancelledAt: project.updatedAt.toISOString(), // Mock cancellation date
        cancelledBy: 'client', // Mock cancellation user
        cancellationReason: 'client_request', // Mock cancellation reason
        refundAmount: null, // Mock refund amount
        refundStatus: 'not_applicable', // Mock refund status
        freelancerName: 'Mock Freelancer', // Mock freelancer name since relation doesn't exist
        clientName: `${project.client?.profile?.firstName || ''} ${project.client?.profile?.lastName || ''}`.trim() || 'Client',
        freelancerAvatar: '/assets/image/freelancer-avatar.png', // Mock freelancer avatar
        clientAvatar: project.client?.image || '/assets/image/client-avatar.png',
        category: project.category?.name || 'General',
        bidsCount: project._count.bids,
        userRole: 'client' // Only clients can access this simplified version
      }));

      return NextResponse.json({
        success: true,
        data: {
          projects: formattedProjects,
          pagination: {
            page,
            limit,
            total: totalCount,
            pages: Math.ceil(totalCount / limit)
          },
          filters: {
            sortBy,
            sortOrder,
            reason,
            dateFrom,
            dateTo
          }
        }
      });

    } catch (dbError) {
      console.error('Database query error:', dbError);
      
      // Return mock cancelled projects when database is not ready
      const mockProjects = [
        {
          id: 'cancelled-1',
          title: 'Laravel E-Commerce Website Development',
          description: 'Develop a modern responsive website with user authentication and payment integration...',
          status: 'cancelled',
          budget: 2000,
          currency: 'EUR',
          createdAt: '2024-06-01T10:00:00Z',
          cancelledAt: '2024-06-15T14:30:00Z',
          cancelledBy: 'client',
          cancellationReason: 'scope_change',
          refundAmount: 1500,
          refundStatus: 'processed',
          freelancerName: 'John Developer',
          clientName: 'Esther Howard',
          freelancerAvatar: '/assets/image/freelancer-avatar.png',
          clientAvatar: '/assets/image/profile02.png',
          category: 'Web Development',
          bidsCount: 4,
          userRole: session.user.email === 'freelancer-1' ? 'freelancer' : 'client'
        },
        {
          id: 'cancelled-2',
          title: 'Mobile App UI/UX Design',
          description: 'Design modern mobile application interface with user-friendly experience...',
          status: 'cancelled',
          budget: 1200,
          currency: 'USD',
          createdAt: '2024-05-20T09:15:00Z',
          cancelledAt: '2024-05-28T11:45:00Z',
          cancelledBy: 'freelancer',
          cancellationReason: 'freelancer_unavailable',
          refundAmount: null,
          refundStatus: 'not_applicable',
          freelancerName: 'Jane Designer',
          clientName: 'Mike Johnson',
          freelancerAvatar: '/assets/image/freelancer-avatar.png',
          clientAvatar: '/assets/image/client-avatar.png',
          category: 'UI/UX Design',
          bidsCount: 7,
          userRole: session.user.email === 'freelancer-1' ? 'freelancer' : 'client'
        }
      ];

      return NextResponse.json({
        success: true,
        data: {
          projects: mockProjects,
          pagination: {
            page: 1,
            limit: 10,
            total: 2,
            pages: 1
          },
          filters: {
            sortBy: 'cancelledAt',
            sortOrder: 'desc',
            reason: null,
            dateFrom: null,
            dateTo: null
          }
        }
      });
    }

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