"use client";
import { useEffect, useState, type FormEvent } from "react";
import { prepareImage } from "@/lib/prepare-image";
export type LibraryImage = {
  id: string;
  url: string;
  alt: string;
  name: string;
  width: number;
  height: number;
};
export function MediaLibrary({
  onSelect,
}: {
  onSelect?: (image: LibraryImage) => void;
}) {
  const [images, setImages] = useState<LibraryImage[]>([]),
    [error, setError] = useState(""),
    [uploading, setUploading] = useState(false),
    [alt, setAlt] = useState("");
  async function refresh() {
    const response = await fetch("/api/admin/media/");
    if (response.ok) setImages(await response.json());
    else setError("Unable to load images.");
  }
  useEffect(() => {
    void refresh();
  }, []);
  async function upload(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setUploading(true);
    setError("");
    try {
      const data = new FormData(event.currentTarget);
      const original = data.get("file");
      if (!(original instanceof File))
        throw new Error("Choose an image to upload.");
      data.set("originalName", original.name);
      data.set("file", await prepareImage(original));
      const response = await fetch("/api/admin/media/", {
          method: "POST",
          body: data,
        }),
        result = await response.json();
      if (!response.ok) throw new Error(result.error);
      await refresh();
      setAlt("");
    } catch (error) {
      setError(error instanceof Error ? error.message : "Upload failed");
    } finally {
      setUploading(false);
    }
  }
  return (
    <>
      <form className="admin-upload" onSubmit={upload}>
        <label>
          Choose an image
          <input
            type="file"
            name="file"
            accept="image/jpeg,image/png,image/webp,image/avif"
            required
          />
        </label>
        <label>
          Alternative text
          <input
            name="alt"
            value={alt}
            onChange={(event) => setAlt(event.target.value)}
            placeholder="Describe the image for accessibility"
            maxLength={300}
          />
        </label>
        <button className="admin-button" disabled={uploading}>
          {uploading ? "Uploading…" : "Upload image"}
        </button>
        <p>
          JPG, PNG, WebP or AVIF, up to 10 MB. Large images are optimized before
          upload.
        </p>
      </form>
      {error && (
        <p className="admin-error" role="alert">
          {error}
        </p>
      )}
      <div className="admin-media-grid">
        {images.map((image) => (
          <figure key={image.id}>
            <button
              type="button"
              className="admin-image-choice"
              onClick={() => onSelect?.(image)}
              aria-label={onSelect ? "Use " + image.name : image.name}
            >
              <img src={image.url} alt={image.alt} loading="lazy" />
            </button>
            <figcaption>
              <strong>{image.name}</strong>
              <span>
                {image.width} × {image.height}
              </span>
              <label>
                Alternative text
                <input
                  value={image.alt}
                  maxLength={300}
                  onChange={(event) =>
                    setImages(
                      images.map((item) =>
                        item.id === image.id
                          ? { ...item, alt: event.target.value }
                          : item,
                      ),
                    )
                  }
                  onBlur={async () => {
                    try {
                      const response = await fetch("/api/admin/media/", {
                        method: "PATCH",
                        headers: { "Content-Type": "application/json" },
                        body: JSON.stringify({ id: image.id, alt: image.alt }),
                      });
                      if (!response.ok)
                        throw new Error(
                          "Alternative text could not be saved. Please try again.",
                        );
                      setError("");
                    } catch (error) {
                      setError(
                        error instanceof Error
                          ? error.message
                          : "Unable to save alternative text.",
                      );
                    }
                  }}
                />
              </label>
              {onSelect && (
                <button
                  className="admin-button secondary"
                  onClick={() => onSelect(image)}
                >
                  Use image
                </button>
              )}
            </figcaption>
          </figure>
        ))}
      </div>
    </>
  );
}
