import { DashboardDetailsPage } from '@/base/components/layout/dashboard'
import { getServerApi } from '@garage/api/server'
import { EstimateActions } from '@/modules/estimates/estimate-actions'
import { EstimateProvider } from '@/modules/estimates/estimate-context'
import { CreateInvoiceFromEstimateButton } from '@/modules/estimates/create-invoice-from-estimate-button'
import { CreateJobCardFromEstimateButton } from '@/modules/estimates/create-job-card-from-estimate-button'
import { ShareDocumentButton } from '@/shared/components/share-document-button'
import { FileTextIcon } from 'lucide-react'
import React from 'react'
import { formatDate } from '@/shared/utils/formatters'

export default async function layout(props: {
    params: Promise<{ id: string }>
    children: React.ReactNode
}) {
    const { id } = await props.params
    const api = await getServerApi()
    const estimate = await api.estimates.show(id)

    const estimateData = estimate?.data
    const title = estimateData?.title || estimateData?.estimate_number || `Estimate #${id}`
    const estimateLabel = estimateData?.estimate_number
        ? `${estimateData.estimate_number}${estimateData.title ? ` — ${estimateData.title}` : ''}`
        : title

    if (!estimateData) {
        return <div className="text-muted-foreground p-4">Estimate not found.</div>
    }

    return (
        <EstimateProvider estimate={estimateData}>
            <DashboardDetailsPage
                className="p-0 lg:p-0"
                icon={<FileTextIcon className="size-5" />}
                title={title}
                description={
                    estimateData?.date ? `Date: ${formatDate(estimateData.date)}` : undefined
                }
                backHref="/sales/estimates"
                actions={
                    <div className="flex items-center gap-2">
                        <CreateInvoiceFromEstimateButton />
                        <CreateJobCardFromEstimateButton />
                        <ShareDocumentButton type="estimate" id={id} />
                        <EstimateActions estimateId={id} />
                    </div>
                }
                tabs={[
                    { href: `/sales/estimates/${id}`, label: 'Details' },
                ]}
            >
                {props.children}
            </DashboardDetailsPage>
        </EstimateProvider>
    )
}
