"use client"

import React from "react"
import DashboardPage from "@/base/components/layout/dashboard/dashboard-page"
import type { DashboardHeaderProps } from "@/base/components/layout/dashboard"
import { Card, CardContent } from "@/shared/components/ui/card"
import type { ResourcePageClient, ResourceItem } from "./use-resource-page"
import { CrudResource, type CrudResourceContext, type CrudResourceColumnHelpers, type CrudResourceProps } from "./crud-resource"

// Re-exported for backward compatibility
export type ResourcePageColumnHelpers<TClient extends ResourcePageClient> = CrudResourceColumnHelpers<TClient>
export type ResourcePageContext<TClient extends ResourcePageClient> = CrudResourceContext<TClient>

export type ResourceFormProps<TClient extends ResourcePageClient> = {
    resourceId: string | null
    initialData: ResourceItem<TClient> | null
    onSuccess: () => void
}

export type ResourcePageHeaderHelpers<TClient extends ResourcePageClient> = {
    selectedItem: ResourceItem<TClient> | null
    invalidateQuery: () => void
}

type ReactNodeOrRender<TClient extends ResourcePageClient> =
    | React.ReactNode
    | ((context: ResourcePageContext<TClient>) => React.ReactNode)

export type ResourcePageProps<TClient extends ResourcePageClient> = Omit<CrudResourceProps<TClient>, "render"> & {
    headerProps?: DashboardHeaderProps | ((helpers: ResourcePageHeaderHelpers<TClient>) => DashboardHeaderProps)
    header?: ReactNodeOrRender<TClient> | null
}

export function ResourcePage<TClient extends ResourcePageClient>({
    headerProps: headerPropsProp,
    header,
    ...crudResourceProps
}: ResourcePageProps<TClient>) {
    return (
        <CrudResource<TClient>
            {...crudResourceProps}
            render={(table, context) => {
                const resolvedHeaderProps = typeof headerPropsProp === "function"
                    ? headerPropsProp({
                        selectedItem: context.selectedItem,
                        invalidateQuery: context.invalidateQuery,
                    })
                    : headerPropsProp

                const resolvedHeader = typeof header === "function" ? header(context) : header

                return (
                    <DashboardPage
                        header={resolvedHeader}
                        headerProps={resolvedHeaderProps}
                        fullscreen
                    >
                        <Card className="rounded-none">
                            <CardContent className="space-y-4">
                                {table}
                            </CardContent>
                        </Card>
                    </DashboardPage>
                )
            }}
        />
    )
}
