import type { Metadata } from "next";
import { headers } from "next/headers";
import { auth } from "@/lib/auth/server";
import { db, pantryItems, recipes, cookingHistory, eq, and, or, inArray, isNotNull } from "@epicure/db";
import { asc } from "@epicure/db";
import { PantryManager } from "@/components/meal-plan/pantry-manager";
import { PantryPageHeader } from "@/components/pantry/pantry-page-header";
import { ExpiringSoonSuggestions } from "@/components/pantry/expiring-soon-suggestions";
import { ExpiringLeftovers } from "@/components/pantry/expiring-leftovers";
import { scoreRecipesAgainstPantry } from "@/lib/pantry-match";
import { dishExpiresAt, daysUntil, isLeftoverExpiringSoon } from "@/lib/leftover-match";
import { getPublicUrl } from "@/lib/storage";
import { getFeatureFlagMatrix, isFeatureAvailableAnyTier, type Tier } from "@/lib/feature-flags";
import { loadIngredientAliasIndex } from "@/lib/ingredient-match";

export const metadata: Metadata = {};

export default async function PantryPage() {
  const session = await auth.api.getSession({ headers: await headers() });
  if (!session) return null;
  const viewerTier = (session.user as { tier?: string }).tier as Tier | undefined ?? "free";
  const featureFlags = await getFeatureFlagMatrix();
  const markdownExportLocked = !featureFlags.markdown_export[viewerTier];
  const markdownExportAvailable = isFeatureAvailableAnyTier(featureFlags, "markdown_export");

  const [items, candidateRecipes, cookedDishes, aliasIndex] = await Promise.all([
    db.query.pantryItems.findMany({
      where: eq(pantryItems.userId, session.user.id),
      orderBy: asc(pantryItems.rawName),
    }),
    db.query.recipes.findMany({
      where: or(eq(recipes.authorId, session.user.id), inArray(recipes.visibility, ["public", "unlisted"])),
      with: { ingredients: true, photos: true },
    }),
    db.query.cookingHistory.findMany({
      where: and(eq(cookingHistory.userId, session.user.id), isNotNull(cookingHistory.batchDishId)),
      with: {
        batchDish: { columns: { id: true, name: true, fridgeDays: true } },
        recipe: { columns: { id: true, title: true } },
      },
    }),
    loadIngredientAliasIndex(),
  ]);

  const mappedItems = items.map((i) => ({
    id: i.id,
    rawName: i.rawName,
    quantity: i.quantity,
    unit: i.unit,
    notes: i.notes,
    aisle: i.aisle,
    expiresAt: i.expiresAt?.toISOString() ?? null,
  }));

  const suggestions = scoreRecipesAgainstPantry(candidateRecipes, items, aliasIndex)
    .filter((s) => s.usesExpiring.length > 0)
    .slice(0, 3)
    .map((s) => {
      const cover = s.recipe.photos?.find((p) => p.isCover) ?? s.recipe.photos?.[0];
      return {
        id: s.recipe.id,
        title: s.recipe.title,
        photoUrl: cover ? getPublicUrl(cover.storageKey) : null,
        usesExpiring: s.usesExpiring,
      };
    });

  const latestByDish = new Map<string, (typeof cookedDishes)[number]>();
  for (const log of cookedDishes) {
    if (!log.batchDish) continue;
    const existing = latestByDish.get(log.batchDish.id);
    if (!existing || log.cookedAt > existing.cookedAt) latestByDish.set(log.batchDish.id, log);
  }
  const leftovers = [...latestByDish.values()]
    .filter((log) => log.batchDish && isLeftoverExpiringSoon(log.cookedAt, log.batchDish.fridgeDays))
    .map((log) => ({
      recipeId: log.recipe.id,
      dishName: log.batchDish!.name,
      recipeTitle: log.recipe.title,
      expiresAt: dishExpiresAt(log.cookedAt, log.batchDish!.fridgeDays).toISOString(),
      daysLeft: daysUntil(dishExpiresAt(log.cookedAt, log.batchDish!.fridgeDays)),
    }))
    .sort((a, b) => a.daysLeft - b.daysLeft);

  return (
    <div className="space-y-6">
      <PantryPageHeader items={mappedItems} markdownExportAvailable={markdownExportAvailable} markdownExportLocked={markdownExportLocked} />
      <ExpiringLeftovers leftovers={leftovers} />
      <ExpiringSoonSuggestions suggestions={suggestions} />
      <PantryManager key={mappedItems.map((i) => i.id).join(",")} initialItems={mappedItems} />
    </div>
  );
}
