'use client';

import { useState } from 'react';

// Admin image field backed by the /api/upload route (local /public/uploads).
// - `single` renders one current image + replace/remove.
// - `multiple` renders a list of uploaded URLs, each as a hidden <input name>
//   so AdminFormShell's FormData output includes them.
// File selection is immediate upload; the field's value is the resulting URL.

export function ImageUploadField({
  name,
  label,
  defaultValue,
  multiple = false
}: {
  name: string;
  label: string;
  defaultValue?: string | string[];
  multiple?: boolean;
}) {
  const initial = multiple
    ? Array.isArray(defaultValue)
      ? defaultValue
      : defaultValue
        ? [defaultValue]
        : []
    : typeof defaultValue === 'string'
      ? [defaultValue]
      : [];

  const [urls, setUrls] = useState<string[]>(initial);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function handleFile(file: File) {
    setBusy(true);
    setError(null);
    try {
      const fd = new FormData();
      fd.append('file', file);
      const res = await fetch('/api/upload', { method: 'POST', body: fd });
      if (!res.ok) {
        const body = await res.json().catch(() => ({}));
        throw new Error(body.error ?? 'Upload failed');
      }
      const data = (await res.json()) as { url: string };
      setUrls((prev) => (multiple ? [...prev, data.url] : [data.url]));
    } catch (err: any) {
      setError(err.message ?? 'Upload failed');
    } finally {
      setBusy(false);
    }
  }

  function remove(url: string) {
    setUrls((prev) => prev.filter((u) => u !== url));
  }

  return (
    <div className="space-y-3">
      <div>
        <p className="mb-1 block text-sm font-medium">{label}</p>
        <label className="inline-flex cursor-pointer items-center gap-2 rounded-full border border-graphite-800/20 px-4 py-2 text-sm font-medium hover:bg-graphite-900/5">
          {busy ? 'Upload…' : multiple ? '+ Ajouter une image' : 'Choisir une image'}
          <input
            type="file"
            accept="image/*"
            className="sr-only"
            disabled={busy}
            onChange={(e) => {
              const f = e.target.files?.[0];
              if (f) handleFile(f);
              e.currentTarget.value = '';
            }}
          />
        </label>
      </div>

      {urls.length > 0 && (
        <div className={multiple ? 'flex flex-wrap gap-3' : undefined}>
          {urls.map((url) => (
            <div key={url} className="relative">
              <input type="hidden" name={name} value={url} />
              {/* eslint-disable-next-line @next/next/no-img-element */}
              <img src={url} alt="" className="h-24 w-32 rounded-lg border border-graphite-800/15 object-cover" />
              <button
                type="button"
                onClick={() => remove(url)}
                className="absolute -right-2 -top-2 rounded-full bg-graphite-950 px-2 py-0.5 text-xs text-white"
                title="Retirer"
              >
                ×
              </button>
            </div>
          ))}
        </div>
      )}

      {error && <p className="text-sm text-copper-600">{error}</p>}
    </div>
  );
}