import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { headers } from "next/headers";
import Link from "next/link";
import { Printer } from "lucide-react";
import { auth } from "@/lib/auth/server";
import { db, shoppingLists, eq } from "@epicure/db";
import { ShoppingListView } from "@/components/meal-plan/shopping-list-view";
import { ShareShoppingListButton } from "@/components/shopping-lists/share-shopping-list-button";
import { GroceryExportButton } from "@/components/shopping-lists/grocery-export-button";
import { ShoppingListActionsMenu } from "@/components/shopping-lists/shopping-list-actions-menu";
import { buttonVariants } from "@/components/ui/button";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import { cn } from "@/lib/utils";
import { getShoppingListAccess, canWriteShoppingList } from "@/lib/shopping-list-access";
import { ExportMarkdownButton } from "@/components/shared/export-markdown-button";
import { shoppingListToMarkdown } from "@/lib/markdown/shopping-list";
import { getMessages, formatMessage } from "@/lib/i18n/server";
import { getFeatureFlagMatrix, isFeatureAvailableAnyTier, type Tier } from "@/lib/feature-flags";

type Params = { params: Promise<{ id: string }> };

export const metadata: Metadata = {};

export default async function ShoppingListPage({ params }: Params) {
  const { id } = await params;
  const session = await auth.api.getSession({ headers: await headers() });
  if (!session) return null;
  const m = getMessages((session.user as { locale?: string }).locale);

  const access = await getShoppingListAccess(id, session.user.id);
  if (!access) notFound();

  const list = await db.query.shoppingLists.findFirst({
    where: eq(shoppingLists.id, id),
    with: { items: { orderBy: (t, { asc }) => [asc(t.aisle), asc(t.sortOrder), asc(t.rawName)] } },
  });
  if (!list) notFound();

  const canEdit = canWriteShoppingList(access.role);
  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 instacartProviderConfigured = process.env["NEXT_PUBLIC_GROCERY_PROVIDER"] === "instacart";
  const instacartLocked = !featureFlags.grocery_delivery[viewerTier];
  const instacartAvailable = instacartProviderConfigured && isFeatureAvailableAnyTier(featureFlags, "grocery_delivery");

  return (
    <div className="space-y-6 max-w-2xl">
      <div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">{list.name}</h1>
          <p className="text-muted-foreground mt-1">
            {formatMessage(list.items.length === 1 ? m.shoppingLists.itemCount : m.shoppingLists.itemCountPlural, { count: list.items.length })}
            {list.generatedAt ? m.shoppingLists.fromMealPlan : ""}
          </p>
        </div>
        <TooltipProvider>
        <div className="flex items-center gap-2 overflow-x-auto pb-0.5 [scrollbar-width:none] [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden">
          <GroceryExportButton listId={id} instacartAvailable={instacartAvailable} instacartLocked={instacartLocked} />
          {access.role === "owner" && (
            <ShareShoppingListButton listId={id} initialIsPublic={list.isPublic} initialPublicEditable={list.publicEditable} />
          )}
          <Tooltip>
            <TooltipTrigger render={
              <Link href={`/print/shopping-list/${id}`} target="_blank" className={cn(buttonVariants({ variant: "ghost", size: "icon" }))} aria-label={m.common.print}>
                <Printer className="h-4 w-4" />
              </Link>
            } />
            <TooltipContent>{m.common.print}</TooltipContent>
          </Tooltip>
          {markdownExportAvailable && (
            <ExportMarkdownButton
              markdown={shoppingListToMarkdown({ name: list.name, items: list.items })}
              filename={list.name}
              locked={markdownExportLocked}
            />
          )}
          {access.role === "owner" && (
            <ShoppingListActionsMenu listId={id} name={list.name} redirectAfterDeleteTo="/shopping-lists" />
          )}
        </div>
        </TooltipProvider>
      </div>
      <ShoppingListView
        listId={id}
        readOnly={!canEdit}
        initialItems={list.items.map((i) => ({
          id: i.id,
          rawName: i.rawName,
          quantity: i.quantity,
          unit: i.unit,
          aisle: i.aisle,
          checked: i.checked,
          sortOrder: i.sortOrder,
        }))}
      />
    </div>
  );
}
