"use client";

import { X } from "lucide-react";
import { useTranslations } from "next-intl";
import { MenuItemModelViewer } from "@/components/menu/menu-item-model-viewer";
import { MenuItemLabels } from "@/components/menu/menu-item-labels";
import { formatCurrency } from "@/lib/format";
import type { QrPublicMenuItem } from "@/lib/api/qr-public";
import { Button } from "@/components/ui/button";

type QrMenu3dSheetProps = {
  item: QrPublicMenuItem;
  primary: string;
  onClose: () => void;
  onAdd: () => void;
  addLabel: string;
};

export function QrMenu3dSheet({ item, primary, onClose, onAdd, addLabel }: QrMenu3dSheetProps) {
  const t = useTranslations("qrMenu");

  if (!item.model3dUrl) return null;

  return (
    <div
      className="fixed inset-0 z-50 flex flex-col bg-black/50 backdrop-blur-sm"
      role="dialog"
      aria-modal="true"
      aria-label={t("view3d")}
    >
      <div className="mx-auto mt-auto flex w-full max-w-md flex-col rounded-t-2xl qr-surface shadow-2xl">
        <div className="flex items-center justify-between border-b px-4 py-3">
          <div className="min-w-0 flex-1">
            <MenuItemLabels item={item} lines={1} primaryClassName="text-base font-semibold" />
            <p className="text-sm font-medium" style={{ color: primary }}>
              {formatCurrency(effectiveItemPrice(item), "fa-IR")}
            </p>
          </div>
          <Button type="button" size="icon" variant="ghost" onClick={onClose} aria-label={t("close3d")}>
            <X className="h-5 w-5" />
          </Button>
        </div>
        <p className="px-4 pt-2 text-center text-xs qr-muted">{t("view3dHint")}</p>
        <div className="min-h-[50vh] w-full px-2 pb-2">
          <MenuItemModelViewer
            modelUrl={item.model3dUrl}
            posterUrl={item.imageUrl}
            alt={item.name}
            className="rounded-xl"
          />
        </div>
        <div className="border-t p-4">
          <Button
            type="button"
            className="w-full text-white"
            style={{ backgroundColor: primary }}
            onClick={() => {
              onAdd();
              onClose();
            }}
          >
            {addLabel}
          </Button>
        </div>
      </div>
    </div>
  );
}

function effectiveItemPrice(item: QrPublicMenuItem): number {
  const discount = item.discountPercent > 0 ? item.discountPercent : 0;
  return Math.round(item.price * (1 - discount / 100));
}
