import { Metadata } from 'next';
import FreelancersList from '@/components/public/FreelancersList';
import { prisma } from '@/lib/prisma';
import PostProjectSection from '@/components/sections/PostProjectSection';
import Footer from '@/components/Footer';
import './freelancers.css';

interface FreelancersPageProps {
  params: Promise<{
    locale: string;
  }>;
  searchParams: Promise<{
    category?: string;
    search?: string;
    location?: string;
    rating?: string;
    sort?: string;
    page?: string;
  }>;
}

export async function generateMetadata({ params }: FreelancersPageProps): Promise<Metadata> {
  return {
    title: 'Find Freelancers - Smile24',
    description: 'Browse and connect with talented freelancers for your projects',
  };
}

async function getFreelancers(searchParams: any) {
  try {
    if (!prisma) {
      // Return mock data when database is not available
      return {
        freelancers: [
        ],
        totalCount: 0,
        totalPages: 1,
        currentPage: 1
      };
    }

    // Extract search parameters
    const page = parseInt(searchParams.page || '1');
    const limit = 12;
    const skip = (page - 1) * limit;
    const search = searchParams.search || '';
    const category = searchParams.category || '';
    const location = searchParams.location || '';
    const rating = searchParams.rating || '';
    const sort = searchParams.sort || 'newest';

    // Build where clause
    let whereClause: any = {
      role: 'FREELANCER',
      profile: {
        isNot: null
      }
    };

    // Collect profile conditions
    const profileConditions: any = {};

    // Add category filter - check for freelancers subscribed to the category
    if (category) {
      profileConditions.categories = {
        some: {
          category: {
            slug: category
          }
        }
      };
    }

    // Add location filter
    if (location) {
      console.log('Location filter applied:', location);
      profileConditions.country = {
        name: location
      };
    }

    // Merge profile conditions
    if (Object.keys(profileConditions).length > 0) {
      whereClause.profile = {
        ...whereClause.profile,
        ...profileConditions
      };
    }

    // Add search filter
    if (search) {
      if (whereClause.AND) {
        whereClause.AND.push({
          OR: [
            {
              profile: {
                firstName: { contains: search }
              }
            },
            {
              profile: {
                lastName: { contains: search }
              }
            },
            {
              profile: {
                title: { contains: search }
              }
            },
            {
              profile: {
                skills: { contains: search }
              }
            },
            {
              email: { contains: search }
            }
          ]
        });
      } else {
        whereClause.AND = [
          {
            OR: [
              {
                profile: {
                  firstName: { contains: search }
                }
              },
              {
                profile: {
                  lastName: { contains: search }
                }
              },
              {
                profile: {
                  title: { contains: search }
                }
              },
              {
                profile: {
                  skills: { contains: search }
                }
              },
              {
                email: { contains: search }
              }
            ]
          }
        ];
      }
    }

    // Note: Rating filter would need to be implemented based on review aggregation
    // For now, we'll skip this filter as User model doesn't have direct rating field
    if (rating) {
      // This would require a complex aggregation query on reviews
      // Skipping for now to avoid schema errors
    }

    // Build order by clause
    let orderBy: any = { createdAt: 'desc' };
    if (sort === 'newest') {
      orderBy = { createdAt: 'desc' };
    } else if (sort === 'oldest') {
      orderBy = { createdAt: 'asc' };
    }

    // Get freelancers with error handling for categories
    let freelancers;
    try {
      freelancers = await prisma.user.findMany({
        where: whereClause,
        include: {
          profile: {
            include: {
              categories: {
                include: {
                  category: true
                }
              },
              country: true
            }
          },
          _count: {
            select: {
              freelancerBids: true,
              receivedReviews: true
            }
          },
          receivedReviews: true
        },
        orderBy
      });
    } catch (error: any) {
      console.log('Error with categories relationship, falling back to keyword search:', error.message);
      
      // If categories/country relationship fails, fall back to alternative approaches
      if (category) {
        // Remove the category condition from profileConditions
        delete profileConditions.categories;
        
        // Add keyword-based category filtering
        const categoryKeywords: Record<string, string[]> = {
          'web-development': ['web', 'website', 'javascript', 'react', 'node', 'html', 'css', 'frontend', 'backend'],
          'graphic-design': ['design', 'graphic', 'logo', 'photoshop', 'illustrator', 'branding', 'visual'],
          'writing': ['writing', 'content', 'blog', 'copywriting', 'article', 'editing', 'proofreading'],
          'marketing': ['marketing', 'seo', 'social', 'ads', 'promotion', 'digital', 'campaign'],
          'mobile-development': ['mobile', 'android', 'ios', 'react native', 'flutter', 'app'],
          'data-science': ['data', 'python', 'analytics', 'machine learning', 'ai', 'statistics']
        };
        
        const keywords = categoryKeywords[category] || [category.replace('-', ' ')];
        const categoryCondition = {
          OR: keywords.flatMap(keyword => [
            { profile: { skills: { contains: keyword } } },
            { profile: { title: { contains: keyword } } },
            { profile: { bio: { contains: keyword } } }
          ])
        };
        
        if (whereClause.AND) {
          whereClause.AND.push(categoryCondition);
        } else {
          whereClause.AND = [categoryCondition];
        }
      }

      if (location) {
        // Remove the country condition from profileConditions
        delete profileConditions.country;
        
        // Add location-based filtering using city or bio fields as fallback
        const locationCondition = {
          OR: [
            { profile: { city: { contains: location } } },
            { profile: { bio: { contains: location } } }
          ]
        };
        
        if (whereClause.AND) {
          whereClause.AND.push(locationCondition);
        } else {
          whereClause.AND = [locationCondition];
        }
      }
      
      // Rebuild whereClause
      whereClause.profile = {
        isNot: null,
        ...profileConditions
      };
      
      // Retry query without categories include
      freelancers = await prisma.user.findMany({
        where: whereClause,
        include: {
          profile: {
            include: {
              country: true
            }
          },
          _count: {
            select: {
              freelancerBids: true,
              receivedReviews: true
            }
          },
          receivedReviews: true
        },
        orderBy
      });
    }

    if (rating) {
      const minRating = parseInt(rating);
      freelancers = freelancers.filter((f: any) => {
        const avgRating = f.receivedReviews.length > 0 ? f.receivedReviews.reduce((acc: number, r: { rating: number }) => acc + r.rating, 0) / f.receivedReviews.length : 0;
        return avgRating >= minRating;
      });
    }

    const totalCount = freelancers.length;
    const totalPages = Math.ceil(totalCount / limit);
    const paginatedFreelancers = freelancers.slice(skip, skip + limit);

    const formattedFreelancers = paginatedFreelancers.map((freelancer: any) => ({
      id: freelancer.id,
      name: freelancer.profile ? 
        `${freelancer.profile.firstName || ''} ${freelancer.profile.lastName || ''}`.trim() || freelancer.email :
        freelancer.email,
      email: freelancer.email,
      profileImage: freelancer.profile?.profileImage || freelancer.image || '/assets/image/user.png',
      bio: freelancer.profile?.bio || 'Experienced freelancer ready to work on your projects',
      rating: 4.0 + Math.random() * 1, // Mock rating between 4.0 and 5.0
      reviewCount: freelancer._count?.receivedReviews || Math.floor(Math.random() * 50) + 5,
      skills: freelancer.profile?.skills ? 
        (typeof freelancer.profile.skills === 'string' ? JSON.parse(freelancer.profile.skills) : freelancer.profile.skills) :
        ['React', 'Node.js', 'TypeScript'],
      hourlyRate: freelancer.profile?.hourlyRate || (50 + Math.floor(Math.random() * 100)),
      location: freelancer.profile?.city && freelancer.profile?.country?.name ? 
        `${freelancer.profile.city}, ${freelancer.profile.country.name}` : 
        'Remote',
      completedProjects: Math.floor(Math.random() * 50) + 10,
      category: 'Web Development' // This would need to be added to profile schema
    }));

    return {
      freelancers: formattedFreelancers,
      totalCount,
      totalPages,
      currentPage: page
    };

  } catch (error) {
    console.error('Error fetching freelancers:', error);
    // Return mock data on error
    return {
      freelancers: [],
      totalCount: 0,
      totalPages: 1,
      currentPage: 1
    };
  }
}

async function getCategories() {
  try {
    if (!prisma) {
      return [
        { id: '1', name: 'Web Development', slug: 'web-development' },
        { id: '2', name: 'Graphic Design', slug: 'graphic-design' },
        { id: '3', name: 'Writing', slug: 'writing' },
        { id: '4', name: 'Marketing', slug: 'marketing' }
      ];
    }

    const categories = await prisma.category.findMany({
      select: {
        id: true,
        name: true,
        slug: true
      },
      orderBy: { name: 'asc' }
    });

    return categories;
  } catch (error) {
    console.error('Error fetching categories:', error);
    return [];
  }
}

async function getCountries() {
  try {
    if (!prisma) {
      return [
        { id: '1', name: 'United States', code: 'US', _count: { profiles: 15 } },
        { id: '2', name: 'United Kingdom', code: 'UK', _count: { profiles: 12 } },
        { id: '3', name: 'Canada', code: 'CA', _count: { profiles: 8 } },
        { id: '4', name: 'Australia', code: 'AU', _count: { profiles: 6 } }
      ];
    }

    const countries = await prisma.country.findMany({
      orderBy: {
        name: 'asc'
      }
    });

    // Add mock profile counts
    const countriesWithCounts = countries.map((country: any) => ({
      ...country,
      _count: {
        profiles: Math.floor(Math.random() * 20) + 1
      }
    }));
    
    return countriesWithCounts;
  } catch (error) {
    console.error('Error fetching countries:', error);
    return [];
  }
}

export default async function FreelancersPage({ params, searchParams }: FreelancersPageProps) {
  const { locale } = await params;
  const { category, search, location, rating, sort, page = '1' } = await searchParams;

  const resolvedSearchParams = await searchParams;
  const freelancersData = await getFreelancers(resolvedSearchParams);
  const categories = await getCategories();
  const countries = await getCountries();

  const { freelancers, totalCount, totalPages, currentPage } = freelancersData;

  return (
    <>
      
      {/* Hero Section */}
      <section className="inner-hero-wrapper">
        <div className="container">
          <div className="row">
            <div className="col-12 col-md-7 col-lg-8 align-self-center">
              <div className="hero-content">
                <h1>Top Freelancers For Your Project</h1>
                <p>Discover experienced freelancers ready to work on your next project</p>
              </div>
            </div>
            <div className="col-12 col-md-5 col-lg-4 align-self-end">
              <div className="inner-hero-img text-center pt-3">
                <img src="/assets/image/service-banner-img.svg" alt="service-banner-img" />
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Freelancers Section */}
      <section className="freelancers-page py-60">
        <div className="container">
          <FreelancersList
            freelancers={freelancers}
            categories={categories}
            countries={countries}
            currentPage={currentPage}
            totalPages={totalPages}
            totalCount={totalCount}
            currentCategory={category}
            currentSearch={search}
            currentLocation={location}
            currentRating={rating}
            currentSort={sort}
            locale={locale}
          />
        </div>
      </section>


      {/* Post Project Section */}
      <PostProjectSection locale={locale} />

      {/* Footer */}
      <Footer locale={locale} />
    </>
  );
}
