"use client";

import { useRef } from "react";
import { Box } from "lucide-react";
import { useTranslations } from "next-intl";
import { useQuery } from "@tanstack/react-query";
import { apiGet, apiUpload, ApiClientError } from "@/lib/api/client";
import { MENU_3D_GLB_MAX_MB, MENU_360_PHOTO_COUNT } from "@/lib/menu-3d";
import { Button } from "@/components/ui/button";

type Menu3dUploadProps = {
  cafeId: string;
  model3dUrl?: string | null;
  onChange: (url: string | null) => void;
};

export function Menu3dUpload({ cafeId, model3dUrl, onChange }: Menu3dUploadProps) {
  const t = useTranslations("media");
  const tSub = useTranslations("subscription");
  const ref = useRef<HTMLInputElement>(null);
  const { data: billing } = useQuery({
    queryKey: ["billing-status", cafeId],
    queryFn: () => apiGet<{ menu3dEnabled: boolean }>("/api/billing/status"),
    enabled: !!cafeId,
  });
  const enabled = billing?.menu3dEnabled ?? false;

  return (
    <div className="space-y-2 rounded-lg border border-dashed border-border/80 bg-muted/20 p-3">
      <p className="text-xs font-medium text-foreground">{t("upload3dTitle")}</p>
      <p className="text-xs text-muted-foreground">{t("upload3dHint", { maxMb: MENU_3D_GLB_MAX_MB })}</p>
      {!enabled ? (
        <p className="text-xs text-amber-700">{tSub("featureMenu3dUpgrade")}</p>
      ) : null}
      <p className="text-[11px] text-muted-foreground">
        {t("upload3dPhotoCount", {
          min: MENU_360_PHOTO_COUNT.min,
          ideal: MENU_360_PHOTO_COUNT.ideal,
        })}
      </p>
      <div className="flex flex-wrap gap-2">
        <input
          ref={ref}
          type="file"
          accept=".glb,model/gltf-binary"
          className="hidden"
          onChange={(e) => {
            const f = e.target.files?.[0];
            if (!f) return;
            void apiUpload<{ url: string }>(`/api/cafes/${cafeId}/media/menu-model3d`, f)
              .then((d) => onChange(d.url))
              .catch((err) => {
                if (err instanceof ApiClientError && err.code === "PLAN_FEATURE_DISABLED") {
                  alert(tSub("featureMenu3dUpgrade"));
                }
              });
          }}
        />
        <Button
          type="button"
          size="sm"
          variant="outline"
          disabled={!enabled}
          onClick={() => ref.current?.click()}
        >
          <Box className="me-1 h-3.5 w-3.5" />
          {t("upload3d")}
        </Button>
        {model3dUrl ? (
          <Button type="button" size="sm" variant="ghost" onClick={() => onChange(null)}>
            {t("remove3d")}
          </Button>
        ) : null}
      </div>
      {model3dUrl ? (
        <p className="text-[11px] text-[#0F6E56]">{t("upload3dReady")}</p>
      ) : null}
    </div>
  );
}
