"use client";

import { useState } from "react";
import { useTranslations } from "next-intl";
import { ShoppingBag, Copy, ExternalLink } from "lucide-react";
import { toast } from "sonner";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Button } from "@/components/ui/button";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import type { GroceryExportPayload } from "@/lib/grocery-export";
import { groceryExportToText } from "@/lib/grocery-export";
import { UpgradeDialog } from "@/components/premium/upgrade-dialog";
import { ProBadge } from "@/components/premium/pro-badge";

interface Props {
  listId: string;
  /** Set when NEXT_PUBLIC_GROCERY_PROVIDER=instacart and the feature is
   * enabled for at least one tier — otherwise only "copy as text" is
   * offered, since there's no upgrade path to point at. */
  instacartAvailable: boolean;
  /** Available on some tier but not the viewer's — the menu item still
   * shows (with a "Pro" upsell) instead of hiding. */
  instacartLocked?: boolean;
}

export function GroceryExportButton({ listId, instacartAvailable, instacartLocked = false }: Props) {
  const t = useTranslations("shoppingLists");
  const [loading, setLoading] = useState(false);
  const [upgradeOpen, setUpgradeOpen] = useState(false);

  async function fetchPayload(): Promise<GroceryExportPayload | null> {
    const res = await fetch(`/api/v1/shopping-lists/${listId}/export`);
    if (!res.ok) {
      toast.error(t("exportBuildFailed"));
      return null;
    }
    return res.json() as Promise<GroceryExportPayload>;
  }

  async function handleCopy() {
    setLoading(true);
    try {
      const payload = await fetchPayload();
      if (!payload) return;
      await navigator.clipboard.writeText(groceryExportToText(payload));
      toast.success(t("copiedToClipboard"));
    } finally {
      setLoading(false);
    }
  }

  async function handleInstacart() {
    setLoading(true);
    try {
      const res = await fetch(`/api/v1/shopping-lists/${listId}/export/instacart`, { method: "POST" });
      if (!res.ok) {
        toast.error(t("instacartNotConfigured"));
        return;
      }
      const { url } = await res.json() as { url: string };
      window.open(url, "_blank");
    } finally {
      setLoading(false);
    }
  }

  return (
    <DropdownMenu>
      <TooltipProvider>
        <Tooltip>
          <TooltipTrigger render={
            <DropdownMenuTrigger render={
              <Button variant="ghost" size="icon" disabled={loading} aria-label={t("sendToGroceryDelivery")}>
                <ShoppingBag className="h-4 w-4" />
              </Button>
            } />
          } />
          <TooltipContent>{t("sendToGroceryDelivery")}</TooltipContent>
        </Tooltip>
      </TooltipProvider>
      <DropdownMenuContent align="end">
        <DropdownMenuItem onClick={() => void handleCopy()}>
          <Copy className="h-4 w-4" />
          {t("copyAsText")}
        </DropdownMenuItem>
        {instacartAvailable && (
          <DropdownMenuItem onClick={() => (instacartLocked ? setUpgradeOpen(true) : void handleInstacart())}>
            <ExternalLink className="h-4 w-4" />
            {t("sendToInstacart")}
            {instacartLocked && <ProBadge className="ml-auto" />}
          </DropdownMenuItem>
        )}
      </DropdownMenuContent>
      <UpgradeDialog
        open={upgradeOpen}
        onOpenChange={setUpgradeOpen}
        featureKey="grocery_delivery"
        featureLabel="Grocery delivery integration"
      />
    </DropdownMenu>
  );
}
