import { auth } from '@/auth'
import { redirect } from 'next/navigation'
import { ProfileForm } from './profile-form'
import prisma from '@/lib/prisma'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Sparkles } from 'lucide-react'
import { ProfilePageHeader } from '@/components/profile-page-header'
import { AISettingsLinkCard } from './ai-settings-link-card'

export default async function ProfilePage() {
  const session = await auth()

  if (!session?.user?.id) {
    redirect('/login')
  }

  const user = await prisma.user.findUnique({
    where: { id: session.user.id },
    select: { name: true, email: true, role: true }
  })

  if (!user) {
    redirect('/login')
  }

  // Get user AI settings for language preference and recent notes setting
  let userAISettings = { preferredLanguage: 'auto', showRecentNotes: false }
  try {
    const result = await prisma.$queryRaw<Array<{ preferredLanguage: string | null; showRecentNotes: number | null }>>`
      SELECT preferredLanguage, showRecentNotes FROM UserAISettings WHERE userId = ${session.user.id}
    `
    if (result && result[0]) {
      // Handle NULL values - if showRecentNotes is NULL, default to false
      const showRecentNotesValue = result[0].showRecentNotes !== null && result[0].showRecentNotes !== undefined
        ? result[0].showRecentNotes === 1
        : false
      
      userAISettings = {
        preferredLanguage: result[0].preferredLanguage || 'auto',
        showRecentNotes: showRecentNotesValue
      }
    }
  } catch (error) {
    // Record doesn't exist, use defaults
  }

  return (
    <div className="container max-w-2xl mx-auto py-10 px-4">
      <ProfilePageHeader />
      <ProfileForm user={user} userAISettings={userAISettings} />

      {/* AI Settings Link */}
      <AISettingsLinkCard />
    </div>
  )
}
