"use client";

/**
 * فیلد یک عکس در فرم‌های پنل (بنر، کاور مقاله). عکس بلافاصله آپلود و به WebP تبدیل می‌شود
 * و آدرس آن در یک input مخفی با نام name قرار می‌گیرد تا همراه فرم ذخیره شود.
 */
import { useRef, useState } from "react";
import { imageSrc } from "@/lib/media";
import { uploadMediaAction } from "@/server/admin/images";

interface Props {
  name: string;
  target: "banners" | "articles";
  initialUrl?: string | null;
  /** نام فیلد متن جایگزین (alt)؛ اگر داده شود کنار عکس نمایش داده می‌شود */
  altName?: string;
  initialAlt?: string | null;
  label?: string;
  /** برای فرم‌های کلاینتی: با آپلود یا حذف عکس صدا زده می‌شود */
  onChange?: (url: string) => void;
}

export function ImageField({ name, target, initialUrl, altName, initialAlt, label = "عکس", onChange }: Props) {
  const [url, setUrl] = useState(initialUrl ?? "");
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState("");
  const inputRef = useRef<HTMLInputElement>(null);

  async function upload(file: File) {
    setError("");
    if (file.size > 10 * 1024 * 1024) return setError("حجم عکس باید کمتر از ۱۰ مگابایت باشد");
    setBusy(true);
    const fd = new FormData();
    fd.set("file", file);
    const res = await uploadMediaAction(target, fd).catch(() => ({ ok: false as const, error: "ارتباط با سرور قطع شد" }));
    setBusy(false);
    if (inputRef.current) inputRef.current.value = "";
    if (!res.ok) return setError(res.error);
    setUrl(res.url);
    onChange?.(res.url);
  }

  return (
    <div className="space-y-2">
      <span className="label">{label}</span>
      <input type="hidden" name={name} value={url} />
      <div className="flex items-start gap-3">
        <div className="grid size-20 shrink-0 place-items-center overflow-hidden rounded-xl bg-mist text-[11px] text-muted">
          {/* eslint-disable-next-line @next/next/no-img-element */}
          {url ? <img src={imageSrc(url, 400)} alt="" className="size-full object-contain" /> : "بدون عکس"}
        </div>
        <div className="min-w-0 flex-1 space-y-2">
          <div className="flex flex-wrap gap-2">
            <button type="button" className="btn-outline h-9 px-3 text-xs" disabled={busy} onClick={() => inputRef.current?.click()}>
              {busy ? "در حال تبدیل به WebP…" : url ? "تعویض عکس" : "انتخاب عکس"}
            </button>
            {url && !busy && (
              <button type="button" className="h-9 px-2 text-xs text-muted underline" onClick={() => {
                  setUrl("");
                  onChange?.("");
                }}>
                حذف عکس
              </button>
            )}
          </div>
          {altName && <input name={altName} defaultValue={initialAlt ?? ""} placeholder="متن جایگزین عکس (alt) برای سئو" maxLength={140} className="field h-9 text-xs" />}
          <p className="text-[11px] leading-5 text-muted">هر فرمت و هر ابعادی خودکار به WebP مربع ۱:۱ تبدیل می‌شود (عکس وسط کادر، اطراف خاکستری یکدست).</p>
          {error && <p role="alert" className="text-xs">⚠ {error}</p>}
        </div>
      </div>
      <input ref={inputRef} type="file" accept="image/*,.heic,.heif" className="sr-only" tabIndex={-1} onChange={(e) => e.target.files?.[0] && void upload(e.target.files[0])} />
    </div>
  );
}
