"use client";

import { type ChangeEvent, useRef, useState } from "react";
import { ImagePlus, Loader2, Trash2, Upload } from "lucide-react";
import Button from "@/components/ui/Button";
import { useMenuBoardText } from "@/components/business/menu-boards/menuBoardI18n";

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

export default function MenuBoardBrandLogoControl({ businessId, logo, disabled, onChange }: Props) {
  const t = useMenuBoardText();
  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 data = new FormData();
      data.set("file", file);
      data.set("kind", "brand");
      const response = await fetch(`/api/businesses/${businessId}/menu-boards/upload`, { method: "POST", body: data });
      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 : t("uploadLogo"));
      }
      onChange(result.url);
    } catch (cause) {
      setError(cause instanceof Error ? cause.message : t("uploadLogo"));
    } finally {
      setUploading(false);
      event.target.value = "";
    }
  }

  return (
    <section className="rounded-xl border border-[var(--border)] bg-[var(--bg)] p-4">
      <div className="flex items-start justify-between gap-3">
        <div>
          <h3 className="text-sm font-semibold text-[var(--text)]">{t("brandLogo")}</h3>
          <p className="mt-1 text-xs leading-5 text-[var(--text-faint)]">{t("brandLogoDescription")}</p>
        </div>
        {logo && <button type="button" title={t("removeLogo")} aria-label={t("removeLogo")} 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>
      <div className="mt-3 grid aspect-[4/1] place-items-center overflow-hidden rounded-lg border border-dashed border-[var(--border)] bg-[var(--bg-elevated)]">
        {logo ? (
          // This image is uploaded through the authenticated Menu Board asset endpoint.
          // eslint-disable-next-line @next/next/no-img-element
          <img src={logo} alt={t("brandLogo")} className="h-full w-full object-contain p-3" />
        ) : <ImagePlus className="h-5 w-5 text-[var(--text-faint)]" />}
      </div>
      <Button type="button" variant="secondary" size="sm" className="mt-3 w-full justify-center" disabled={disabled || uploading} onClick={() => inputRef.current?.click()}>
        {uploading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Upload className="h-4 w-4" />}
        {uploading ? t("uploadingLogo") : logo ? t("replaceLogo") : t("uploadLogo")}
      </Button>
      {error && <p className="mt-2 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} />
    </section>
  );
}
