import React from 'react'
import { notFound, redirect } from 'next/navigation'

import { getPageSession } from '@/auth/lucia'
import Expert from './expert'
import { fetchVideos } from '@/components/ExpertPage/getYoutube'

import { prisma } from '@/lib/prisma'
import { getFavoriteById } from '@/components/ExpertPage/actions'

const page = async ({ params }: { params: { id: string } }) => {
  const session = await getPageSession()

  const expertId = params && params.id
  console.log({ expertId })
  let videos: any = []

  const getExpertInfo = async () => {
    if (expertId) {
      const expert = await prisma.user.findUnique({
        where: {
          id: expertId, // Replace 'id' with the actual unique identifier field for your Expert model
        },
        include: {
          experiences: true, // Include experiences related to the expert
          educations: true, // Include educations related to the expert
          expertises: true,
          Expert: true,
          // expertises: true, // Include expertises related to the expert
          languagesSpoken: true, // Include languages spoken by the expert
        },
      })

      if (!expert) {
        console.log('no expert')
        redirect('/')
      }

      let finalExpert

      if (session?.user.userId) {
        const favoriteList = await getFavoriteById(session?.user.userId)
        const isFavorite = favoriteList?.includes(expert.Expert?.id as string)
        finalExpert = {
          ...expert,
          isFavorite,
        }
      } else {
        finalExpert = expert
      }

      return finalExpert
    }
  }

  const expertInfo = await getExpertInfo()

  // videos = await fetchVideos('https://www.youtube.com/UCFbNIlppjAuEX4znoulh0Cw')

  console.log('from expert page new')
  videos = expertInfo?.videos

  const reviews = await prisma.clientReview.findMany({
    where: {
      expertId: expertInfo?.id,
    },
    include: {
      client: true,
    },
  })

  console.log({ reviews })

  return (
    <>
      <Expert
        session={session}
        expertInfo={expertInfo}
        videos={videos || []}
        reviews={reviews}
      />
    </>
  )
}

export default page
