"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { useConfirm } from "@/components/shared/use-confirm";
import { photoUrl } from "@/lib/media";

interface Photo {
  id: number;
  photo: string | null;
}

interface Gallery {
  id: number;
  name: string;
  description: string | null;
  credits: number;
  photos: Photo[];
}

export default function EditGalleryForm({ gallery, idAw }: { gallery: Gallery; idAw?: string | null }) {
  const router = useRouter();
  const [saving, setSaving] = useState(false);
  const [name, setName] = useState(gallery.name);
  const [description, setDescription] = useState(gallery.description || "");
  const [credits, setCredits] = useState(gallery.credits);
  const [photos, setPhotos] = useState(gallery.photos);
  const { confirm: askConfirm, dialog: confirmDialog } = useConfirm();

  async function handleDelete(photoId: number) {
    if (!(await askConfirm({ title: "Delete photo", message: "Delete this photo?" }))) return;
    try {
      await fetch(`/api/gallery/${gallery.id}/photos/${photoId}`, { method: "DELETE" });
      setPhotos((prev) => prev.filter((p) => p.id !== photoId));
    } catch {
      alert("Failed to delete photo.");
    }
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setSaving(true);
    try {
      const res = await fetch(`/api/gallery/${gallery.id}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name, description, credits }),
      });
      if (!res.ok) throw new Error("Failed");
      router.push(`/gallery/show/${gallery.id}`);
    } catch {
      alert("Failed to update gallery.");
    } finally {
      setSaving(false);
    }
  }

  async function handleDeleteGallery() {
    if (!(await askConfirm({ title: "Delete gallery", message: "Delete this entire gallery? This cannot be undone." }))) return;
    try {
      await fetch(`/api/gallery/${gallery.id}`, { method: "DELETE" });
      router.push("/manage/galleries");
    } catch {
      alert("Failed to delete gallery.");
    }
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-6">
      {confirmDialog}
      <div className="bg-surface rounded-lg p-6 space-y-4">
        <div>
          <label className="block text-sm font-medium text-text mb-1">Name</label>
          <input type="text" required value={name} onChange={(e) => setName(e.target.value)} className="w-full bg-background border border-surface-light rounded-lg px-4 py-2.5 text-text focus:outline-none focus:ring-2 focus:ring-primary" />
        </div>
        <div>
          <label className="block text-sm font-medium text-text mb-1">Description</label>
          <textarea rows={3} value={description} onChange={(e) => setDescription(e.target.value)} className="w-full bg-background border border-surface-light rounded-lg px-4 py-2.5 text-text focus:outline-none focus:ring-2 focus:ring-primary" />
        </div>
        <div>
          <label className="block text-sm font-medium text-text mb-1">Credits (0 = free)</label>
          <input type="number" min={0} value={credits} onChange={(e) => setCredits(Number(e.target.value))} className="w-full bg-background border border-surface-light rounded-lg px-4 py-2.5 text-text focus:outline-none focus:ring-2 focus:ring-primary" />
        </div>
      </div>

      {photos.length > 0 && (
        <div className="bg-surface rounded-lg p-6">
          <h2 className="font-semibold text-text mb-3">Photos</h2>
          <div className="grid grid-cols-3 gap-3">
            {photos.map((photo) => (
              <div key={photo.id} className="relative group">
                <img src={photoUrl(photo.photo, idAw)} alt="" className="w-full h-28 object-cover rounded" />
                <button type="button" onClick={() => handleDelete(photo.id)} className="absolute top-1 right-1 bg-red-600 text-white rounded-full w-6 h-6 text-xs opacity-0 group-hover:opacity-100 transition-opacity">X</button>
              </div>
            ))}
          </div>
        </div>
      )}

      <div className="flex items-center justify-between">
        <button type="button" onClick={handleDeleteGallery} className="text-red-400 hover:text-red-300 text-sm">
          Delete Gallery
        </button>
        <button type="submit" disabled={saving} className="bg-primary hover:bg-primary-dark text-white px-6 py-2.5 rounded-lg font-semibold transition-colors disabled:opacity-50">
          {saving ? "Saving..." : "Save Changes"}
        </button>
      </div>
    </form>
  );
}
