'use client'

import React, { useState, useEffect, useCallback } from 'react'
import { useRouter, useParams } from 'next/navigation'
import Link from 'next/link'
import { formatISO, format, parseISO } from 'date-fns'
import {
  ArrowLeft,
  Loader2,
  Search,
  Plus,
  Check,
  X,
  AlertTriangle,
  Send,
  Pencil,
  Eye,
  Users,
  ChefHat,
  ClipboardList,
  Upload,
  Trash2,
  ImageIcon,
  Sparkles,
  Camera,
} from 'lucide-react'

import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Badge } from '@/components/ui/badge'
import { Checkbox } from '@/components/ui/checkbox'
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
import { Separator } from '@/components/ui/separator'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import {
  Sheet,
  SheetContent,
  SheetDescription,
  SheetHeader,
  SheetTitle,
} from '@/components/ui/sheet'
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog'
import { cn } from '@/lib/utils'

interface Resident {
  id: number
  name: string
  room: string
  table?: string
  station?: string
  highCaloric?: boolean
  aversions?: string
  notes?: string
}

interface MediaFile {
  id: number
  url: string
  alt?: string
  filename?: string
  thumbnailURL?: string
}

interface Meal {
  id: number
  resident: Resident | number
  mealType: 'breakfast' | 'lunch' | 'dinner'
  status: 'pending' | 'preparing' | 'prepared'
  formImage?: MediaFile | number
  breakfast?: BreakfastOptions
  lunch?: LunchOptions
  dinner?: DinnerOptions
}

interface MealOrder {
  id: number
  title: string
  date: string
  mealType: 'breakfast' | 'lunch' | 'dinner'
  status: 'draft' | 'submitted' | 'preparing' | 'completed'
  mealCount: number
  notes?: string
}

interface BreakfastOptions {
  accordingToPlan: boolean
  bread: {
    breadRoll: boolean
    wholeGrainRoll: boolean
    greyBread: boolean
    wholeGrainBread: boolean
    whiteBread: boolean
    crispbread: boolean
  }
  porridge: boolean
  preparation: { sliced: boolean; spread: boolean }
  spreads: {
    butter: boolean
    margarine: boolean
    jam: boolean
    diabeticJam: boolean
    honey: boolean
    cheese: boolean
    quark: boolean
    sausage: boolean
  }
  beverages: { coffee: boolean; tea: boolean; hotMilk: boolean; coldMilk: boolean }
  additions: { sugar: boolean; sweetener: boolean; coffeeCreamer: boolean }
}

interface LunchOptions {
  portionSize: 'small' | 'large' | 'vegetarian'
  soup: boolean
  dessert: boolean
  specialPreparations: {
    pureedFood: boolean
    pureedMeat: boolean
    slicedMeat: boolean
    mashedPotatoes: boolean
  }
  restrictions: { noFish: boolean; fingerFood: boolean; onlySweet: boolean }
}

interface DinnerOptions {
  accordingToPlan: boolean
  bread: { greyBread: boolean; wholeGrainBread: boolean; whiteBread: boolean; crispbread: boolean }
  preparation: { spread: boolean; sliced: boolean }
  spreads: { butter: boolean; margarine: boolean }
  soup: boolean
  porridge: boolean
  noFish: boolean
  beverages: { tea: boolean; cocoa: boolean; hotMilk: boolean; coldMilk: boolean }
  additions: { sugar: boolean; sweetener: boolean }
}

const defaultBreakfast: BreakfastOptions = {
  accordingToPlan: false,
  bread: {
    breadRoll: false,
    wholeGrainRoll: false,
    greyBread: false,
    wholeGrainBread: false,
    whiteBread: false,
    crispbread: false,
  },
  porridge: false,
  preparation: { sliced: false, spread: false },
  spreads: {
    butter: false,
    margarine: false,
    jam: false,
    diabeticJam: false,
    honey: false,
    cheese: false,
    quark: false,
    sausage: false,
  },
  beverages: { coffee: false, tea: false, hotMilk: false, coldMilk: false },
  additions: { sugar: false, sweetener: false, coffeeCreamer: false },
}

const defaultLunch: LunchOptions = {
  portionSize: 'large',
  soup: false,
  dessert: true,
  specialPreparations: {
    pureedFood: false,
    pureedMeat: false,
    slicedMeat: false,
    mashedPotatoes: false,
  },
  restrictions: { noFish: false, fingerFood: false, onlySweet: false },
}

const defaultDinner: DinnerOptions = {
  accordingToPlan: false,
  bread: { greyBread: false, wholeGrainBread: false, whiteBread: false, crispbread: false },
  preparation: { spread: false, sliced: false },
  spreads: { butter: false, margarine: false },
  soup: false,
  porridge: false,
  noFish: false,
  beverages: { tea: false, cocoa: false, hotMilk: false, coldMilk: false },
  additions: { sugar: false, sweetener: false },
}

function CheckboxOption({
  id,
  label,
  checked,
  onCheckedChange,
}: {
  id: string
  label: string
  checked: boolean
  onCheckedChange: (checked: boolean) => void
}) {
  return (
    <div
      className={cn(
        'flex items-center space-x-3 rounded-lg border p-3 cursor-pointer transition-colors select-none',
        checked ? 'border-primary bg-primary/5' : 'border-border hover:bg-muted/50',
      )}
      onClick={() => onCheckedChange(!checked)}
      role="button"
      tabIndex={0}
      onKeyDown={(e) => {
        if (e.key === 'Enter' || e.key === ' ') {
          e.preventDefault()
          onCheckedChange(!checked)
        }
      }}
    >
      <Checkbox
        id={id}
        checked={checked}
        onCheckedChange={onCheckedChange}
        onClick={(e) => e.stopPropagation()}
      />
      <Label htmlFor={id} className="cursor-pointer flex-1 text-sm" onClick={(e) => e.stopPropagation()}>
        {label}
      </Label>
    </div>
  )
}

export default function OrderDetailPage() {
  const router = useRouter()
  const params = useParams()
  const orderId = params.id as string

  const [order, setOrder] = useState<MealOrder | null>(null)
  const [meals, setMeals] = useState<Meal[]>([])
  const [residents, setResidents] = useState<Resident[]>([])
  const [loading, setLoading] = useState(true)
  const [searchQuery, setSearchQuery] = useState('')
  const [showSummary, setShowSummary] = useState(false)
  const [submitting, setSubmitting] = useState(false)

  // Meal form state
  const [editingMeal, setEditingMeal] = useState<Meal | null>(null)
  const [selectedResident, setSelectedResident] = useState<Resident | null>(null)
  const [showMealForm, setShowMealForm] = useState(false)
  const [breakfast, setBreakfast] = useState<BreakfastOptions>(defaultBreakfast)
  const [lunch, setLunch] = useState<LunchOptions>(defaultLunch)
  const [dinner, setDinner] = useState<DinnerOptions>(defaultDinner)
  const [savingMeal, setSavingMeal] = useState(false)

  // Image upload state
  const [formImageFile, setFormImageFile] = useState<File | null>(null)
  const [formImagePreview, setFormImagePreview] = useState<string | null>(null)
  const [formImageId, setFormImageId] = useState<number | null>(null)
  const [existingFormImage, setExistingFormImage] = useState<MediaFile | null>(null)
  const [uploadingImage, setUploadingImage] = useState(false)
  const [analyzingImage, setAnalyzingImage] = useState(false)
  const [analysisError, setAnalysisError] = useState<string | null>(null)

  // Delete confirmation state
  const [mealToDelete, setMealToDelete] = useState<number | null>(null)
  const [showDeleteDialog, setShowDeleteDialog] = useState(false)
  const [deletingMeal, setDeletingMeal] = useState(false)

  const fetchData = useCallback(async () => {
    setLoading(true)
    try {
      // Fetch order details
      const orderRes = await fetch(`/api/meal-orders/${orderId}`, {
        credentials: 'include',
      })
      if (!orderRes.ok) {
        if (orderRes.status === 401) {
          router.push('/caregiver/login')
          return
        }
        throw new Error('Failed to fetch order')
      }
      const orderData = await orderRes.json()
      setOrder(orderData)

      // Fetch meals for this order
      const mealsRes = await fetch(
        `/api/meals?where[order][equals]=${orderId}&depth=1&limit=100`,
        { credentials: 'include' },
      )
      if (mealsRes.ok) {
        const mealsData = await mealsRes.json()
        setMeals(mealsData.docs || [])
      }

      // Fetch all active residents
      const residentsRes = await fetch(
        '/api/residents?where[active][equals]=true&limit=100&sort=name',
        { credentials: 'include' },
      )
      if (residentsRes.ok) {
        const residentsData = await residentsRes.json()
        setResidents(residentsData.docs || [])
      }
    } catch (err) {
      console.error('Error fetching data:', err)
    } finally {
      setLoading(false)
    }
  }, [orderId, router])

  useEffect(() => {
    fetchData()
  }, [fetchData])

  const getResidentMeal = (residentId: number): Meal | undefined => {
    return meals.find((meal) => {
      const mealResidentId =
        typeof meal.resident === 'object' ? meal.resident.id : meal.resident
      return mealResidentId === residentId
    })
  }

  const filteredResidents = residents.filter(
    (r) =>
      r.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      r.room.toLowerCase().includes(searchQuery.toLowerCase()),
  )

  const coveredResidents = residents.filter((r) => getResidentMeal(r.id))
  const uncoveredResidents = residents.filter((r) => !getResidentMeal(r.id))
  const coveragePercent = residents.length > 0 ? Math.round((coveredResidents.length / residents.length) * 100) : 0

  const getMealTypeLabel = (type: string) => {
    switch (type) {
      case 'breakfast':
        return 'Breakfast'
      case 'lunch':
        return 'Lunch'
      case 'dinner':
        return 'Dinner'
      default:
        return type
    }
  }

  const openMealForm = (resident: Resident, existingMeal?: Meal) => {
    setSelectedResident(resident)
    setEditingMeal(existingMeal || null)

    if (existingMeal) {
      // Load existing meal data
      if (existingMeal.breakfast) setBreakfast(existingMeal.breakfast)
      if (existingMeal.lunch) setLunch(existingMeal.lunch)
      if (existingMeal.dinner) setDinner(existingMeal.dinner)
      // Load existing form image
      if (existingMeal.formImage && typeof existingMeal.formImage === 'object') {
        setExistingFormImage(existingMeal.formImage)
        setFormImageId(existingMeal.formImage.id)
      } else if (typeof existingMeal.formImage === 'number') {
        setFormImageId(existingMeal.formImage)
      }
    } else {
      // Reset to defaults
      setBreakfast(defaultBreakfast)
      setLunch(defaultLunch)
      setDinner(defaultDinner)
    }

    setShowMealForm(true)
  }

  const closeMealForm = () => {
    setShowMealForm(false)
    setSelectedResident(null)
    setEditingMeal(null)
    // Reset image state
    setFormImageFile(null)
    setFormImagePreview(null)
    setFormImageId(null)
    setExistingFormImage(null)
    setAnalysisError(null)
  }

  const handleImageSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (!file) return

    setFormImageFile(file)
    setExistingFormImage(null)
    setAnalysisError(null)

    // Create preview
    const reader = new FileReader()
    reader.onload = (event) => {
      setFormImagePreview(event.target?.result as string)
    }
    reader.readAsDataURL(file)
  }

  const handleRemoveImage = () => {
    setFormImageFile(null)
    setFormImagePreview(null)
    setFormImageId(null)
    setExistingFormImage(null)
    setAnalysisError(null)
  }

  const handleUploadImage = async (): Promise<number | null> => {
    if (!formImageFile) return formImageId

    setUploadingImage(true)
    try {
      const formData = new FormData()
      formData.append('file', formImageFile)
      formData.append('alt', `Meal order form for ${selectedResident?.name}`)

      const res = await fetch('/api/media', {
        method: 'POST',
        body: formData,
        credentials: 'include',
      })

      if (res.ok) {
        const data = await res.json()
        setFormImageId(data.doc.id)
        return data.doc.id
      } else {
        console.error('Failed to upload image')
        return null
      }
    } catch (err) {
      console.error('Error uploading image:', err)
      return null
    } finally {
      setUploadingImage(false)
    }
  }

  const handleAnalyzeImage = async () => {
    if (!formImagePreview && !existingFormImage) return

    setAnalyzingImage(true)
    setAnalysisError(null)

    try {
      const imageData: { imageBase64?: string; imageUrl?: string } = {}

      if (formImagePreview) {
        // Extract base64 data from the data URL
        const base64Match = formImagePreview.match(/^data:image\/[^;]+;base64,(.+)$/)
        if (base64Match) {
          imageData.imageBase64 = base64Match[1]
        }
      } else if (existingFormImage?.url) {
        imageData.imageUrl = existingFormImage.url
      }

      const res = await fetch('/api/analyze-form', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          ...imageData,
          mealType: order?.mealType,
        }),
        credentials: 'include',
      })

      if (res.ok) {
        const analysis = await res.json()

        // Apply the analysis results to the form
        if (analysis.confidence > 50) {
          if (order?.mealType === 'breakfast' && analysis.breakfast) {
            setBreakfast((prev) => ({
              ...prev,
              ...analysis.breakfast,
              bread: { ...prev.bread, ...analysis.breakfast?.bread },
              preparation: { ...prev.preparation, ...analysis.breakfast?.preparation },
              spreads: { ...prev.spreads, ...analysis.breakfast?.spreads },
              beverages: { ...prev.beverages, ...analysis.breakfast?.beverages },
              additions: { ...prev.additions, ...analysis.breakfast?.additions },
            }))
          } else if (order?.mealType === 'lunch' && analysis.lunch) {
            setLunch((prev) => ({
              ...prev,
              ...analysis.lunch,
              specialPreparations: { ...prev.specialPreparations, ...analysis.lunch?.specialPreparations },
              restrictions: { ...prev.restrictions, ...analysis.lunch?.restrictions },
            }))
          } else if (order?.mealType === 'dinner' && analysis.dinner) {
            setDinner((prev) => ({
              ...prev,
              ...analysis.dinner,
              bread: { ...prev.bread, ...analysis.dinner?.bread },
              preparation: { ...prev.preparation, ...analysis.dinner?.preparation },
              spreads: { ...prev.spreads, ...analysis.dinner?.spreads },
              beverages: { ...prev.beverages, ...analysis.dinner?.beverages },
              additions: { ...prev.additions, ...analysis.dinner?.additions },
            }))
          }
        } else {
          setAnalysisError(`Low confidence (${analysis.confidence}%). Please check the options manually.`)
        }
      } else {
        const error = await res.json()
        setAnalysisError(error.error || 'Failed to analyze image')
      }
    } catch (err) {
      console.error('Error analyzing image:', err)
      setAnalysisError('Failed to analyze the form image')
    } finally {
      setAnalyzingImage(false)
    }
  }

  const handleSaveMeal = async () => {
    if (!selectedResident || !order) return

    setSavingMeal(true)
    try {
      // Upload image first if there's a new one
      let imageId = formImageId
      if (formImageFile) {
        imageId = await handleUploadImage()
      }

      const mealData: Record<string, unknown> = {
        order: order.id,
        resident: selectedResident.id,
        date: order.date,
        mealType: order.mealType,
        status: 'pending',
        formImage: imageId || undefined,
      }

      if (order.mealType === 'breakfast') {
        mealData.breakfast = breakfast
      } else if (order.mealType === 'lunch') {
        mealData.lunch = lunch
      } else if (order.mealType === 'dinner') {
        mealData.dinner = dinner
      }

      let res
      if (editingMeal) {
        // Update existing meal
        res = await fetch(`/api/meals/${editingMeal.id}`, {
          method: 'PATCH',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(mealData),
          credentials: 'include',
        })
      } else {
        // Create new meal
        res = await fetch('/api/meals', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(mealData),
          credentials: 'include',
        })
      }

      if (res.ok) {
        // Update order meal count
        await fetch(`/api/meal-orders/${order.id}`, {
          method: 'PATCH',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ mealCount: editingMeal ? meals.length : meals.length + 1 }),
          credentials: 'include',
        })

        closeMealForm()
        fetchData()
      } else {
        const data = await res.json()
        console.error('Error saving meal:', data)
      }
    } catch (err) {
      console.error('Error saving meal:', err)
    } finally {
      setSavingMeal(false)
    }
  }

  const handleDeleteMeal = async (mealId: number) => {
    setMealToDelete(mealId)
    setShowDeleteDialog(true)
  }

  const confirmDeleteMeal = async () => {
    if (!order || !mealToDelete) return

    setDeletingMeal(true)
    try {
      const res = await fetch(`/api/meals/${mealToDelete}`, {
        method: 'DELETE',
        credentials: 'include',
      })

      if (res.ok) {
        // Update order meal count
        await fetch(`/api/meal-orders/${order.id}`, {
          method: 'PATCH',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ mealCount: meals.length - 1 }),
          credentials: 'include',
        })

        fetchData()
      }
    } catch (err) {
      console.error('Error deleting meal:', err)
    } finally {
      setDeletingMeal(false)
      setShowDeleteDialog(false)
      setMealToDelete(null)
    }
  }

  const handleSubmitToKitchen = async () => {
    if (!order || meals.length === 0) return

    setSubmitting(true)
    try {
      const res = await fetch(`/api/meal-orders/${order.id}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          status: 'submitted',
          submittedAt: formatISO(new Date()),
        }),
        credentials: 'include',
      })

      if (res.ok) {
        setShowSummary(false)
        router.push('/caregiver/orders')
      }
    } catch (err) {
      console.error('Error submitting order:', err)
    } finally {
      setSubmitting(false)
    }
  }

  const getMealSummary = (meal: Meal) => {
    const items: string[] = []

    if (meal.breakfast) {
      if (meal.breakfast.accordingToPlan) items.push('According to Plan')
      const breads = Object.entries(meal.breakfast.bread)
        .filter(([, v]) => v)
        .map(([k]) => k)
      if (breads.length) items.push(`Bread: ${breads.length} types`)
      if (meal.breakfast.porridge) items.push('Porridge')
      const beverages = Object.entries(meal.breakfast.beverages)
        .filter(([, v]) => v)
        .map(([k]) => k)
      if (beverages.length) items.push(`Beverages: ${beverages.join(', ')}`)
    }

    if (meal.lunch) {
      items.push(`Portion: ${meal.lunch.portionSize}`)
      if (meal.lunch.soup) items.push('Soup')
      if (meal.lunch.dessert) items.push('Dessert')
      const preps = Object.entries(meal.lunch.specialPreparations)
        .filter(([, v]) => v)
        .map(([k]) => k)
      if (preps.length) items.push(`Special: ${preps.join(', ')}`)
    }

    if (meal.dinner) {
      if (meal.dinner.accordingToPlan) items.push('According to Plan')
      const breads = Object.entries(meal.dinner.bread)
        .filter(([, v]) => v)
        .map(([k]) => k)
      if (breads.length) items.push(`Bread: ${breads.length} types`)
      if (meal.dinner.soup) items.push('Soup')
      if (meal.dinner.porridge) items.push('Porridge')
    }

    return items.length > 0 ? items.slice(0, 3).join(', ') : 'Basic meal'
  }

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-muted/50">
        <Loader2 className="h-8 w-8 animate-spin text-primary" />
      </div>
    )
  }

  if (!order) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-muted/50">
        <Card className="w-full max-w-md">
          <CardContent className="pt-6 text-center">
            <AlertTriangle className="h-12 w-12 mx-auto mb-4 text-destructive" />
            <h2 className="text-lg font-semibold mb-2">Order Not Found</h2>
            <p className="text-muted-foreground mb-4">
              The order you&apos;re looking for doesn&apos;t exist.
            </p>
            <Button asChild>
              <Link href="/caregiver/orders">Back to Orders</Link>
            </Button>
          </CardContent>
        </Card>
      </div>
    )
  }

  const isDraft = order.status === 'draft'

  return (
    <div className="min-h-screen bg-muted/50">
      <header className="sticky top-0 z-50 w-full border-b bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60">
        <div className="container flex h-16 items-center justify-between">
          <div className="flex items-center gap-4">
            <Button variant="ghost" size="sm" asChild>
              <Link href="/caregiver/orders">
                <ArrowLeft className="mr-2 h-4 w-4" />
                Back
              </Link>
            </Button>
            <div>
              <h1 className="text-xl font-semibold">{order.title}</h1>
              <p className="text-sm text-muted-foreground">
                {format(parseISO(order.date), 'EEEE, MMM d, yyyy')}
              </p>
            </div>
          </div>
          <div className="flex items-center gap-2">
            <Badge
              variant="outline"
              className={cn(
                order.status === 'draft' && 'bg-gray-50 text-gray-700',
                order.status === 'submitted' && 'bg-blue-50 text-blue-700',
                order.status === 'preparing' && 'bg-yellow-50 text-yellow-700',
                order.status === 'completed' && 'bg-green-50 text-green-700',
              )}
            >
              {order.status.charAt(0).toUpperCase() + order.status.slice(1)}
            </Badge>
          </div>
        </div>
      </header>

      <main className="container py-6">
        {/* Coverage Stats */}
        <div className="grid gap-4 md:grid-cols-4 mb-6">
          <Card>
            <CardContent className="pt-6">
              <div className="flex items-center gap-4">
                <div className="p-3 rounded-full bg-blue-100">
                  <Users className="h-6 w-6 text-blue-600" />
                </div>
                <div>
                  <p className="text-sm text-muted-foreground">Total Residents</p>
                  <p className="text-2xl font-bold">{residents.length}</p>
                </div>
              </div>
            </CardContent>
          </Card>
          <Card>
            <CardContent className="pt-6">
              <div className="flex items-center gap-4">
                <div className="p-3 rounded-full bg-green-100">
                  <Check className="h-6 w-6 text-green-600" />
                </div>
                <div>
                  <p className="text-sm text-muted-foreground">Meals Created</p>
                  <p className="text-2xl font-bold">{coveredResidents.length}</p>
                </div>
              </div>
            </CardContent>
          </Card>
          <Card>
            <CardContent className="pt-6">
              <div className="flex items-center gap-4">
                <div className="p-3 rounded-full bg-orange-100">
                  <AlertTriangle className="h-6 w-6 text-orange-600" />
                </div>
                <div>
                  <p className="text-sm text-muted-foreground">Missing Meals</p>
                  <p className="text-2xl font-bold">{uncoveredResidents.length}</p>
                </div>
              </div>
            </CardContent>
          </Card>
          <Card>
            <CardContent className="pt-6">
              <div className="flex items-center gap-4">
                <div className="p-3 rounded-full bg-purple-100">
                  <ClipboardList className="h-6 w-6 text-purple-600" />
                </div>
                <div>
                  <p className="text-sm text-muted-foreground">Coverage</p>
                  <p className="text-2xl font-bold">{coveragePercent}%</p>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Progress Bar */}
        <Card className="mb-6">
          <CardContent className="pt-6">
            <div className="flex items-center justify-between mb-2">
              <span className="text-sm font-medium">Meal Coverage</span>
              <span className="text-sm text-muted-foreground">
                {coveredResidents.length} of {residents.length} residents
              </span>
            </div>
            <div className="h-3 bg-muted rounded-full overflow-hidden">
              <div
                className={cn(
                  'h-full rounded-full transition-all',
                  coveragePercent === 100 ? 'bg-green-500' : 'bg-blue-500',
                )}
                style={{ width: `${coveragePercent}%` }}
              />
            </div>
          </CardContent>
        </Card>

        {/* Residents Table */}
        <Card>
          <CardHeader>
            <div className="flex items-center justify-between">
              <div>
                <CardTitle>Residents</CardTitle>
                <CardDescription>
                  {isDraft
                    ? 'Add meals for each resident before submitting to kitchen'
                    : 'View meals for all residents'}
                </CardDescription>
              </div>
              {isDraft && meals.length > 0 && (
                <Button onClick={() => setShowSummary(true)}>
                  <Eye className="mr-2 h-4 w-4" />
                  Review & Submit
                </Button>
              )}
            </div>
          </CardHeader>
          <CardContent>
            <div className="relative mb-4">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
              <Input
                type="text"
                placeholder="Search residents..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="pl-10"
              />
            </div>

            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Resident</TableHead>
                  <TableHead>Room</TableHead>
                  <TableHead>Station</TableHead>
                  <TableHead>Info</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead className="text-right">Actions</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredResidents.map((resident) => {
                  const meal = getResidentMeal(resident.id)
                  return (
                    <TableRow key={resident.id}>
                      <TableCell className="font-medium">{resident.name}</TableCell>
                      <TableCell>{resident.room}</TableCell>
                      <TableCell>{resident.station || '-'}</TableCell>
                      <TableCell>
                        <div className="flex gap-1">
                          {resident.highCaloric && (
                            <Badge variant="secondary" className="bg-yellow-100 text-yellow-800">
                              High Cal
                            </Badge>
                          )}
                          {resident.aversions && (
                            <Badge variant="outline" className="text-orange-600">
                              Aversions
                            </Badge>
                          )}
                        </div>
                      </TableCell>
                      <TableCell>
                        {meal ? (
                          <Badge variant="outline" className="bg-green-50 text-green-700">
                            <Check className="mr-1 h-3 w-3" />
                            Meal Created
                          </Badge>
                        ) : (
                          <Badge variant="outline" className="bg-gray-50 text-gray-500">
                            <X className="mr-1 h-3 w-3" />
                            No Meal
                          </Badge>
                        )}
                      </TableCell>
                      <TableCell className="text-right">
                        {isDraft ? (
                          <div className="flex justify-end gap-2">
                            {meal ? (
                              <>
                                <Button
                                  variant="outline"
                                  size="sm"
                                  onClick={() => openMealForm(resident, meal)}
                                >
                                  <Pencil className="mr-1 h-3 w-3" />
                                  Edit
                                </Button>
                                <Button
                                  variant="outline"
                                  size="sm"
                                  className="text-destructive hover:text-destructive"
                                  onClick={() => handleDeleteMeal(meal.id)}
                                >
                                  <X className="h-3 w-3" />
                                </Button>
                              </>
                            ) : (
                              <Button
                                variant="outline"
                                size="sm"
                                onClick={() => openMealForm(resident)}
                              >
                                <Plus className="mr-1 h-3 w-3" />
                                Add Meal
                              </Button>
                            )}
                          </div>
                        ) : meal ? (
                          <Button
                            variant="outline"
                            size="sm"
                            onClick={() => openMealForm(resident, meal)}
                          >
                            <Eye className="mr-1 h-3 w-3" />
                            View
                          </Button>
                        ) : null}
                      </TableCell>
                    </TableRow>
                  )
                })}
              </TableBody>
            </Table>
          </CardContent>
        </Card>
      </main>

      {/* Meal Form Sheet */}
      <Sheet open={showMealForm} onOpenChange={setShowMealForm}>
        <SheetContent className="sm:max-w-xl flex flex-col h-full p-0">
          <SheetHeader className="px-6 pt-6 pb-4 border-b">
            <SheetTitle>
              {editingMeal ? 'Edit' : 'Add'} {getMealTypeLabel(order.mealType)} Meal
            </SheetTitle>
            <SheetDescription>
              {selectedResident?.name} - Room {selectedResident?.room}
            </SheetDescription>
          </SheetHeader>

          <div className="flex-1 overflow-y-auto px-6 py-4 space-y-6">
            {/* Image Upload Section */}
            {isDraft && (
              <div className="space-y-3">
                <div className="flex items-center justify-between">
                  <h3 className="font-semibold flex items-center gap-2">
                    <Camera className="h-4 w-4" />
                    Paper Form Image
                  </h3>
                  {(formImagePreview || existingFormImage) && (
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={handleAnalyzeImage}
                      disabled={analyzingImage}
                    >
                      {analyzingImage ? (
                        <>
                          <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                          Analyzing...
                        </>
                      ) : (
                        <>
                          <Sparkles className="mr-2 h-4 w-4" />
                          Auto-fill from Image
                        </>
                      )}
                    </Button>
                  )}
                </div>

                {formImagePreview || existingFormImage ? (
                  <div className="relative">
                    <div className="relative aspect-[4/3] w-full overflow-hidden rounded-lg border bg-muted">
                      {/* eslint-disable-next-line @next/next/no-img-element */}
                      <img
                        src={formImagePreview || existingFormImage?.url}
                        alt="Meal order form"
                        className="h-full w-full object-contain"
                      />
                    </div>
                    <Button
                      variant="destructive"
                      size="icon"
                      className="absolute top-2 right-2"
                      onClick={handleRemoveImage}
                    >
                      <Trash2 className="h-4 w-4" />
                    </Button>
                    <div className="mt-2 text-sm text-muted-foreground text-center">
                      {formImageFile?.name || existingFormImage?.filename || 'Uploaded image'}
                    </div>
                  </div>
                ) : (
                  <label className="flex flex-col items-center justify-center gap-2 p-6 border-2 border-dashed rounded-lg cursor-pointer hover:bg-muted/50 transition-colors">
                    <div className="p-3 rounded-full bg-muted">
                      <Upload className="h-6 w-6 text-muted-foreground" />
                    </div>
                    <div className="text-center">
                      <span className="text-sm font-medium">Upload paper form photo</span>
                      <p className="text-xs text-muted-foreground mt-1">
                        Take a photo of the paper meal order form to auto-fill options
                      </p>
                    </div>
                    <input
                      type="file"
                      accept="image/*"
                      capture="environment"
                      className="hidden"
                      onChange={handleImageSelect}
                    />
                  </label>
                )}

                {analysisError && (
                  <Alert variant="destructive">
                    <AlertTriangle className="h-4 w-4" />
                    <AlertDescription>{analysisError}</AlertDescription>
                  </Alert>
                )}

                {uploadingImage && (
                  <div className="flex items-center justify-center gap-2 text-sm text-muted-foreground">
                    <Loader2 className="h-4 w-4 animate-spin" />
                    Uploading image...
                  </div>
                )}
              </div>
            )}

            {/* Show existing image in view mode */}
            {!isDraft && existingFormImage && (
              <div className="space-y-3">
                <h3 className="font-semibold flex items-center gap-2">
                  <ImageIcon className="h-4 w-4" />
                  Paper Form Image
                </h3>
                <div className="relative aspect-[4/3] w-full overflow-hidden rounded-lg border bg-muted">
                  {/* eslint-disable-next-line @next/next/no-img-element */}
                  <img
                    src={existingFormImage.url}
                    alt="Meal order form"
                    className="h-full w-full object-contain"
                  />
                </div>
              </div>
            )}

            <Separator />

            {(selectedResident?.aversions || selectedResident?.notes || selectedResident?.highCaloric) && (
              <Alert>
                <AlertTriangle className="h-4 w-4" />
                <AlertTitle>Notes for {selectedResident?.name}</AlertTitle>
                <AlertDescription>
                  {selectedResident?.highCaloric && (
                    <div className="font-medium text-yellow-700">High caloric requirement</div>
                  )}
                  {selectedResident?.aversions && <div>Aversions: {selectedResident.aversions}</div>}
                  {selectedResident?.notes && <div>{selectedResident.notes}</div>}
                </AlertDescription>
              </Alert>
            )}

            {/* BREAKFAST OPTIONS */}
            {order.mealType === 'breakfast' && (
              <>
                <div className="space-y-3">
                  <h3 className="font-semibold">General</h3>
                  <CheckboxOption
                    id="accordingToPlan"
                    label="According to Plan (lt. Plan)"
                    checked={breakfast.accordingToPlan}
                    onCheckedChange={(v) => setBreakfast({ ...breakfast, accordingToPlan: v })}
                  />
                </div>

                <Separator />

                <div className="space-y-3">
                  <h3 className="font-semibold">Bread (Brot)</h3>
                  <div className="grid gap-2 grid-cols-2">
                    <CheckboxOption id="breadRoll" label="Bread Roll" checked={breakfast.bread.breadRoll} onCheckedChange={(v) => setBreakfast({ ...breakfast, bread: { ...breakfast.bread, breadRoll: v } })} />
                    <CheckboxOption id="wholeGrainRoll" label="Whole Grain Roll" checked={breakfast.bread.wholeGrainRoll} onCheckedChange={(v) => setBreakfast({ ...breakfast, bread: { ...breakfast.bread, wholeGrainRoll: v } })} />
                    <CheckboxOption id="greyBread" label="Grey Bread" checked={breakfast.bread.greyBread} onCheckedChange={(v) => setBreakfast({ ...breakfast, bread: { ...breakfast.bread, greyBread: v } })} />
                    <CheckboxOption id="wholeGrainBread" label="Whole Grain" checked={breakfast.bread.wholeGrainBread} onCheckedChange={(v) => setBreakfast({ ...breakfast, bread: { ...breakfast.bread, wholeGrainBread: v } })} />
                    <CheckboxOption id="whiteBread" label="White Bread" checked={breakfast.bread.whiteBread} onCheckedChange={(v) => setBreakfast({ ...breakfast, bread: { ...breakfast.bread, whiteBread: v } })} />
                    <CheckboxOption id="crispbread" label="Crispbread" checked={breakfast.bread.crispbread} onCheckedChange={(v) => setBreakfast({ ...breakfast, bread: { ...breakfast.bread, crispbread: v } })} />
                  </div>
                </div>

                <Separator />

                <div className="space-y-3">
                  <h3 className="font-semibold">Preparation</h3>
                  <div className="grid gap-2 grid-cols-3">
                    <CheckboxOption id="porridge" label="Porridge" checked={breakfast.porridge} onCheckedChange={(v) => setBreakfast({ ...breakfast, porridge: v })} />
                    <CheckboxOption id="sliced" label="Sliced" checked={breakfast.preparation.sliced} onCheckedChange={(v) => setBreakfast({ ...breakfast, preparation: { ...breakfast.preparation, sliced: v } })} />
                    <CheckboxOption id="spread" label="Spread" checked={breakfast.preparation.spread} onCheckedChange={(v) => setBreakfast({ ...breakfast, preparation: { ...breakfast.preparation, spread: v } })} />
                  </div>
                </div>

                <Separator />

                <div className="space-y-3">
                  <h3 className="font-semibold">Spreads</h3>
                  <div className="grid gap-2 grid-cols-2">
                    <CheckboxOption id="butter" label="Butter" checked={breakfast.spreads.butter} onCheckedChange={(v) => setBreakfast({ ...breakfast, spreads: { ...breakfast.spreads, butter: v } })} />
                    <CheckboxOption id="margarine" label="Margarine" checked={breakfast.spreads.margarine} onCheckedChange={(v) => setBreakfast({ ...breakfast, spreads: { ...breakfast.spreads, margarine: v } })} />
                    <CheckboxOption id="jam" label="Jam" checked={breakfast.spreads.jam} onCheckedChange={(v) => setBreakfast({ ...breakfast, spreads: { ...breakfast.spreads, jam: v } })} />
                    <CheckboxOption id="diabeticJam" label="Diabetic Jam" checked={breakfast.spreads.diabeticJam} onCheckedChange={(v) => setBreakfast({ ...breakfast, spreads: { ...breakfast.spreads, diabeticJam: v } })} />
                    <CheckboxOption id="honey" label="Honey" checked={breakfast.spreads.honey} onCheckedChange={(v) => setBreakfast({ ...breakfast, spreads: { ...breakfast.spreads, honey: v } })} />
                    <CheckboxOption id="cheese" label="Cheese" checked={breakfast.spreads.cheese} onCheckedChange={(v) => setBreakfast({ ...breakfast, spreads: { ...breakfast.spreads, cheese: v } })} />
                    <CheckboxOption id="quark" label="Quark" checked={breakfast.spreads.quark} onCheckedChange={(v) => setBreakfast({ ...breakfast, spreads: { ...breakfast.spreads, quark: v } })} />
                    <CheckboxOption id="sausage" label="Sausage" checked={breakfast.spreads.sausage} onCheckedChange={(v) => setBreakfast({ ...breakfast, spreads: { ...breakfast.spreads, sausage: v } })} />
                  </div>
                </div>

                <Separator />

                <div className="space-y-3">
                  <h3 className="font-semibold">Beverages</h3>
                  <div className="grid gap-2 grid-cols-2">
                    <CheckboxOption id="coffee" label="Coffee" checked={breakfast.beverages.coffee} onCheckedChange={(v) => setBreakfast({ ...breakfast, beverages: { ...breakfast.beverages, coffee: v } })} />
                    <CheckboxOption id="tea" label="Tea" checked={breakfast.beverages.tea} onCheckedChange={(v) => setBreakfast({ ...breakfast, beverages: { ...breakfast.beverages, tea: v } })} />
                    <CheckboxOption id="hotMilk" label="Hot Milk" checked={breakfast.beverages.hotMilk} onCheckedChange={(v) => setBreakfast({ ...breakfast, beverages: { ...breakfast.beverages, hotMilk: v } })} />
                    <CheckboxOption id="coldMilk" label="Cold Milk" checked={breakfast.beverages.coldMilk} onCheckedChange={(v) => setBreakfast({ ...breakfast, beverages: { ...breakfast.beverages, coldMilk: v } })} />
                  </div>
                </div>

                <Separator />

                <div className="space-y-3">
                  <h3 className="font-semibold">Additions</h3>
                  <div className="grid gap-2 grid-cols-3">
                    <CheckboxOption id="sugar" label="Sugar" checked={breakfast.additions.sugar} onCheckedChange={(v) => setBreakfast({ ...breakfast, additions: { ...breakfast.additions, sugar: v } })} />
                    <CheckboxOption id="sweetener" label="Sweetener" checked={breakfast.additions.sweetener} onCheckedChange={(v) => setBreakfast({ ...breakfast, additions: { ...breakfast.additions, sweetener: v } })} />
                    <CheckboxOption id="coffeeCreamer" label="Creamer" checked={breakfast.additions.coffeeCreamer} onCheckedChange={(v) => setBreakfast({ ...breakfast, additions: { ...breakfast.additions, coffeeCreamer: v } })} />
                  </div>
                </div>
              </>
            )}

            {/* LUNCH OPTIONS */}
            {order.mealType === 'lunch' && (
              <>
                <div className="space-y-3">
                  <h3 className="font-semibold">Portion Size</h3>
                  <RadioGroup
                    value={lunch.portionSize}
                    onValueChange={(v) => setLunch({ ...lunch, portionSize: v as 'small' | 'large' | 'vegetarian' })}
                    className="grid gap-2 grid-cols-3"
                  >
                    {[
                      { value: 'small', label: 'Small' },
                      { value: 'large', label: 'Large' },
                      { value: 'vegetarian', label: 'Vegetarian' },
                    ].map(({ value, label }) => (
                      <div
                        key={value}
                        className={cn(
                          'flex items-center space-x-3 rounded-lg border p-3 cursor-pointer transition-colors',
                          lunch.portionSize === value ? 'border-primary bg-primary/5' : 'border-border hover:bg-muted/50',
                        )}
                        onClick={() => setLunch({ ...lunch, portionSize: value as 'small' | 'large' | 'vegetarian' })}
                      >
                        <RadioGroupItem value={value} id={value} />
                        <Label htmlFor={value} className="cursor-pointer">{label}</Label>
                      </div>
                    ))}
                  </RadioGroup>
                </div>

                <Separator />

                <div className="space-y-3">
                  <h3 className="font-semibold">Meal Options</h3>
                  <div className="grid gap-2 grid-cols-2">
                    <CheckboxOption id="soup" label="Soup" checked={lunch.soup} onCheckedChange={(v) => setLunch({ ...lunch, soup: v })} />
                    <CheckboxOption id="dessert" label="Dessert" checked={lunch.dessert} onCheckedChange={(v) => setLunch({ ...lunch, dessert: v })} />
                  </div>
                </div>

                <Separator />

                <div className="space-y-3">
                  <h3 className="font-semibold">Special Preparations</h3>
                  <div className="grid gap-2 grid-cols-2">
                    <CheckboxOption id="pureedFood" label="Pureed Food" checked={lunch.specialPreparations.pureedFood} onCheckedChange={(v) => setLunch({ ...lunch, specialPreparations: { ...lunch.specialPreparations, pureedFood: v } })} />
                    <CheckboxOption id="pureedMeat" label="Pureed Meat" checked={lunch.specialPreparations.pureedMeat} onCheckedChange={(v) => setLunch({ ...lunch, specialPreparations: { ...lunch.specialPreparations, pureedMeat: v } })} />
                    <CheckboxOption id="slicedMeat" label="Sliced Meat" checked={lunch.specialPreparations.slicedMeat} onCheckedChange={(v) => setLunch({ ...lunch, specialPreparations: { ...lunch.specialPreparations, slicedMeat: v } })} />
                    <CheckboxOption id="mashedPotatoes" label="Mashed Potatoes" checked={lunch.specialPreparations.mashedPotatoes} onCheckedChange={(v) => setLunch({ ...lunch, specialPreparations: { ...lunch.specialPreparations, mashedPotatoes: v } })} />
                  </div>
                </div>

                <Separator />

                <div className="space-y-3">
                  <h3 className="font-semibold">Restrictions</h3>
                  <div className="grid gap-2 grid-cols-3">
                    <CheckboxOption id="noFish" label="No Fish" checked={lunch.restrictions.noFish} onCheckedChange={(v) => setLunch({ ...lunch, restrictions: { ...lunch.restrictions, noFish: v } })} />
                    <CheckboxOption id="fingerFood" label="Finger Food" checked={lunch.restrictions.fingerFood} onCheckedChange={(v) => setLunch({ ...lunch, restrictions: { ...lunch.restrictions, fingerFood: v } })} />
                    <CheckboxOption id="onlySweet" label="Only Sweet" checked={lunch.restrictions.onlySweet} onCheckedChange={(v) => setLunch({ ...lunch, restrictions: { ...lunch.restrictions, onlySweet: v } })} />
                  </div>
                </div>
              </>
            )}

            {/* DINNER OPTIONS */}
            {order.mealType === 'dinner' && (
              <>
                <div className="space-y-3">
                  <h3 className="font-semibold">General</h3>
                  <CheckboxOption
                    id="dinnerAccordingToPlan"
                    label="According to Plan (lt. Plan)"
                    checked={dinner.accordingToPlan}
                    onCheckedChange={(v) => setDinner({ ...dinner, accordingToPlan: v })}
                  />
                </div>

                <Separator />

                <div className="space-y-3">
                  <h3 className="font-semibold">Bread</h3>
                  <div className="grid gap-2 grid-cols-2">
                    <CheckboxOption id="dinnerGreyBread" label="Grey Bread" checked={dinner.bread.greyBread} onCheckedChange={(v) => setDinner({ ...dinner, bread: { ...dinner.bread, greyBread: v } })} />
                    <CheckboxOption id="dinnerWholeGrainBread" label="Whole Grain" checked={dinner.bread.wholeGrainBread} onCheckedChange={(v) => setDinner({ ...dinner, bread: { ...dinner.bread, wholeGrainBread: v } })} />
                    <CheckboxOption id="dinnerWhiteBread" label="White Bread" checked={dinner.bread.whiteBread} onCheckedChange={(v) => setDinner({ ...dinner, bread: { ...dinner.bread, whiteBread: v } })} />
                    <CheckboxOption id="dinnerCrispbread" label="Crispbread" checked={dinner.bread.crispbread} onCheckedChange={(v) => setDinner({ ...dinner, bread: { ...dinner.bread, crispbread: v } })} />
                  </div>
                </div>

                <Separator />

                <div className="space-y-3">
                  <h3 className="font-semibold">Preparation</h3>
                  <div className="grid gap-2 grid-cols-2">
                    <CheckboxOption id="dinnerSpread" label="Spread" checked={dinner.preparation.spread} onCheckedChange={(v) => setDinner({ ...dinner, preparation: { ...dinner.preparation, spread: v } })} />
                    <CheckboxOption id="dinnerSliced" label="Sliced" checked={dinner.preparation.sliced} onCheckedChange={(v) => setDinner({ ...dinner, preparation: { ...dinner.preparation, sliced: v } })} />
                  </div>
                </div>

                <Separator />

                <div className="space-y-3">
                  <h3 className="font-semibold">Spreads</h3>
                  <div className="grid gap-2 grid-cols-2">
                    <CheckboxOption id="dinnerButter" label="Butter" checked={dinner.spreads.butter} onCheckedChange={(v) => setDinner({ ...dinner, spreads: { ...dinner.spreads, butter: v } })} />
                    <CheckboxOption id="dinnerMargarine" label="Margarine" checked={dinner.spreads.margarine} onCheckedChange={(v) => setDinner({ ...dinner, spreads: { ...dinner.spreads, margarine: v } })} />
                  </div>
                </div>

                <Separator />

                <div className="space-y-3">
                  <h3 className="font-semibold">Additional Items</h3>
                  <div className="grid gap-2 grid-cols-3">
                    <CheckboxOption id="dinnerSoup" label="Soup" checked={dinner.soup} onCheckedChange={(v) => setDinner({ ...dinner, soup: v })} />
                    <CheckboxOption id="dinnerPorridge" label="Porridge" checked={dinner.porridge} onCheckedChange={(v) => setDinner({ ...dinner, porridge: v })} />
                    <CheckboxOption id="dinnerNoFish" label="No Fish" checked={dinner.noFish} onCheckedChange={(v) => setDinner({ ...dinner, noFish: v })} />
                  </div>
                </div>

                <Separator />

                <div className="space-y-3">
                  <h3 className="font-semibold">Beverages</h3>
                  <div className="grid gap-2 grid-cols-2">
                    <CheckboxOption id="dinnerTea" label="Tea" checked={dinner.beverages.tea} onCheckedChange={(v) => setDinner({ ...dinner, beverages: { ...dinner.beverages, tea: v } })} />
                    <CheckboxOption id="dinnerCocoa" label="Cocoa" checked={dinner.beverages.cocoa} onCheckedChange={(v) => setDinner({ ...dinner, beverages: { ...dinner.beverages, cocoa: v } })} />
                    <CheckboxOption id="dinnerHotMilk" label="Hot Milk" checked={dinner.beverages.hotMilk} onCheckedChange={(v) => setDinner({ ...dinner, beverages: { ...dinner.beverages, hotMilk: v } })} />
                    <CheckboxOption id="dinnerColdMilk" label="Cold Milk" checked={dinner.beverages.coldMilk} onCheckedChange={(v) => setDinner({ ...dinner, beverages: { ...dinner.beverages, coldMilk: v } })} />
                  </div>
                </div>

                <Separator />

                <div className="space-y-3">
                  <h3 className="font-semibold">Additions</h3>
                  <div className="grid gap-2 grid-cols-2">
                    <CheckboxOption id="dinnerSugar" label="Sugar" checked={dinner.additions.sugar} onCheckedChange={(v) => setDinner({ ...dinner, additions: { ...dinner.additions, sugar: v } })} />
                    <CheckboxOption id="dinnerSweetener" label="Sweetener" checked={dinner.additions.sweetener} onCheckedChange={(v) => setDinner({ ...dinner, additions: { ...dinner.additions, sweetener: v } })} />
                  </div>
                </div>
              </>
            )}

          </div>

          {isDraft && (
            <div className="flex gap-4 px-6 py-4 border-t bg-background">
              <Button variant="outline" onClick={closeMealForm} className="flex-1">
                Cancel
              </Button>
              <Button onClick={handleSaveMeal} disabled={savingMeal} className="flex-1">
                {savingMeal ? (
                  <>
                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                    Saving...
                  </>
                ) : (
                  <>
                    <Check className="mr-2 h-4 w-4" />
                    {editingMeal ? 'Update Meal' : 'Add Meal'}
                  </>
                )}
              </Button>
            </div>
          )}
        </SheetContent>
      </Sheet>

      {/* Summary Dialog */}
      <Dialog open={showSummary} onOpenChange={setShowSummary}>
        <DialogContent className="max-w-2xl max-h-[80vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <ChefHat className="h-5 w-5" />
              Review Meals Before Submission
            </DialogTitle>
            <DialogDescription>
              {order.title} - {meals.length} meals for {order.date}
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            {uncoveredResidents.length > 0 && (
              <Alert variant="destructive">
                <AlertTriangle className="h-4 w-4" />
                <AlertTitle>Missing Meals</AlertTitle>
                <AlertDescription>
                  {uncoveredResidents.length} residents don&apos;t have meals:{' '}
                  {uncoveredResidents.map((r) => r.name).join(', ')}
                </AlertDescription>
              </Alert>
            )}

            <div className="space-y-2">
              {meals.map((meal) => {
                const resident =
                  typeof meal.resident === 'object' ? meal.resident : null
                return (
                  <div
                    key={meal.id}
                    className="flex items-center justify-between p-3 bg-muted rounded-lg"
                  >
                    <div>
                      <div className="font-medium">{resident?.name || 'Unknown'}</div>
                      <div className="text-sm text-muted-foreground">
                        Room {resident?.room} - {getMealSummary(meal)}
                      </div>
                    </div>
                    <Badge variant="outline" className="bg-green-50 text-green-700">
                      <Check className="mr-1 h-3 w-3" />
                      Ready
                    </Badge>
                  </div>
                )
              })}
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowSummary(false)}>
              Continue Editing
            </Button>
            <Button
              onClick={handleSubmitToKitchen}
              disabled={submitting || meals.length === 0}
              className="bg-green-600 hover:bg-green-700"
            >
              {submitting ? (
                <>
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  Submitting...
                </>
              ) : (
                <>
                  <Send className="mr-2 h-4 w-4" />
                  Submit to Kitchen
                </>
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Delete Meal Confirmation Dialog */}
      <AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Remove Meal</AlertDialogTitle>
            <AlertDialogDescription>
              Are you sure you want to remove this meal? This action cannot be undone.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel disabled={deletingMeal}>Cancel</AlertDialogCancel>
            <AlertDialogAction
              onClick={confirmDeleteMeal}
              disabled={deletingMeal}
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
            >
              {deletingMeal ? (
                <>
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  Removing...
                </>
              ) : (
                'Remove'
              )}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  )
}
