'use client'

import { useRef } from 'react'
import { trpc } from '@/lib/trpc/client'
import { Skeleton } from '@/components/ui/skeleton'
import { LunchEventConfig } from './lunch-event-config'
import { LunchDishes } from './lunch-dishes'
import { LunchManifest } from './lunch-manifest'
import { LunchExternals, type LunchExternalsHandle } from './lunch-externals'
import { LunchRecapActions } from './lunch-recap-actions'

export function LunchTab({ programId }: { programId: string }) {
  const { data: event, isLoading } = trpc.lunch.getEvent.useQuery({ programId })
  const externalsRef = useRef<LunchExternalsHandle>(null)
  if (isLoading || !event) {
    return <Skeleton className="h-48 w-full" />
  }
  return (
    <div className="space-y-6">
      <LunchEventConfig programId={programId} event={event} />
      {event.enabled && (
        <>
          <LunchDishes programId={programId} lunchEventId={event.id} />
          <LunchManifest
            programId={programId}
            onEditExternal={(id) => externalsRef.current?.openEditDialog(id)}
          />
          <LunchExternals
            ref={externalsRef}
            programId={programId}
            lunchEventId={event.id}
          />
          <LunchRecapActions
            programId={programId}
            lunchEventId={event.id}
            recapSentAt={event.recapSentAt}
            extraRecipientCount={event.extraRecipients.length}
          />
        </>
      )}
    </div>
  )
}
