import { createClient } from '@/lib/supabase/server'
import NewProjectButton from '@/components/NewProjectButton'
import ProjectList from '@/components/ProjectList'

export default async function DashboardPage() {
  const supabase = await createClient()

  const {
    data: { user },
  } = await supabase.auth.getUser()

  if (!user) {
    return null
  }

  const { data: projects, error } = await supabase
    .from('projects')
    .select('id, name, updated_at')
    .eq('user_id', user.id)
    .order('updated_at', { ascending: false })

  if (error) {
    return (
      <div className="rounded-lg border border-red-200 bg-red-50 p-4 dark:border-red-800 dark:bg-red-900/20">
        <p className="text-red-700 dark:text-red-400">
          Failed to load projects. Please try again.
        </p>
      </div>
    )
  }

  return (
    <div>
      <div className="mb-8 flex items-start justify-between">
        <div>
          <h1 className="text-2xl font-bold text-zinc-900 dark:text-zinc-50">
            Your Projects
          </h1>
          <p className="mt-1 text-sm text-zinc-600 dark:text-zinc-400">
            Select a project to open the flowchart editor
          </p>
        </div>
        <NewProjectButton />
      </div>

      <ProjectList initialProjects={projects || []} />
    </div>
  )
}
