"use client";

import { type ChangeEvent, useRef, useState } from "react";
import { ImagePlus, Loader2, Trash2 } from "lucide-react";

type Props = {
  businessId: string;
  imageUrl?: string | null;
  disabled?: boolean;
  onChange: (imageUrl: string | null) => void;
};

export default function MenuBoardProductImageControl({ businessId, imageUrl, disabled, onChange }: Props) {
  const inputRef = useRef<HTMLInputElement>(null);
  const [uploading, setUploading] = useState(false);
  const [error, setError] = useState("");

  async function upload(event: ChangeEvent<HTMLInputElement>) {
    const file = event.target.files?.[0];
    if (!file || disabled) return;

    setUploading(true);
    setError("");
    try {
      const body = new FormData();
      body.set("file", file);
      body.set("kind", "product");
      const response = await fetch(`/api/businesses/${businessId}/menu-boards/upload`, { method: "POST", body });
      const result = await response.json().catch(() => ({}));
      if (!response.ok || result.type !== "image" || typeof result.url !== "string") {
        throw new Error(typeof result.error === "string" ? result.error : "Product image upload failed");
      }
      onChange(result.url);
    } catch (cause) {
      setError(cause instanceof Error ? cause.message : "Product image upload failed");
    } finally {
      setUploading(false);
      event.target.value = "";
    }
  }

  return (
    <div className="min-w-0">
      <div className="flex items-center gap-2">
        <button
          type="button"
          title={imageUrl ? "Replace product image" : "Add product image"}
          aria-label={imageUrl ? "Replace product image" : "Add product image"}
          disabled={disabled || uploading}
          onClick={() => inputRef.current?.click()}
          className="grid h-10 w-10 shrink-0 place-items-center overflow-hidden rounded-lg border border-[var(--border)] bg-[var(--bg-elevated)] text-[var(--text-muted)] transition hover:border-[var(--accent)] hover:text-[var(--accent)] disabled:cursor-not-allowed disabled:opacity-50"
        >
          {uploading ? <Loader2 className="h-4 w-4 animate-spin" /> : imageUrl ? (
            // Product images are uploaded through this module's authenticated asset endpoint.
            // eslint-disable-next-line @next/next/no-img-element
            <img src={imageUrl} alt="Product" className="h-full w-full object-cover" />
          ) : <ImagePlus className="h-4 w-4" />}
        </button>
        {imageUrl && (
          <button
            type="button"
            title="Remove product image"
            aria-label="Remove product image"
            disabled={disabled || uploading}
            onClick={() => onChange(null)}
            className="grid h-9 w-9 shrink-0 place-items-center rounded-lg text-[var(--text-muted)] transition hover:bg-red-500/10 hover:text-red-400 disabled:cursor-not-allowed disabled:opacity-50"
          >
            <Trash2 className="h-4 w-4" />
          </button>
        )}
      </div>
      {error && <p className="mt-1 text-xs text-red-400">{error}</p>}
      <input ref={inputRef} type="file" className="hidden" accept="image/jpeg,image/png,image/webp,image/gif" disabled={disabled || uploading} onChange={upload} />
    </div>
  );
}
