"use client"

import { use } from "react"
import { useQuery } from "@tanstack/react-query"
import { useAuthApi } from "@/shared/useApi"
import { useRouter } from "next/navigation"
import { BillForm } from "@/modules/bills/bill-form"
import DashboardPage from "@/base/components/layout/dashboard/dashboard-page"
import { BILL_ROUTES } from "@garage/api"

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

    const { data, isLoading } = useQuery({
        queryKey: [BILL_ROUTES.BY_ID, id],
        queryFn: () => api.bills.show(id),
    })

    if (isLoading) {
        return (
            <DashboardPage header={null}>
                <div className="flex items-center justify-center p-8 text-muted-foreground">
                    Loading...
                </div>
            </DashboardPage>
        )
    }

    return (
        <DashboardPage header={null}>
            <div className="p-6">
                <BillForm
                    resourceId={id}
                    initialData={data}
                    onSuccess={() => router.push(`/purchase/bill/${id}`)}
                />
            </div>
        </DashboardPage>
    )
}
