"use client";

import { useRef, useState } from "react";
import { useRouter } from "next/navigation";
import type { StoryPhotos } from "@/lib/types";

async function uploadFile(file: File): Promise<string> {
  const body = new FormData();
  body.append("file", file);
  const res = await fetch("/api/admin/upload", { method: "POST", body });
  if (!res.ok) {
    const data = await res.json().catch(() => null);
    throw new Error(data?.error ?? "Upload failed");
  }
  const data: { url: string } = await res.json();
  return data.url;
}

export function StoryPhotosManager({ initial }: { initial: StoryPhotos }) {
  const router = useRouter();
  const [data, setData] = useState(initial);
  const [busy, setBusy] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const heroInputRef = useRef<HTMLInputElement>(null);
  const addInputRef = useRef<HTMLInputElement>(null);

  async function replaceHero(file: File) {
    setBusy("hero");
    setError(null);
    try {
      const url = await uploadFile(file);
      const res = await fetch("/api/story-photos", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ url, caption: data.hero.caption }),
      });
      const updated: StoryPhotos = await res.json();
      setData(updated);
      router.refresh();
    } catch (e) {
      setError(e instanceof Error ? e.message : "Something went wrong");
    } finally {
      setBusy(null);
    }
  }

  async function addPhoto(file: File) {
    setBusy("add");
    setError(null);
    try {
      const url = await uploadFile(file);
      const res = await fetch("/api/story-photos", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ url }),
      });
      const updated: StoryPhotos = await res.json();
      setData(updated);
      router.refresh();
    } catch (e) {
      setError(e instanceof Error ? e.message : "Something went wrong");
    } finally {
      setBusy(null);
    }
  }

  async function removePhoto(id: string) {
    if (!confirm("Remove this photo from the gallery?")) return;
    setBusy(id);
    const res = await fetch(`/api/story-photos/gallery/${id}`, { method: "DELETE" });
    const updated: StoryPhotos = await res.json();
    setData(updated);
    setBusy(null);
    router.refresh();
  }

  async function saveCaption(id: string, caption: string) {
    setData((d) => ({ ...d, gallery: d.gallery.map((p) => (p.id === id ? { ...p, caption } : p)) }));
    await fetch(`/api/story-photos/gallery/${id}`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ caption }),
    });
  }

  return (
    <div className="space-y-10">
      {error && <p className="text-sm text-tomato">{error}</p>}

      <section>
        <h2 className="text-sm font-semibold uppercase tracking-wide text-ink/50">Hero banner</h2>
        <p className="mt-1 text-xs text-ink/50">The large photo at the top of the Our Story page.</p>
        <div className="mt-3 flex items-start gap-4">
          <img src={data.hero.url} alt="" className="h-32 w-48 rounded-lg object-cover" />
          <div>
            <button
              type="button"
              onClick={() => heroInputRef.current?.click()}
              disabled={busy === "hero"}
              className="rounded-lg border border-dashed border-ink/25 px-4 py-2 text-sm text-ink/60 hover:border-ink/40 disabled:opacity-60"
            >
              {busy === "hero" ? "Uploading…" : "Replace hero photo"}
            </button>
            <input
              ref={heroInputRef}
              type="file"
              accept="image/jpeg,image/png,image/webp"
              className="hidden"
              onChange={(e) => {
                const file = e.target.files?.[0];
                if (file) replaceHero(file);
                e.target.value = "";
              }}
            />
          </div>
        </div>
      </section>

      <section>
        <h2 className="text-sm font-semibold uppercase tracking-wide text-ink/50">Gallery</h2>
        <p className="mt-1 text-xs text-ink/50">The photo row below the story text.</p>

        <div className="mt-3 grid gap-4 sm:grid-cols-2">
          {data.gallery.map((photo) => (
            <div key={photo.id} className="rounded-xl border border-ink/10 p-3">
              <img src={photo.url} alt="" className="h-32 w-full rounded-lg object-cover" />
              <input
                defaultValue={photo.caption ?? ""}
                onBlur={(e) => saveCaption(photo.id, e.target.value)}
                placeholder="Caption / alt text"
                className="mt-2 w-full rounded-lg border border-ink/15 px-3 py-1.5 text-sm"
              />
              <button
                type="button"
                onClick={() => removePhoto(photo.id)}
                disabled={busy === photo.id}
                className="mt-2 text-sm text-ink/50 hover:text-tomato disabled:opacity-60"
              >
                Remove
              </button>
            </div>
          ))}
        </div>

        <div className="mt-4">
          <button
            type="button"
            onClick={() => addInputRef.current?.click()}
            disabled={busy === "add"}
            className="rounded-lg border border-dashed border-ink/25 px-4 py-2 text-sm text-ink/60 hover:border-ink/40 disabled:opacity-60"
          >
            {busy === "add" ? "Uploading…" : "+ Add photo"}
          </button>
          <input
            ref={addInputRef}
            type="file"
            accept="image/jpeg,image/png,image/webp"
            className="hidden"
            onChange={(e) => {
              const file = e.target.files?.[0];
              if (file) addPhoto(file);
              e.target.value = "";
            }}
          />
        </div>
      </section>
    </div>
  );
}
