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 { 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>
    }

    // Improved name parsing logic
    const fullName = (profile.full_name || "").trim()
    const firstSpaceIndex = fullName.indexOf(' ')

    let firstName = fullName
    let lastName = ""

    if (firstSpaceIndex > 0) {
        firstName = fullName.substring(0, firstSpaceIndex)
        lastName = fullName.substring(firstSpaceIndex + 1)
    }

    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>
    )
}
