"use client";

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

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

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

  return (
    <section className="min-w-0 overflow-hidden rounded-xl border border-[var(--border)] bg-[var(--bg)] p-4">
      <div className="flex min-w-0 items-start justify-between gap-3">
        <div className="min-w-0">
          <h3 className="text-sm font-semibold text-[var(--text)]">{t("backgroundMedia")}</h3>
          <p className="mt-1 text-xs leading-5 text-[var(--text-faint)]">{t("backgroundDescription")}</p>
        </div>
        {background && (
          <button
            type="button"
            title={t("removeBackground")}
            aria-label={t("removeBackground")}
            disabled={disabled}
            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="relative mt-4 aspect-[16/7] w-full overflow-hidden rounded-lg border border-dashed border-[var(--border)] bg-[var(--bg-elevated)]">
        {background ? (
          background.type === "video" ? (
            <video src={background.url} muted autoPlay loop playsInline className={`h-full w-full ${background.fit === "contain" ? "object-contain" : "object-cover"}`} />
          ) : (
            // The image is a user-provided Menu Board asset served by the existing upload endpoint.
            // eslint-disable-next-line @next/next/no-img-element
            <img src={background.url} alt={t("backgroundAlt")} className={`h-full w-full ${background.fit === "contain" ? "object-contain" : "object-cover"}`} />
          )
        ) : (
          <div className="grid h-full place-items-center text-[var(--text-faint)]">
            <ImagePlus className="h-6 w-6" />
          </div>
        )}
      </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("uploadingBackground") : t("uploadBackground")}
      </Button>
      <p className="mt-2 break-words text-[11px] leading-4 text-[var(--text-faint)]"><Video className="mr-1 inline h-3 w-3" />{t("mediaLimits")}</p>
      {error && <p className="mt-2 break-words text-xs text-red-400">{error}</p>}

      {background && (
        <div className="mt-4 space-y-4 border-t border-[var(--border)] pt-4">
          <label className="block text-xs font-medium text-[var(--text-muted)]">
            {t("mediaFit")}
            <select
              className="mt-1.5 w-full rounded-lg border border-[var(--border)] bg-[var(--bg-elevated)] px-3 py-2 text-sm text-[var(--text)] outline-none focus:border-[var(--accent)]"
              value={background.fit}
              disabled={disabled}
              onChange={(event) => onChange({ ...background, fit: event.target.value as MenuBoardBackground["fit"] })}
            >
              <option value="cover">{t("fillScreen")}</option>
              <option value="contain">{t("showWholeImage")}</option>
            </select>
          </label>
          <label className="block text-xs font-medium text-[var(--text-muted)]">
            {t("darkOverlay", { value: background.overlay })}
            <input
              className="mt-2 h-1.5 w-full cursor-pointer accent-[var(--accent)] disabled:cursor-not-allowed"
              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} />
    </section>
  );
}
