"use client";

import { useState, useEffect } from "react";
import Link from "next/link";
import { useConfirm } from "@/components/shared/use-confirm";
import ManagePageSkeleton from "@/components/shared/manage-page-skeleton";
import { photoUrl } from "@/lib/media";

interface Gallery {
  id: number;
  name: string;
  cover: string | null;
  credits: number;
  private: boolean;
  _count: { photos: number };
}

export default function ManageGalleriesPage() {
  const [galleries, setGalleries] = useState<Gallery[]>([]);
  const [loading, setLoading] = useState(true);
  const [creating, setCreating] = useState(false);
  const [newName, setNewName] = useState("");
  const [showCreate, setShowCreate] = useState(false);
  const [message, setMessage] = useState<{ type: "success" | "error"; text: string } | null>(null);
  const { confirm: askConfirm, dialog: confirmDialog } = useConfirm();

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

  function fetchGalleries() {
    fetch("/api/profile/galleries")
      .then((r) => r.json())
      .then((data) => setGalleries(data.galleries || []))
      .finally(() => setLoading(false));
  }

  async function handleCreate(e: React.FormEvent) {
    e.preventDefault();
    if (!newName.trim()) return;
    setCreating(true);
    setMessage(null);
    try {
      const res = await fetch("/api/profile/galleries", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name: newName }),
      });
      if (!res.ok) throw new Error("Failed");
      setNewName("");
      setShowCreate(false);
      setMessage({ type: "success", text: "Gallery created successfully." });
      fetchGalleries();
    } catch {
      setMessage({ type: "error", text: "Failed to create gallery." });
    } finally {
      setCreating(false);
    }
  }

  async function handleDelete(id: number) {
    if (!(await askConfirm({ title: "Delete gallery", message: "Delete this gallery? All photos in it will be unlinked." }))) return;
    try {
      const res = await fetch(`/api/profile/galleries/${id}`, { method: "DELETE" });
      if (!res.ok) throw new Error("Failed");
      setGalleries((prev) => prev.filter((g) => g.id !== id));
      setMessage({ type: "success", text: "Gallery deleted." });
    } catch {
      setMessage({ type: "error", text: "Failed to delete gallery." });
    }
  }

  if (loading) return <ManagePageSkeleton />;

  return (
    <div className="max-w-4xl mx-auto">
      {confirmDialog}
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-3xl font-bold text-text">My Galleries</h1>
        <button
          onClick={() => setShowCreate(true)}
          className="bg-primary hover:bg-primary-dark text-white px-5 py-2.5 rounded-lg font-semibold transition-colors"
        >
          Create Gallery
        </button>
      </div>

      {message && (
        <div className={`p-3 rounded-lg text-sm mb-4 ${message.type === "success" ? "bg-green-900/30 text-green-400" : "bg-red-900/30 text-red-400"}`}>
          {message.text}
        </div>
      )}

      {showCreate && (
        <form onSubmit={handleCreate} className="bg-surface rounded-lg p-4 mb-6 flex gap-3">
          <input
            type="text"
            value={newName}
            onChange={(e) => setNewName(e.target.value)}
            placeholder="Gallery name"
            className="flex-1 bg-background border border-surface-light rounded-lg px-4 py-2.5 text-text focus:outline-none focus:ring-2 focus:ring-primary"
          />
          <button type="submit" disabled={creating} className="bg-primary hover:bg-primary-dark text-white px-5 py-2.5 rounded-lg font-semibold transition-colors disabled:opacity-50">
            {creating ? "Creating..." : "Create"}
          </button>
          <button type="button" onClick={() => setShowCreate(false)} className="text-text-muted hover:text-text px-3">
            Cancel
          </button>
        </form>
      )}

      {galleries.length === 0 ? (
        <div className="bg-surface rounded-lg p-12 text-center">
          <p className="text-text-muted mb-4">You have no galleries yet.</p>
          <button onClick={() => setShowCreate(true)} className="text-primary hover:text-primary-dark font-semibold">
            Create your first gallery
          </button>
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {galleries.map((gallery) => (
            <div key={gallery.id} className="bg-surface rounded-lg overflow-hidden">
              <div className="h-40 bg-surface-light flex items-center justify-center">
                {gallery.cover ? (
                  <img src={photoUrl(gallery.cover)} alt={gallery.name} className="w-full h-full object-cover" />
                ) : (
                  <span className="text-text-muted text-sm">{gallery._count.photos} photos</span>
                )}
              </div>
              <div className="p-4">
                <h3 className="font-semibold text-text truncate">{gallery.name}</h3>
                <p className="text-text-muted text-sm mt-1">
                  {gallery._count.photos} photos - {gallery.credits > 0 ? "Premium" : "Free"}
                </p>
                <div className="flex gap-2 mt-3">
                  <Link
                    href={`/gallery/show/${gallery.id}`}
                    className="text-primary text-sm hover:text-primary-dark"
                  >
                    View
                  </Link>
                  <Link
                    href={`/gallery/edit/${gallery.id}`}
                    className="text-text-muted text-sm hover:text-text"
                  >
                    Edit
                  </Link>
                  <button
                    onClick={() => handleDelete(gallery.id)}
                    className="text-red-400 text-sm hover:text-red-300"
                  >
                    Delete
                  </button>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
