"use client"

import { use } from "react"
import { useQuery } from "@tanstack/react-query"
import { useAuthApi } from "@/shared/useApi"
import { APPOINTMENT_ROUTES } from "@garage/api"
import { AppointmentGeneralInfo } from "@/modules/appointments/appointment-general-info"
import DashboardPage from "@/base/components/layout/dashboard/dashboard-page"
import { Skeleton } from "@/shared/components/ui/skeleton"

export default function AppointmentDetailsPage({ params }: { params: Promise<{ id: string }> }) {
    const { id } = use(params)
    const api = useAuthApi()

    const { data, isLoading } = useQuery({
        queryKey: [APPOINTMENT_ROUTES.INDEX, "detail", id],
        queryFn: async () => {
            const response = await api.appointments.list()
            const items = (response as any)?.data ?? []
            return items.find((item: any) => String(item.id) === id) ?? null
        },
    })

    if (isLoading) {
        return (
            <DashboardPage header={null}>
                <div className="grid gap-6 md:grid-cols-2 p-6">
                    {Array.from({ length: 4 }).map((_, i) => (
                        <Skeleton key={i} className="h-48 rounded-xl" />
                    ))}
                </div>
            </DashboardPage>
        )
    }

    if (!data) {
        return (
            <DashboardPage header={null}>
                <p className="text-muted-foreground p-6">Appointment not found.</p>
            </DashboardPage>
        )
    }

    return (
        <DashboardPage header={null}>
            <AppointmentGeneralInfo appointment={data} />
        </DashboardPage>
    )
}
