import { createClient } from "@/lib/supabase-server"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { UserForm } from "@/components/dashboard/user-form"
import { notFound } from "next/navigation"
import { getProfile } from "@/lib/data"

export default async function ProfilePage() {
    const supabase = createClient()
    const { data: { user } } = await supabase.auth.getUser()

    if (!user) {
        // Should be protected by middleware but just in case
        return <div>Lütfen giriş yapın.</div>
    }

    // Fetch profile data
    const profile = await getProfile(user.id)

    if (!profile) {
        // Fallback for user without profile row?
        // Or create one on the fly?
        return <div>Profil verisi bulunamadı.</div>
    }

    const parts = (profile.full_name || "").split(' ')
    const firstName = parts[0] || ""
    const lastName = parts.slice(1).join(' ') || ""

    const initialData = {
        firstName,
        lastName,
        phone: profile.phone || "",
        email: user.email || "",
        role: profile.role || "user"
    }

    return (
        <div className="flex-1 space-y-4 p-8 pt-6">
            <div className="flex items-center justify-between space-y-2">
                <h2 className="text-3xl font-bold tracking-tight">Profil</h2>
            </div>

            <div className="grid gap-4 md:grid-cols-2">
                <Card>
                    <CardHeader>
                        <CardTitle>Genel Bilgiler</CardTitle>
                        <CardDescription>
                            Kişisel profil bilgilerinizi buradan güncelleyebilirsiniz.
                        </CardDescription>
                    </CardHeader>
                    <CardContent className="space-y-6">
                        <div className="flex items-center space-x-4 mb-6">
                            <Avatar className="h-20 w-20">
                                <AvatarImage src="/avatars/01.png" alt="@parakasa" />
                                <AvatarFallback>PK</AvatarFallback>
                            </Avatar>
                        </div>

                        <UserForm initialData={initialData} mode="profile" />
                    </CardContent>
                </Card>
            </div>
        </div>
    )
}
