import { createClient } from "@/lib/supabase-server"
import { UserForm } from "@/components/dashboard/user-form"
import { notFound } from "next/navigation"

export default async function EditUserPage({ params }: { params: { userId: string } }) {
    const supabase = createClient()

    // Fetch profile
    const { data: profile } = await supabase
        .from('profiles')
        .select('*')
        .eq('id', params.userId)
        .single()

    if (!profile) {
        notFound()
    }

    // We also need the email, which is in auth.users, but we can't select from there easily with RLS/Client if not admin API
    // However, our logged in user IS admin, but RLS on auth.users is usually strict.
    // Let's see if we can get it via RPC or if the profile should store email (bad practice duplication, but helpful).
    // Actually, `supabaseAdmin` in a server action can get it, but here we are in a Page (Server Component).
    // We can use `supabaseAdmin` here too if we create a utility for it or just import createClient from supabase-js with admin key.

    // WORKAROUND: For now, let's assume we might need a server function to fetch full user details including email 
    // OR we just update the profile part. But the user wants to update email probably.
    // Let's write a small server action/function to fetch this data securely to render the form.

    // Better: Helper function to get user details
    const userDetails = await getUserDetails(params.userId)

    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">Kullanıcı Düzenle</h2>
            </div>
            <UserForm initialData={userDetails} />
        </div>
    )
}

// Helper to get admin-level data for the form
import { createClient as createSupabaseClient } from "@supabase/supabase-js"

async function getUserDetails(userId: string) {
    const supabaseAdmin = createSupabaseClient(
        process.env.NEXT_PUBLIC_SUPABASE_URL!,
        process.env.SUPABASE_SERVICE_ROLE_KEY!,
        { auth: { autoRefreshToken: false, persistSession: false } }
    )

    const { data: { user }, error } = await supabaseAdmin.auth.admin.getUserById(userId)
    const { data: profile } = await supabaseAdmin.from('profiles').select('*').eq('id', userId).single()

    if (error || !user || !profile) return undefined

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

    return {
        id: userId,
        firstName,
        lastName,
        email: user.email || "",
        role: profile.role as "admin" | "user",
        phone: profile.phone || ""
    }
}
