"use client";

import React, { useState, useEffect, useCallback } from "react";
import { format } from "date-fns";
import {
  LogOut,
  ChefHat,
  Users,
  Clock,
  CheckCircle2,
  Loader2,
  RefreshCw,
  ChevronDown,
  ChevronUp,
  AlertTriangle,
} 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 { Progress } from "@/components/ui/progress";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger,
} from "@/components/ui/collapsible";
import { cn } from "@/lib/utils";

import { useAuth } from "@/hooks/useAuth";
import {
  LoadingSpinner,
  MealTypeSelector,
  StatCard,
} from "@/components/caregiver";
import { MEAL_TYPES, type MealType } from "@/lib/constants/meal";

interface Resident {
  id: number;
  name: string;
  room: string;
  table?: string;
  station?: string;
}

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

interface Meal {
  id: number;
  title: string;
  resident: Resident | number;
  mealType: MealType;
  status: "pending" | "preparing" | "prepared";
  order?: MealOrder | number;
  highCaloric?: boolean;
  notes?: string;
}

interface KitchenReport {
  date: string;
  mealType: string;
  totalMeals: number;
  ingredients: Record<string, number>;
  labels: Record<string, string>;
  portionSizes?: Record<string, number>;
}

interface IngredientCategory {
  name: string;
  items: { key: string; label: string; count: number }[];
}

const MEAL_STATUS_CONFIG = {
  pending: {
    label: "Pending",
    bgColor: "bg-gray-100",
    textColor: "text-gray-700",
    icon: Clock,
  },
  preparing: {
    label: "Preparing",
    bgColor: "bg-yellow-100",
    textColor: "text-yellow-700",
    icon: ChefHat,
  },
  prepared: {
    label: "Prepared",
    bgColor: "bg-green-100",
    textColor: "text-green-700",
    icon: CheckCircle2,
  },
};

function categorizeIngredients(
  ingredients: Record<string, number>,
  labels: Record<string, string>,
): IngredientCategory[] {
  const categories: Record<string, IngredientCategory> = {
    bread: { name: "Bread", items: [] },
    preparation: { name: "Preparation", items: [] },
    spreads: { name: "Spreads", items: [] },
    beverages: { name: "Beverages", items: [] },
    additions: { name: "Additions", items: [] },
    mealOptions: { name: "Meal Options", items: [] },
    specialPreparations: { name: "Special Preparations", items: [] },
    restrictions: { name: "Restrictions", items: [] },
    other: { name: "Other", items: [] },
  };

  for (const [key, count] of Object.entries(ingredients)) {
    const label = labels[key] || key;
    const item = { key, label, count };

    if (
      key.includes("Bread") ||
      key.includes("Roll") ||
      key.includes("bread") ||
      key === "crispbread"
    ) {
      categories.bread.items.push(item);
    } else if (key === "sliced" || key === "spread" || key === "porridge") {
      categories.preparation.items.push(item);
    } else if (
      [
        "butter",
        "margarine",
        "jam",
        "diabeticJam",
        "honey",
        "cheese",
        "quark",
        "sausage",
      ].includes(key)
    ) {
      categories.spreads.items.push(item);
    } else if (
      ["coffee", "tea", "hotMilk", "coldMilk", "cocoa"].includes(key)
    ) {
      categories.beverages.items.push(item);
    } else if (["sugar", "sweetener", "coffeeCreamer"].includes(key)) {
      categories.additions.items.push(item);
    } else if (["soup", "dessert"].includes(key)) {
      categories.mealOptions.items.push(item);
    } else if (
      ["pureedFood", "pureedMeat", "slicedMeat", "mashedPotatoes"].includes(key)
    ) {
      categories.specialPreparations.items.push(item);
    } else if (["noFish", "fingerFood", "onlySweet"].includes(key)) {
      categories.restrictions.items.push(item);
    } else {
      categories.other.items.push(item);
    }
  }

  return Object.values(categories).filter((cat) => cat.items.length > 0);
}

export default function KitchenDashboardPage() {
  const {
    user,
    loading: authLoading,
    tenantName,
    logout,
  } = useAuth({ requiredRole: "kitchen" });

  const [date, setDate] = useState(() => format(new Date(), "yyyy-MM-dd"));
  const [mealType, setMealType] = useState<MealType>("breakfast");
  const [report, setReport] = useState<KitchenReport | null>(null);
  const [meals, setMeals] = useState<Meal[]>([]);
  const [orders, setOrders] = useState<MealOrder[]>([]);
  const [loading, setLoading] = useState(false);
  const [updatingMealId, setUpdatingMealId] = useState<number | null>(null);
  const [expandedCategories, setExpandedCategories] = useState<Set<string>>(
    new Set(["bread", "mealOptions"]),
  );

  const fetchData = useCallback(async () => {
    setLoading(true);
    try {
      const [reportRes, mealsRes, ordersRes] = await Promise.all([
        fetch(`/api/meals/kitchen-report?date=${date}&mealType=${mealType}`, {
          credentials: "include",
        }),
        fetch(
          `/api/meals?where[date][equals]=${date}&where[mealType][equals]=${mealType}&depth=2&limit=200&sort=resident`,
          { credentials: "include" },
        ),
        fetch(
          `/api/meal-orders?where[date][equals]=${date}&where[mealType][equals]=${mealType}&depth=0`,
          { credentials: "include" },
        ),
      ]);

      if (reportRes.ok) {
        const reportData = await reportRes.json();
        setReport(reportData);
      }

      if (mealsRes.ok) {
        const mealsData = await mealsRes.json();
        setMeals(mealsData.docs || []);
      }

      if (ordersRes.ok) {
        const ordersData = await ordersRes.json();
        setOrders(ordersData.docs || []);
      }
    } catch (err) {
      console.error("Error fetching data:", err);
    } finally {
      setLoading(false);
    }
  }, [date, mealType]);

  useEffect(() => {
    if (!authLoading && user) {
      fetchData();
    }
  }, [authLoading, user, fetchData]);

  const handleStatusChange = async (
    mealId: number,
    newStatus: Meal["status"],
  ) => {
    setUpdatingMealId(mealId);
    try {
      const res = await fetch(`/api/meals/${mealId}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ status: newStatus }),
        credentials: "include",
      });

      if (res.ok) {
        setMeals((prev) =>
          prev.map((meal) =>
            meal.id === mealId ? { ...meal, status: newStatus } : meal,
          ),
        );
      }
    } catch (err) {
      console.error("Error updating meal status:", err);
    } finally {
      setUpdatingMealId(null);
    }
  };

  const handleBulkStatusChange = async (newStatus: Meal["status"]) => {
    const mealsToUpdate = meals.filter((m) => m.status !== newStatus);
    if (mealsToUpdate.length === 0) return;

    setLoading(true);
    try {
      await Promise.all(
        mealsToUpdate.map((meal) =>
          fetch(`/api/meals/${meal.id}`, {
            method: "PATCH",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ status: newStatus }),
            credentials: "include",
          }),
        ),
      );
      fetchData();
    } catch (err) {
      console.error("Error bulk updating meals:", err);
    } finally {
      setLoading(false);
    }
  };

  const toggleCategory = (categoryName: string) => {
    setExpandedCategories((prev) => {
      const newSet = new Set(prev);
      if (newSet.has(categoryName)) {
        newSet.delete(categoryName);
      } else {
        newSet.add(categoryName);
      }
      return newSet;
    });
  };

  if (authLoading) {
    return <LoadingSpinner fullPage />;
  }

  const mealStats = {
    total: meals.length,
    pending: meals.filter((m) => m.status === "pending").length,
    preparing: meals.filter((m) => m.status === "preparing").length,
    prepared: meals.filter((m) => m.status === "prepared").length,
  };

  const progressPercent =
    mealStats.total > 0 ? (mealStats.prepared / mealStats.total) * 100 : 0;

  const ingredientCategories = report
    ? categorizeIngredients(report.ingredients, report.labels)
    : [];

  const submittedOrders = orders.filter((o) => o.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-14 sm:h-16 items-center justify-between gap-2">
          <div className="flex items-center gap-2 sm:gap-3 min-w-0">
            <ChefHat className="h-5 w-5 sm:h-6 sm:w-6 text-primary flex-shrink-0" />
            <div className="min-w-0">
              <h1 className="text-base sm:text-xl font-semibold truncate">Kitchen Dashboard</h1>
              <p className="text-xs text-muted-foreground truncate">{tenantName}</p>
            </div>
          </div>
          <div className="flex items-center gap-2 sm:gap-4 flex-shrink-0">
            <span className="hidden sm:inline text-sm text-muted-foreground">
              {user?.name || user?.email}
            </span>
            <Button variant="outline" size="sm" onClick={logout}>
              <LogOut className="h-4 w-4 sm:mr-2" />
              <span className="hidden sm:inline">Logout</span>
            </Button>
          </div>
        </div>
      </header>

      <main className="container py-4 sm:py-6">
        <Card className="mb-4 sm:mb-6">
          <CardHeader className="pb-3 sm:pb-6">
            <CardTitle className="text-lg sm:text-xl">Select Date & Meal</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid gap-4 sm:grid-cols-2">
              <div className="space-y-2">
                <Label htmlFor="date">Date</Label>
                <Input
                  type="date"
                  id="date"
                  value={date}
                  onChange={(e) => setDate(e.target.value)}
                />
              </div>
              <div className="space-y-2">
                <Label>Meal Type</Label>
                <MealTypeSelector
                  value={mealType}
                  onChange={setMealType}
                  variant="button"
                />
              </div>
            </div>
            <Button
              variant="outline"
              className="mt-4"
              onClick={fetchData}
              disabled={loading}
            >
              <RefreshCw
                className={cn("mr-2 h-4 w-4", loading && "animate-spin")}
              />
              Refresh Data
            </Button>
          </CardContent>
        </Card>

        {submittedOrders.length === 0 && !loading ? (
          <Card>
            <CardContent className="py-12 text-center">
              <AlertTriangle className="h-12 w-12 mx-auto mb-4 text-muted-foreground" />
              <h3 className="text-lg font-semibold mb-2">
                No Orders Submitted
              </h3>
              <p className="text-muted-foreground">
                No meal orders have been submitted for{" "}
                {MEAL_TYPES.find((m) => m.value === mealType)?.label} on{" "}
                {format(new Date(date), "MMMM d, yyyy")}.
              </p>
            </CardContent>
          </Card>
        ) : (
          <>
            <div className="grid grid-cols-2 gap-3 sm:gap-4 md:grid-cols-4 mb-4 sm:mb-6">
              <StatCard
                title="Total Meals"
                value={mealStats.total}
                icon={Users}
                iconColor="text-blue-600"
              />
              <StatCard
                title="Pending"
                value={mealStats.pending}
                dotColor="bg-gray-400"
              />
              <StatCard
                title="Preparing"
                value={mealStats.preparing}
                dotColor="bg-yellow-500"
              />
              <StatCard
                title="Prepared"
                value={mealStats.prepared}
                dotColor="bg-green-500"
              />
            </div>

            <Card className="mb-4 sm:mb-6">
              <CardContent className="pt-4 sm:pt-6">
                <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-1 sm:gap-0 mb-2">
                  <span className="text-sm font-medium">
                    Preparation Progress
                  </span>
                  <span className="text-xs sm:text-sm text-muted-foreground">
                    {mealStats.prepared} of {mealStats.total} complete
                  </span>
                </div>
                <Progress value={progressPercent} className="h-2 sm:h-3" />
              </CardContent>
            </Card>

            <div className="grid gap-4 sm:gap-6 lg:grid-cols-2 mb-4 sm:mb-6">
              <Card>
                <CardHeader>
                  <CardTitle>Ingredient Summary</CardTitle>
                  <CardDescription>
                    Total quantities needed for {mealStats.total} meals
                  </CardDescription>
                </CardHeader>
                <CardContent className="space-y-2">
                  {loading ? (
                    <LoadingSpinner />
                  ) : ingredientCategories.length === 0 ? (
                    <p className="text-muted-foreground text-center py-4">
                      No ingredients to display
                    </p>
                  ) : (
                    <>
                      {report?.portionSizes && (
                        <div className="mb-4 p-4 bg-muted rounded-lg">
                          <h4 className="font-medium mb-2">Portion Sizes</h4>
                          <div className="flex gap-4">
                            {Object.entries(report.portionSizes).map(
                              ([size, count]) => (
                                <div
                                  key={size}
                                  className="flex items-center gap-2"
                                >
                                  <Badge
                                    variant="outline"
                                    className="capitalize"
                                  >
                                    {size}
                                  </Badge>
                                  <span className="font-semibold">{count}</span>
                                </div>
                              ),
                            )}
                          </div>
                        </div>
                      )}

                      {ingredientCategories.map((category) => (
                        <Collapsible
                          key={category.name}
                          open={expandedCategories.has(
                            category.name.toLowerCase(),
                          )}
                          onOpenChange={() =>
                            toggleCategory(category.name.toLowerCase())
                          }
                        >
                          <CollapsibleTrigger asChild>
                            <Button
                              variant="ghost"
                              className="w-full justify-between p-3 h-auto"
                            >
                              <span className="font-medium">
                                {category.name}
                              </span>
                              <div className="flex items-center gap-2">
                                <Badge variant="secondary">
                                  {category.items.reduce(
                                    (sum, item) => sum + item.count,
                                    0,
                                  )}
                                </Badge>
                                {expandedCategories.has(
                                  category.name.toLowerCase(),
                                ) ? (
                                  <ChevronUp className="h-4 w-4" />
                                ) : (
                                  <ChevronDown className="h-4 w-4" />
                                )}
                              </div>
                            </Button>
                          </CollapsibleTrigger>
                          <CollapsibleContent>
                            <div className="grid gap-2 pl-3 pr-3 pb-3">
                              {category.items.map((item) => (
                                <div
                                  key={item.key}
                                  className="flex items-center justify-between p-2 bg-muted rounded"
                                >
                                  <span className="text-sm">{item.label}</span>
                                  <Badge>{item.count}</Badge>
                                </div>
                              ))}
                            </div>
                          </CollapsibleContent>
                        </Collapsible>
                      ))}
                    </>
                  )}
                </CardContent>
              </Card>

              <Card>
                <CardHeader className="pb-3 sm:pb-6">
                  <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
                    <div>
                      <CardTitle className="text-lg sm:text-xl">Meal Status</CardTitle>
                      <CardDescription className="text-xs sm:text-sm">
                        Update status as meals are prepared
                      </CardDescription>
                    </div>
                    <div className="flex gap-2">
                      <Button
                        size="sm"
                        variant="outline"
                        onClick={() => handleBulkStatusChange("preparing")}
                        disabled={loading || mealStats.pending === 0}
                        className="flex-1 sm:flex-none text-xs sm:text-sm"
                      >
                        Start All
                      </Button>
                      <Button
                        size="sm"
                        variant="outline"
                        className="flex-1 sm:flex-none bg-green-50 hover:bg-green-100 text-green-700 text-xs sm:text-sm"
                        onClick={() => handleBulkStatusChange("prepared")}
                        disabled={
                          loading || mealStats.prepared === mealStats.total
                        }
                      >
                        Complete All
                      </Button>
                    </div>
                  </div>
                </CardHeader>
                <CardContent className="px-3 sm:px-6">
                  {loading ? (
                    <LoadingSpinner />
                  ) : meals.length === 0 ? (
                    <p className="text-muted-foreground text-center py-4">
                      No meals found
                    </p>
                  ) : (
                    <div className="max-h-80 sm:max-h-96 overflow-y-auto -mx-3 sm:mx-0">
                      <Table>
                        <TableHeader>
                          <TableRow>
                            <TableHead className="text-xs sm:text-sm">Resident</TableHead>
                            <TableHead className="text-xs sm:text-sm hidden sm:table-cell">Room</TableHead>
                            <TableHead className="text-xs sm:text-sm">Status</TableHead>
                            <TableHead className="text-right text-xs sm:text-sm">
                              Actions
                            </TableHead>
                          </TableRow>
                        </TableHeader>
                        <TableBody>
                          {meals.map((meal) => {
                            const resident =
                              typeof meal.resident === "object"
                                ? meal.resident
                                : null;
                            const statusConfig =
                              MEAL_STATUS_CONFIG[meal.status];
                            const StatusIcon = statusConfig.icon;

                            return (
                              <TableRow key={meal.id}>
                                <TableCell className="font-medium text-xs sm:text-sm py-2 sm:py-4">
                                  <div className="flex flex-col sm:flex-row sm:items-center gap-1">
                                    <span className="truncate max-w-[120px] sm:max-w-none">{resident?.name || "Unknown"}</span>
                                    <span className="text-muted-foreground sm:hidden text-[10px]">Room {resident?.room || "-"}</span>
                                    {meal.highCaloric && (
                                      <Badge
                                        variant="secondary"
                                        className="w-fit bg-yellow-100 text-yellow-800 text-[10px] sm:text-xs sm:ml-2"
                                      >
                                        HC
                                      </Badge>
                                    )}
                                  </div>
                                </TableCell>
                                <TableCell className="hidden sm:table-cell">{resident?.room || "-"}</TableCell>
                                <TableCell className="py-2 sm:py-4">
                                  <Badge
                                    className={cn(
                                      statusConfig.bgColor,
                                      statusConfig.textColor,
                                      "gap-1 text-[10px] sm:text-xs px-1.5 sm:px-2",
                                    )}
                                  >
                                    <StatusIcon className="h-2.5 w-2.5 sm:h-3 sm:w-3" />
                                    <span className="hidden sm:inline">{statusConfig.label}</span>
                                  </Badge>
                                </TableCell>
                                <TableCell className="text-right py-2 sm:py-4">
                                  {updatingMealId === meal.id ? (
                                    <Loader2 className="h-4 w-4 animate-spin ml-auto" />
                                  ) : (
                                    <Select
                                      value={meal.status}
                                      onValueChange={(value) =>
                                        handleStatusChange(
                                          meal.id,
                                          value as Meal["status"],
                                        )
                                      }
                                    >
                                      <SelectTrigger className="w-20 sm:w-28 h-7 sm:h-8 text-xs sm:text-sm">
                                        <SelectValue />
                                      </SelectTrigger>
                                      <SelectContent>
                                        <SelectItem value="pending">
                                          Pending
                                        </SelectItem>
                                        <SelectItem value="preparing">
                                          Preparing
                                        </SelectItem>
                                        <SelectItem value="prepared">
                                          Prepared
                                        </SelectItem>
                                      </SelectContent>
                                    </Select>
                                  )}
                                </TableCell>
                              </TableRow>
                            );
                          })}
                        </TableBody>
                      </Table>
                    </div>
                  )}
                </CardContent>
              </Card>
            </div>

            {meals.some((m) => m.notes) && (
              <Card>
                <CardHeader>
                  <CardTitle>Special Notes</CardTitle>
                  <CardDescription>
                    Meals with special requirements or notes
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="space-y-3">
                    {meals
                      .filter((m) => m.notes || m.highCaloric)
                      .map((meal) => {
                        const resident =
                          typeof meal.resident === "object"
                            ? meal.resident
                            : null;
                        return (
                          <div
                            key={meal.id}
                            className="flex items-start gap-4 p-3 bg-muted rounded-lg"
                          >
                            <div className="flex-1">
                              <div className="font-medium">
                                {resident?.name} - Room {resident?.room}
                              </div>
                              {meal.highCaloric && (
                                <Badge
                                  variant="secondary"
                                  className="bg-yellow-100 text-yellow-800 mt-1"
                                >
                                  High Caloric Requirement
                                </Badge>
                              )}
                              {meal.notes && (
                                <p className="text-sm text-muted-foreground mt-1">
                                  {meal.notes}
                                </p>
                              )}
                            </div>
                          </div>
                        );
                      })}
                  </div>
                </CardContent>
              </Card>
            )}
          </>
        )}
      </main>
    </div>
  );
}
