"use client";

import { ChangeEvent, useRef, useState } from "react";
import { ImagePlus, Loader2, Trash2, Upload, Video } from "lucide-react";
import Button from "@/components/ui/Button";

export type MenuBoardBackground = {
  type: "image" | "video";
  url: string;
  fit: "cover" | "contain";
  overlay: number;
};

export default function MenuBoardBackgroundControl({
  businessId, background, disabled, onChange,
}: {
  businessId: string;
  background?: MenuBoardBackground | null;
  disabled?: boolean;
  onChange: (value: MenuBoardBackground | null) => void;
}) {
  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);
      const response = await fetch(`/api/businesses/${businessId}/menu-boards/upload`, { method: "POST", body });
      const data = await response.json().catch(() => ({}));
      if (!response.ok || typeof data.url !== "string") throw new Error(typeof data.error === "string" ? data.error : "Upload failed");
      onChange({ type: data.type === "video" ? "video" : "image", url: data.url, fit: "cover", overlay: 45 });
    } catch (cause) { setError(cause instanceof Error ? cause.message : "Upload failed"); }
    finally { setUploading(false); event.target.value = ""; }
  }

  return <div className="rounded-xl border border-[var(--border)] p-4">
    <div className="flex items-start justify-between gap-3"><div><h3 className="text-sm font-semibold text-[var(--text)]">Background media</h3><p className="mt-1 text-xs text-[var(--text-faint)]">Use an image, logo, or muted looping video behind the menu.</p></div>{background && <button type="button" title="Remove background" disabled={disabled} onClick={() => onChange(null)} className="rounded-lg p-2 text-[var(--text-muted)] hover:bg-red-500/10 hover:text-red-400"><Trash2 className="h-4 w-4" /></button>}</div>
    <div className="mt-3 flex flex-col gap-3 sm:flex-row"><div className="flex h-28 w-full shrink-0 items-center justify-center overflow-hidden rounded-lg border border-dashed border-[var(--border)] bg-[var(--bg)] sm:w-44">{background ? background.type === "video" ? <video src={background.url} muted autoPlay loop playsInline className="h-full w-full object-cover" /> : <img src={background.url} alt="" className="h-full w-full object-cover" /> : <ImagePlus className="h-6 w-6 text-[var(--text-faint)]" />}</div><div className="flex flex-1 flex-col justify-center gap-2"><Button type="button" variant="secondary" size="sm" disabled={disabled || uploading} onClick={() => inputRef.current?.click()}>{uploading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Upload className="h-4 w-4" />}{uploading ? "Uploading..." : "Upload background"}</Button><p className="text-[11px] text-[var(--text-faint)]"><Video className="mr-1 inline h-3 w-3" />Images up to 10MB. MP4, WebM, or MOV video up to 40MB.</p>{error && <p className="text-xs text-red-400">{error}</p>}</div></div>
    {background && <div className="mt-4 grid gap-3 sm:grid-cols-2"><label className="text-xs text-[var(--text-muted)]">Media fit<select className="mt-1 w-full rounded-lg border border-[var(--border)] bg-[var(--bg)] px-3 py-2 text-sm text-[var(--text)]" value={background.fit} disabled={disabled} onChange={(event) => onChange({ ...background, fit: event.target.value as MenuBoardBackground["fit"] })}><option value="cover">Fill screen</option><option value="contain">Show whole image</option></select></label><label className="text-xs text-[var(--text-muted)]">Dark overlay: {background.overlay}%<input className="mt-2 w-full accent-[var(--accent)]" type="range" min="0" max="90" value={background.overlay} disabled={disabled} onChange={(event) => onChange({ ...background, overlay: Number(event.target.value) })} /></label></div>}
    <input ref={inputRef} type="file" className="hidden" accept="image/jpeg,image/png,image/webp,image/gif,video/mp4,video/webm,video/quicktime" onChange={upload} disabled={disabled || uploading} />
  </div>;
}
