"use client";
import { useEffect, useState } from "react";
import type { ManagedPhoto } from "@/lib/gallery-store";

export function GalleryManager(){
  const [photos,setPhotos]=useState<ManagedPhoto[]>([]);const [loading,setLoading]=useState(true);const [error,setError]=useState("");
  async function refresh(){try{const r=await fetch("/api/admin/gallery",{cache:"no-store"});const data=await r.json();if(!r.ok)throw new Error(data.error);setPhotos(data.photos);setError("");}catch(e){setError((e as Error).message);}finally{setLoading(false);}}
  useEffect(()=>{void refresh();},[]);
  return <section className="card mt-8 p-6 sm:p-8" id="gallery-manager"><div className="flex flex-wrap items-center justify-between gap-3"><h2 className="font-serif text-3xl">Your gallery</h2><a href="/gallery" target="_blank" rel="noreferrer" className="btn-light">View gallery</a></div><p className="mt-3 text-ink/60">Upload your work, replace photos, and choose which pictures visitors see. Lower display numbers appear first.</p>{error&&<p role="alert" className="mt-4 text-red-700">{error}</p>}<div className="mt-6 rounded-2xl bg-cream p-5"><h3 className="mb-4 font-semibold">Upload a new photo</h3><PhotoForm onSaved={refresh}/></div>{loading?<p className="mt-6">Loading your photos…</p>:<div className="mt-7 grid gap-6 md:grid-cols-2 xl:grid-cols-3">{photos.map(photo=><article key={photo.id} className="overflow-hidden rounded-2xl border border-ink/10"><img src={photo.src} alt={photo.alt} className="aspect-[4/3] w-full object-cover"/><div className="p-4"><span className="text-sm text-rose">{photo.published?"Visible in gallery":"Hidden"}</span><PhotoForm photo={photo} onSaved={refresh}/></div></article>)}</div>}</section>;
}
function PhotoForm({photo,onSaved}:{photo?:ManagedPhoto;onSaved:()=>Promise<void>}){
  const [busy,setBusy]=useState(false);const [message,setMessage]=useState("");const [failed,setFailed]=useState(false);const [preview,setPreview]=useState("");
  useEffect(()=>()=>{if(preview)URL.revokeObjectURL(preview);},[preview]);
  async function send(form:FormData,element?:HTMLFormElement){setBusy(true);setMessage("");setFailed(false);try{const r=await fetch("/api/admin/gallery",{method:"POST",body:form});const data=await r.json();if(!r.ok)throw new Error(data.error);if(!photo)element?.reset();setPreview("");await onSaved();setMessage(photo?"Changes saved.":"Photo uploaded.");}catch(e){setFailed(true);setMessage((e as Error).message);}finally{setBusy(false);}}
  return <form className="mt-3 space-y-4" onSubmit={e=>{e.preventDefault();void send(new FormData(e.currentTarget),e.currentTarget);}}><fieldset disabled={busy} className="space-y-4"><input type="hidden" name="id" value={photo?.id||""}/><label className="block text-sm font-medium">{photo?"Replace photo (optional)":"Choose a photo"}<input className="mt-2 block w-full text-sm" name="image" type="file" accept="image/jpeg,image/png,image/webp,image/avif" required={!photo} onChange={e=>{const f=e.target.files?.[0];setPreview(f?URL.createObjectURL(f):"");}}/></label><p className="text-sm text-ink/50">JPG, PNG, WebP or AVIF · up to 8 MB</p>{preview&&<img src={preview} className="h-40 rounded-xl object-cover" alt="Selected photo preview"/>}<label className="block text-sm font-medium">Description<input name="alt" required maxLength={250} defaultValue={photo?.alt} className="field mt-1" placeholder="Pink almond nails with floral art"/></label><label className="block text-sm font-medium">Category<input name="category" required maxLength={60} defaultValue={photo?.category||"Recent work"} className="field mt-1"/></label><label className="block text-sm font-medium">Display order<input type="number" name="order" min={0} max={9999} required defaultValue={photo?.order||0} className="field mt-1"/></label><label className="flex items-center gap-2 text-sm"><input type="checkbox" name="published" defaultChecked={photo?.published??true} className="accent-rose"/>Show on gallery page</label><div className="flex flex-wrap gap-2"><button className="btn-dark" type="submit">{busy?"Saving…":photo?"Save changes":"Upload photo"}</button>{photo&&<button className="btn-light text-red-700" type="button" onClick={()=>{if(!confirm("Remove this photo from your gallery?"))return;const f=new FormData();f.set("id",photo.id);f.set("action","remove");void send(f);}}>Remove</button>}</div></fieldset>{message&&<p role="status" className={`text-sm ${failed?"text-red-700":"text-rose"}`}>{message}</p>}</form>;
}
