"use client";

import { useEffect, useRef, useState } from "react";
import Image from "next/image";

type GalleryImage = {
  id: string;
  url: string;
  width: number;
  height: number;
};

const LAYOUT_OPTIONS = [
  { value: "square", label: "Square Grid (3x3)", description: "Even square thumbnails, 3 per row." },
  { value: "landscape", label: "Landscape", description: "Wide rectangular tiles, 2 per row." },
  { value: "portrait", label: "Portrait", description: "Tall rectangular tiles, 4 per row." },
] as const;

export default function AdminGalleryPage() {
  const [images, setImages] = useState<GalleryImage[]>([]);
  const [layout, setLayout] = useState<string>("square");
  const [loading, setLoading] = useState(true);
  const [uploading, setUploading] = useState(false);
  const [savingLayout, setSavingLayout] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  async function refresh() {
    const [imagesRes, settingsRes] = await Promise.all([
      fetch("/api/admin/gallery").then((r) => r.json()),
      fetch("/api/admin/settings").then((r) => r.json()),
    ]);
    setImages(imagesRes.images ?? []);
    setLayout(settingsRes.galleryLayout ?? "square");
    setLoading(false);
  }

  useEffect(() => {
    refresh();
  }, []);

  async function handleUpload(files: FileList | null) {
    if (!files || files.length === 0) return;
    setUploading(true);
    setError(null);

    for (const file of Array.from(files)) {
      const formData = new FormData();
      formData.append("file", file);
      const res = await fetch("/api/admin/gallery", { method: "POST", body: formData });
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        setError(data.error ?? `Could not upload ${file.name}`);
      }
    }

    setUploading(false);
    if (fileInputRef.current) fileInputRef.current.value = "";
    refresh();
  }

  async function handleDelete(id: string) {
    if (!confirm("Remove this photo from the gallery?")) return;
    await fetch(`/api/admin/gallery/${id}`, { method: "DELETE" });
    refresh();
  }

  async function handleLayoutChange(value: string) {
    setLayout(value);
    setSavingLayout(true);
    await fetch("/api/admin/settings", {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ galleryLayout: value }),
    });
    setSavingLayout(false);
  }

  return (
    <div>
      <h1 className="font-display text-3xl text-rosewood">Gallery</h1>
      <p className="mt-2 text-sm text-ink/60">
        Upload photos of your work for visitors to browse at{" "}
        <span className="font-mono text-xs">/gallery</span>.
      </p>

      <div className="mt-8 max-w-2xl rounded-2xl border border-blush-dark/50 bg-white p-6">
        <h2 className="font-display text-xl text-rosewood">Layout</h2>
        <p className="mt-1 text-xs text-ink/50">
          Choose how photos are arranged on the public gallery page.
        </p>
        <div className="mt-4 grid gap-3 sm:grid-cols-3">
          {LAYOUT_OPTIONS.map((option) => (
            <button
              key={option.value}
              type="button"
              disabled={savingLayout}
              onClick={() => handleLayoutChange(option.value)}
              className={`rounded-xl border p-4 text-left transition disabled:opacity-50 ${
                layout === option.value
                  ? "border-rosewood bg-blush"
                  : "border-blush-dark/60 hover:border-rose"
              }`}
            >
              <p className="text-sm font-medium text-ink">{option.label}</p>
              <p className="mt-1 text-xs text-ink/50">{option.description}</p>
            </button>
          ))}
        </div>
      </div>

      <div className="mt-8 max-w-2xl rounded-2xl border border-blush-dark/50 bg-white p-6">
        <h2 className="font-display text-xl text-rosewood">Upload Photos</h2>
        <p className="mt-1 text-xs text-ink/50">JPEG, PNG, or WEBP, up to 20MB each.</p>
        <input
          ref={fileInputRef}
          type="file"
          accept="image/*"
          multiple
          disabled={uploading}
          onChange={(e) => handleUpload(e.target.files)}
          className="mt-4 block w-full text-sm"
        />
        {uploading && <p className="mt-2 text-xs text-rose-dark">Uploading&hellip;</p>}
        {error && <p className="mt-2 text-sm text-red-600">{error}</p>}
      </div>

      <div className="mt-8">
        <h2 className="font-display text-xl text-rosewood">
          Photos {loading ? "" : `(${images.length})`}
        </h2>
        <div className="mt-4 grid grid-cols-2 gap-4 sm:grid-cols-3 md:grid-cols-4">
          {images.map((image) => (
            <div
              key={image.id}
              className="group relative aspect-square overflow-hidden rounded-xl bg-blush"
            >
              <Image
                src={image.url}
                alt=""
                fill
                sizes="200px"
                className="object-cover"
              />
              <button
                onClick={() => handleDelete(image.id)}
                className="absolute right-2 top-2 rounded-full bg-ink/70 px-3 py-1 text-xs text-cream opacity-0 transition group-hover:opacity-100"
              >
                Delete
              </button>
            </div>
          ))}
          {!loading && images.length === 0 && (
            <p className="col-span-full py-8 text-center text-sm text-ink/50">
              No photos uploaded yet.
            </p>
          )}
        </div>
      </div>
    </div>
  );
}
