"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 {
  Search,
  Plus,
  Check,
  X,
  AlertTriangle,
  Send,
  Pencil,
  Eye,
  Users,
  ChefHat,
  ClipboardList,
  Upload,
  Trash2,
  ImageIcon,
  Sparkles,
  Camera,
  Loader2,
} 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 { 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";

import {
  PageHeader,
  LoadingSpinner,
  StatusBadge,
  StatCard,
  CheckboxOption,
} from "@/components/caregiver";
import {
  getMealTypeLabel,
  type MealType,
  type OrderStatus,
} from "@/lib/constants/meal";
import {
  type BreakfastOptions,
  type LunchOptions,
  type DinnerOptions,
  DEFAULT_BREAKFAST,
  DEFAULT_LUNCH,
  DEFAULT_DINNER,
  BREAKFAST_CONFIG,
  LUNCH_CONFIG,
  DINNER_CONFIG,
  getGridColsClass,
} from "@/lib/constants/meal-options";

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: MealType;
  status: "pending" | "preparing" | "prepared";
  formImage?: MediaFile | number;
  breakfast?: BreakfastOptions;
  lunch?: LunchOptions;
  dinner?: DinnerOptions;
}

interface MealOrder {
  id: number;
  title: string;
  date: string;
  mealType: MealType;
  status: OrderStatus;
  mealCount: number;
  notes?: string;
}

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);

  const [editingMeal, setEditingMeal] = useState<Meal | null>(null);
  const [selectedResident, setSelectedResident] = useState<Resident | null>(
    null,
  );
  const [showMealForm, setShowMealForm] = useState(false);
  const [breakfast, setBreakfast] =
    useState<BreakfastOptions>(DEFAULT_BREAKFAST);
  const [lunch, setLunch] = useState<LunchOptions>(DEFAULT_LUNCH);
  const [dinner, setDinner] = useState<DinnerOptions>(DEFAULT_DINNER);
  const [savingMeal, setSavingMeal] = useState(false);

  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);

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

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

      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 || []);
      }

      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 openMealForm = (resident: Resident, existingMeal?: Meal) => {
    setSelectedResident(resident);
    setEditingMeal(existingMeal || null);

    if (existingMeal) {
      if (existingMeal.breakfast) setBreakfast(existingMeal.breakfast);
      if (existingMeal.lunch) setLunch(existingMeal.lunch);
      if (existingMeal.dinner) setDinner(existingMeal.dinner);
      if (
        existingMeal.formImage &&
        typeof existingMeal.formImage === "object"
      ) {
        setExistingFormImage(existingMeal.formImage);
        setFormImageId(existingMeal.formImage.id);
      } else if (typeof existingMeal.formImage === "number") {
        setFormImageId(existingMeal.formImage);
      }
    } else {
      setBreakfast(DEFAULT_BREAKFAST);
      setLunch(DEFAULT_LUNCH);
      setDinner(DEFAULT_DINNER);
    }

    setShowMealForm(true);
  };

  const closeMealForm = () => {
    setShowMealForm(false);
    setSelectedResident(null);
    setEditingMeal(null);
    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);

    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;
      }
      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) {
        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();

        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 {
      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) {
        res = await fetch(`/api/meals/${editingMeal.id}`, {
          method: "PATCH",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(mealData),
          credentials: "include",
        });
      } else {
        res = await fetch("/api/meals", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(mealData),
          credentials: "include",
        });
      }

      if (res.ok) {
        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();
      }
    } 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) {
        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 <LoadingSpinner fullPage />;
  }

  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">
      <PageHeader
        title={order.title}
        subtitle={format(parseISO(order.date), "EEEE, MMM d, yyyy")}
        backHref="/caregiver/orders"
        rightContent={<StatusBadge status={order.status} />}
      />

      <main className="container py-6">
        <div className="grid gap-4 md:grid-cols-4 mb-6">
          <StatCard
            title="Total Residents"
            value={residents.length}
            icon={Users}
            iconColor="text-blue-600"
          />
          <StatCard
            title="Meals Created"
            value={coveredResidents.length}
            icon={Check}
            iconColor="text-green-600"
          />
          <StatCard
            title="Missing Meals"
            value={uncoveredResidents.length}
            icon={AlertTriangle}
            iconColor="text-orange-600"
          />
          <StatCard
            title="Coverage"
            value={`${coveragePercent}%`}
            icon={ClipboardList}
            iconColor="text-purple-600"
          />
        </div>

        <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>

        <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>

      <Sheet open={showMealForm} onOpenChange={setShowMealForm}>
        <SheetContent
          className="w-full sm:max-w-xl flex flex-col h-full overflow-hidden p-0"
          side="right"
        >
          <SheetHeader className="flex-shrink-0 px-4 sm: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-4 sm:px-6 py-4 space-y-6 min-h-0">
            {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>
            )}

            {!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>
            )}

            {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>

                {Object.entries(BREAKFAST_CONFIG).map(([key, section]) => (
                  <React.Fragment key={key}>
                    <Separator />
                    <div className="space-y-3">
                      <h3 className="font-semibold">{section.title}</h3>
                      <div
                        className={cn(
                          "grid gap-2",
                          getGridColsClass(section.columns),
                        )}
                      >
                        {section.options.map(({ key: optKey, label }) => {
                          const isTopLevel = optKey === "porridge";
                          const checked = isTopLevel
                            ? breakfast.porridge
                            : key === "preparation" &&
                                (optKey === "sliced" || optKey === "spread")
                              ? breakfast.preparation[
                                  optKey as keyof typeof breakfast.preparation
                                ]
                              : (
                                  breakfast[
                                    key as keyof BreakfastOptions
                                  ] as Record<string, boolean>
                                )?.[optKey];
                          return (
                            <CheckboxOption
                              key={optKey}
                              id={`breakfast-${key}-${optKey}`}
                              label={label}
                              checked={checked || false}
                              onCheckedChange={(v) => {
                                if (isTopLevel) {
                                  setBreakfast({ ...breakfast, porridge: v });
                                } else if (
                                  key === "preparation" &&
                                  (optKey === "sliced" || optKey === "spread")
                                ) {
                                  setBreakfast({
                                    ...breakfast,
                                    preparation: {
                                      ...breakfast.preparation,
                                      [optKey]: v,
                                    },
                                  });
                                } else {
                                  setBreakfast({
                                    ...breakfast,
                                    [key]: {
                                      ...(breakfast[
                                        key as keyof BreakfastOptions
                                      ] as Record<string, boolean>),
                                      [optKey]: v,
                                    },
                                  });
                                }
                              }}
                            />
                          );
                        })}
                      </div>
                    </div>
                  </React.Fragment>
                ))}
              </>
            )}

            {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-1 sm:grid-cols-3"
                  >
                    {LUNCH_CONFIG.portionSizes.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 })
                        }
                      >
                        <RadioGroupItem value={value} id={`portion-${value}`} />
                        <Label
                          htmlFor={`portion-${value}`}
                          className="cursor-pointer"
                        >
                          {label}
                        </Label>
                      </div>
                    ))}
                  </RadioGroup>
                </div>

                <Separator />
                <div className="space-y-3">
                  <h3 className="font-semibold">
                    {LUNCH_CONFIG.mealOptions.title}
                  </h3>
                  <div
                    className={cn(
                      "grid gap-2",
                      getGridColsClass(LUNCH_CONFIG.mealOptions.columns),
                    )}
                  >
                    {LUNCH_CONFIG.mealOptions.options.map(({ key, label }) => (
                      <CheckboxOption
                        key={key}
                        id={`lunch-meal-${key}`}
                        label={label}
                        checked={
                          lunch[
                            key as keyof Pick<LunchOptions, "soup" | "dessert">
                          ]
                        }
                        onCheckedChange={(v) =>
                          setLunch({ ...lunch, [key]: v })
                        }
                      />
                    ))}
                  </div>
                </div>

                <Separator />
                <div className="space-y-3">
                  <h3 className="font-semibold">
                    {LUNCH_CONFIG.specialPreparations.title}
                  </h3>
                  <div
                    className={cn(
                      "grid gap-2",
                      getGridColsClass(
                        LUNCH_CONFIG.specialPreparations.columns,
                      ),
                    )}
                  >
                    {LUNCH_CONFIG.specialPreparations.options.map(
                      ({ key, label }) => (
                        <CheckboxOption
                          key={key}
                          id={`lunch-prep-${key}`}
                          label={label}
                          checked={
                            lunch.specialPreparations[
                              key as keyof typeof lunch.specialPreparations
                            ]
                          }
                          onCheckedChange={(v) =>
                            setLunch({
                              ...lunch,
                              specialPreparations: {
                                ...lunch.specialPreparations,
                                [key]: v,
                              },
                            })
                          }
                        />
                      ),
                    )}
                  </div>
                </div>

                <Separator />
                <div className="space-y-3">
                  <h3 className="font-semibold">
                    {LUNCH_CONFIG.restrictions.title}
                  </h3>
                  <div
                    className={cn(
                      "grid gap-2",
                      getGridColsClass(LUNCH_CONFIG.restrictions.columns),
                    )}
                  >
                    {LUNCH_CONFIG.restrictions.options.map(({ key, label }) => (
                      <CheckboxOption
                        key={key}
                        id={`lunch-rest-${key}`}
                        label={label}
                        checked={
                          lunch.restrictions[
                            key as keyof typeof lunch.restrictions
                          ]
                        }
                        onCheckedChange={(v) =>
                          setLunch({
                            ...lunch,
                            restrictions: { ...lunch.restrictions, [key]: v },
                          })
                        }
                      />
                    ))}
                  </div>
                </div>
              </>
            )}

            {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>

                {Object.entries(DINNER_CONFIG).map(([key, section]) => (
                  <React.Fragment key={key}>
                    <Separator />
                    <div className="space-y-3">
                      <h3 className="font-semibold">{section.title}</h3>
                      <div
                        className={cn(
                          "grid gap-2",
                          getGridColsClass(section.columns),
                        )}
                      >
                        {section.options.map(({ key: optKey, label }) => {
                          const isTopLevel = [
                            "soup",
                            "porridge",
                            "noFish",
                          ].includes(optKey);
                          const checked = isTopLevel
                            ? dinner[
                                optKey as keyof Pick<
                                  DinnerOptions,
                                  "soup" | "porridge" | "noFish"
                                >
                              ]
                            : (
                                dinner[key as keyof DinnerOptions] as Record<
                                  string,
                                  boolean
                                >
                              )?.[optKey];
                          return (
                            <CheckboxOption
                              key={optKey}
                              id={`dinner-${key}-${optKey}`}
                              label={label}
                              checked={checked || false}
                              onCheckedChange={(v) => {
                                if (isTopLevel) {
                                  setDinner({ ...dinner, [optKey]: v });
                                } else {
                                  setDinner({
                                    ...dinner,
                                    [key]: {
                                      ...(dinner[
                                        key as keyof DinnerOptions
                                      ] as Record<string, boolean>),
                                      [optKey]: v,
                                    },
                                  });
                                }
                              }}
                            />
                          );
                        })}
                      </div>
                    </div>
                  </React.Fragment>
                ))}
              </>
            )}
          </div>

          {isDraft && (
            <div className="flex-shrink-0 flex gap-3 px-4 sm:px-6 py-4 border-t bg-background safe-area-bottom">
              <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>

      <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>

      <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>
  );
}
