'use client'

import React from 'react'
import { useRouter } from 'next/navigation'
import { LogOut, User, Loader2 } from 'lucide-react'
import { supabase } from '../../lib/supabase'
import { Button } from '../../components/ui/button'
import { Link } from '../../components/ui/link'
import type { UserType } from '../../types/supabase'

export default function DashboardPage() {
  const router = useRouter()
  const [user, setUser] = React.useState<UserType | null>(null)
  const [isLoading, setIsLoading] = React.useState(true)
  const [isSigningOut, setIsSigningOut] = React.useState(false)

  React.useEffect(() => {
    const getUser = async () => {
      try {
        const { data: { user } } = await supabase.auth.getUser()
        setUser(user as UserType)
      } catch (error) {
        console.error('Error fetching user:', error)
        router.push('/auth/login')
      } finally {
        setIsLoading(false)
      }
    }
    getUser()
  }, [router])

  const handleSignOut = async () => {
    try {
      setIsSigningOut(true)
      await supabase.auth.signOut()
      router.push('/auth/login')
    } catch (error) {
      console.error('Error signing out:', error)
    }
  }

  if (isLoading) {
    return (
      <div className="flex min-h-screen items-center justify-center">
        <Loader2 className="h-8 w-8 animate-spin text-primary" />
      </div>
    )
  }

  return (
    <div className="flex min-h-screen flex-col items-center justify-center py-2">
      <div className="w-full max-w-md">
        <div className="rounded-lg border border-gray-200 p-8 shadow-md">
          <div className="flex items-center justify-center">
            <User className="h-16 w-16 text-primary" />
          </div>
          <h1 className="mt-4 text-center text-2xl font-bold">Dashboard</h1>
          <div className="mt-6">
            <p className="text-center text-gray-600">Welcome back,</p>
            <p className="mt-1 text-center font-medium">{user?.email}</p>
          </div>
          <div className="mt-8 space-y-4">
            <Button
              onClick={handleSignOut}
              variant="destructive"
              className="w-full"
              disabled={isSigningOut}
            >
              {isSigningOut ? (
                <>
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  Signing out...
                </>
              ) : (
                <>
                  <LogOut className="mr-2 h-4 w-4" />
                  Sign Out
                </>
              )}
            </Button>
            <Link href="/profile" className="block text-center">
              View Profile Settings
            </Link>
          </div>
        </div>
      </div>
    </div>
  )
} 