import { Metadata } from 'next';
import { notFound } from 'next/navigation';
import { prisma } from '@/lib/prisma';
import FreelancerProfileView from '@/components/public/FreelancerProfileView';
import Footer from '@/components/Footer';
import './profile-view.css';

interface FreelancerProfilePageProps {
  params: Promise<{
    locale: string;
    freelancerId: string;
  }>;
}

export async function generateMetadata({ params }: FreelancerProfilePageProps): Promise<Metadata> {
  const { freelancerId } = await params;
  
  try {
    // Try to get freelancer name for metadata
    if (prisma) {
      const freelancer = await prisma.user.findUnique({
        where: { 
          id: freelancerId,
          role: 'FREELANCER'
        },
        include: {
          profile: {
            select: {
              firstName: true,
              lastName: true
            }
          }
        }
      });

      if (freelancer?.profile) {
        const name = `${freelancer.profile.firstName || ''} ${freelancer.profile.lastName || ''}`.trim();
        return {
          title: `${name} - Freelancer Profile | Smile24`,
          description: `View ${name}'s professional profile, skills, and portfolio on Smile24`,
        };
      }
    }
  } catch (error) {
    console.error('Error generating metadata:', error);
  }

  return {
    title: 'Freelancer Profile - Smile24',
    description: 'View freelancer profile, skills, and portfolio on Smile24',
  };
}

async function getFreelancerProfile(freelancerId: string) {
  try {
    if (!prisma) {
      // Mock data when database is not available
      return {
        id: freelancerId,
        name: 'Juan Mullins',
        email: 'juan.mullins@example.com',
        profileImage: '/assets/image/profile03.png',
        bio: 'Hi, I\'m John — a passionate UI/UX designer and frontend developer with over 5 years of experience turning complex ideas into clean, intuitive digital products. I specialize in designing user-centric interfaces and building responsive websites that not only look good but also perform seamlessly across devices.',
        title: 'Creative UI/UX Designer & Frontend Developer',
        rating: 4.5,
        reviewCount: 25,
        phone: '+33 6 12 34 56 78',
        location: 'Zurich, Switzerland',
        completedProjects: 25,
        memberSince: '12/06/2024',
        workExperiences: [
          {
            id: '1',
            title: 'Work Experience title here',
            location: 'Zurich, Switzerland',
            description: 'Our platform is designed with your needs in mind. Featuring a clear, motivating interface, we guide you through every step of creating and managing your profile. With easy-to-navigate. Our platform is designed with your needs in mind. Featuring a clear, motivating interface.',
            documents: [
              {
                id: '1',
                filename: 'Document.png',
                size: '256MB',
                type: 'image',
                url: '/assets/documents/document1.png'
              },
              {
                id: '2',
                filename: 'Document.png',
                size: '256MB',
                type: 'image',
                url: '/assets/documents/document2.png'
              }
            ]
          },
          {
            id: '2',
            title: 'Work Experience title here',
            location: 'Zurich, Switzerland',
            description: 'Our platform is designed with your needs in mind. Featuring a clear, motivating interface, we guide you through every step of creating and managing your profile. With easy-to-navigate. Our platform is designed with your needs in mind. Featuring a clear, motivating interface.',
            documents: [
              {
                id: '3',
                filename: 'Document.png',
                size: '256MB',
                type: 'image',
                url: '/assets/documents/document3.png'
              },
              {
                id: '4',
                filename: 'Document.png',
                size: '256MB',
                type: 'image',
                url: '/assets/documents/document4.png'
              }
            ]
          }
        ]
      };
    }

    const freelancer = await prisma.user.findUnique({
      where: { 
        id: freelancerId,
        role: 'FREELANCER'
      },
      include: {
        profile: {
          include: {
            country: {
              select: {
                name: true
              }
            },
            experience: {
              orderBy: {
                createdAt: 'desc'
              }
            }
          }
        },
        _count: {
          select: {
            receivedReviews: true
          }
        }
      }
    });

    if (!freelancer) {
      return null;
    }

    // Calculate average rating
    const reviews = await prisma.review.findMany({
      where: {
        recipientId: freelancerId
      },
      select: {
        rating: true
      }
    });

    const averageRating = reviews.length > 0 
      ? reviews.reduce((sum, review) => sum + review.rating, 0) / reviews.length
      : 4.5; // Default rating

    return {
      id: freelancer.id,
      name: freelancer.profile ? 
        `${freelancer.profile.firstName || ''} ${freelancer.profile.lastName || ''}`.trim() :
        freelancer.email,
      email: freelancer.email,
      profileImage: freelancer.profile?.profileImage || freelancer.image || '/assets/image/profile03.png',
      bio: freelancer.profile?.bio || 'Experienced freelancer ready to work on your projects',
      title: freelancer.profile?.title || 'Experienced Freelancer',
      rating: Math.round(averageRating * 10) / 10,
      reviewCount: freelancer._count.receivedReviews,
      phone: freelancer.profile?.phone || '',
      location: freelancer.profile?.city && freelancer.profile?.country?.name ? 
        `${freelancer.profile.city}, ${freelancer.profile.country.name}` : 
        'Remote',
      completedProjects: Math.floor(Math.random() * 50) + 10, // Mock data - would need proper project relationship
      memberSince: freelancer.createdAt.toLocaleDateString('en-US', { 
        month: '2-digit',
        day: '2-digit', 
        year: 'numeric' 
      }),
      workExperiences: freelancer.profile?.experience?.map(exp => ({
        id: exp.id,
        title: exp.title,
        location: exp.location || freelancer.profile?.city || 'Remote',
        description: exp.description || '',
        documents: [] // Document handling would need to be implemented
      })) || []
    };

  } catch (error) {
    console.error('Error fetching freelancer profile:', error);
    return null;
  }
}

export default async function FreelancerProfilePage({ params }: FreelancerProfilePageProps) {
  const { locale, freelancerId } = await params;

  const freelancerProfile = await getFreelancerProfile(freelancerId);

  if (!freelancerProfile) {
    notFound();
  }

  return (
    <>
      <FreelancerProfileView 
        freelancer={freelancerProfile}
        locale={locale}
      />
      <Footer locale={locale} />
    </>
  );
}