import { HydrationBoundary, dehydrate } from '@tanstack/react-query';
import { auth } from '@/auth';
import PageContainer from '@/components/layout/page-container';
import { assetByIdQueryOptions, assetOptionsQueryOptions } from '@/features/assets/api/queries';
import { AssetActionForm } from '@/features/assets/components/asset-action-form';
import { getQueryClient } from '@/lib/query-client';
import type { SearchParams } from 'nuqs/server';

type PageProps = {
  searchParams: Promise<SearchParams>;
};

export default async function RepairAssetPage({ searchParams }: PageProps) {
  const params = await searchParams;
  const assetId = typeof params.assetId === 'string' ? params.assetId : '';
  const session = await auth();
  const canRepair =
    session?.user?.systemRole === 'super_admin' ||
    session?.user?.activePermissions.includes('asset:repair');

  if (!assetId) {
    return (
      <PageContainer pageTitle='Repair Asset'>
        <div className='text-muted-foreground rounded-lg border border-dashed p-8 text-center'>
          Select an asset to repair.
        </div>
      </PageContainer>
    );
  }

  const queryClient = getQueryClient();
  void queryClient.prefetchQuery(assetByIdQueryOptions(assetId));
  void queryClient.prefetchQuery(assetOptionsQueryOptions());

  return (
    <PageContainer pageTitle='Repair Asset' pageDescription='Record repair history for an asset.'>
      <HydrationBoundary state={dehydrate(queryClient)}>
        {canRepair ? (
          <AssetActionForm action='repair' assetId={assetId} />
        ) : (
          <div className='text-muted-foreground rounded-lg border border-dashed p-8 text-center'>
            You do not have access to repair assets.
          </div>
        )}
      </HydrationBoundary>
    </PageContainer>
  );
}
