"use client";

import { useEffect, useRef, useState } from "react";
import Image from "next/image";
import Link from "next/link";
import CustomLoader from "@/components/common/CustomLoader";

interface Album {
  id: string;
  title: string;
  slug: string;
  cover: string | null;
  status: boolean;
  _count?: { images: number };
  pendingCover?: File | null;
  pendingCoverPreview?: string | null;
  dirty?: boolean;
}

export default function GalleryAlbumsPage() {
  const [albums, setAlbums] = useState<Album[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [savingId, setSavingId] = useState<string | null>(null);

  // "Add new album" form
  const [newTitle, setNewTitle] = useState("");
  const [newCover, setNewCover] = useState<File | null>(null);
  const [creating, setCreating] = useState(false);
  const newCoverInputRef = useRef<HTMLInputElement>(null);

  const fetchAlbums = async () => {
    try {
      setLoading(true);
      const res = await fetch("/api/admin/gallery-albums");
      const json = await res.json();

      if (json.success) {
        setAlbums(json.data.map((a: Album) => ({ ...a, dirty: false })));
      } else {
        setError(json.message || "Failed to load albums");
      }
    } catch {
      setError("Failed to load albums");
    } finally {
      setLoading(false);
    }
  };

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

  const handleCreateAlbum = async () => {
    if (!newTitle.trim()) {
      setError("Title is required");
      return;
    }

    if (!newCover) {
      setError("Cover image is required");
      return;
    }

    setCreating(true);
    setError(null);

    try {
      const formData = new FormData();
      formData.append("title", newTitle.trim());
      formData.append("status", "true");
      if (newCover) formData.append("cover", newCover);

      const res = await fetch("/api/admin/gallery-albums", {
        method: "POST",
        body: formData,
      });

      const json = await res.json();

      if (!json.success) {
        setError(json.message || "Failed to create album");
        return;
      }

      setNewTitle("");
      setNewCover(null);
      if (newCoverInputRef.current) newCoverInputRef.current.value = "";
      await fetchAlbums();
    } catch {
      setError("Failed to create album");
    } finally {
      setCreating(false);
    }
  };

  const handleTitleChange = (index: number, value: string) => {
    const updated = [...albums];
    updated[index] = { ...updated[index], title: value, dirty: true };
    setAlbums(updated);
  };

  const handleStatusToggle = (index: number, value: boolean) => {
    const updated = [...albums];
    updated[index] = { ...updated[index], status: value, dirty: true };
    setAlbums(updated);
  };

  const handleStageCover = (
    index: number,
    e: React.ChangeEvent<HTMLInputElement>
  ) => {
    const file = e.target.files?.[0];
    if (!file) return;

    const updated = [...albums];
    updated[index] = {
      ...updated[index],
      pendingCover: file,
      pendingCoverPreview: URL.createObjectURL(file),
      dirty: true,
    };
    setAlbums(updated);
  };

  const handleSaveAlbum = async (index: number) => {
    const album = albums[index];
    setSavingId(album.id);
    setError(null);

    try {
      const formData = new FormData();
      formData.append("id", album.id);
      formData.append("title", album.title);
      formData.append("status", String(album.status));
      if (album.pendingCover) formData.append("cover", album.pendingCover);

      const res = await fetch("/api/admin/gallery-albums", {
        method: "PUT",
        body: formData,
      });

      const json = await res.json();

      if (!json.success) {
        setError(json.message || "Failed to save album");
        return;
      }

      await fetchAlbums();
    } catch {
      setError("Failed to save album");
    } finally {
      setSavingId(null);
    }
  };

  const handleDeleteAlbum = async (id: string) => {
    if (
      !confirm(
        "Delete this album? All images inside it will also be deleted. This cannot be undone."
      )
    )
      return;

    try {
      const res = await fetch(`/api/admin/gallery-albums?id=${id}`, {
        method: "DELETE",
      });
      const json = await res.json();

      if (json.success) {
        setAlbums(albums.filter((a) => a.id !== id));
      } else {
        setError(json.message || "Failed to delete album");
      }
    } catch {
      setError("Failed to delete album");
    }
  };

  if (loading) {
    return <CustomLoader />;
  }

  return (
    <div className="admin-page-wrapper">
      <div className="admin-page-header mb-4">
        <div>
          <h2 className="admin-page-title">Key Performances — Albums</h2>
          <p className="admin-page-subtitle">
            Manage gallery albums. The URL slug is generated automatically
            from the title.
          </p>
        </div>
      </div>

      {error && <div className="alert alert-danger">{error}</div>}

      {/* Add new album */}
      <div className="card-theme p-4 mb-4">
        <h5 className="fw-semibold mb-3">
          <i className="bi bi-plus-circle me-2 text-primary" />
          Add New Album
        </h5>
        <div className="row g-3 align-items-end">
          <div className="col-md-6">
            <label className="form-label">Album Title <span className="text-danger">*</span></label>
            <input
              type="text"
              className="form-control"
              placeholder="e.g. 2020 Annual Recital"
              value={newTitle}
              onChange={(e) => setNewTitle(e.target.value)}
            />
          </div>
          <div className="col-md-4">
            <label className="form-label">Cover Image <span className="text-danger">*</span></label>
            <input
              ref={newCoverInputRef}
              type="file"
              accept="image/*"
              className="form-control"
              onChange={(e) => setNewCover(e.target.files?.[0] || null)}
            />
          </div>
          <div className="col-md-2">
            <button
              className="admin-theme-btn w-100"
              disabled={creating}
              onClick={handleCreateAlbum}
            >
              {creating ? (
                <span className="spinner-border spinner-border-sm" />
              ) : (
                "Create"
              )}
            </button>
          </div>
        </div>
      </div>

      {/* Existing albums */}
      <div className="row g-4">
        {albums.length === 0 && (
          <div className="col-12 text-center py-5 text-muted">
            No albums yet. Create one above.
          </div>
        )}

        {albums.map((album, index) => (
          <div className="col-lg-3 col-md-4 col-sm-6 col-12" key={album.id}>
            <div className="card-theme p-3 h-100 d-flex flex-column">
              <div
                className="position-relative mb-2"
                style={{ aspectRatio: "4/3", background: "#f0f0f0" }}
              >
                {(album.pendingCoverPreview || album.cover) && (
                  <Image
                    src={album.pendingCoverPreview || (album.cover as string)}
                    alt={album.title}
                    fill
                    style={{ objectFit: "cover", borderRadius: "6px" }}
                  />
                )}
              </div>

              <label className="btn btn-sm btn-outline-secondary mb-2">
                <i className="bi bi-arrow-repeat me-1" />
                Change Cover
                <input
                  type="file"
                  accept="image/*"
                  hidden
                  onChange={(e) => handleStageCover(index, e)}
                />
              </label>

              <input
                type="text"
                className="form-control form-control-sm mb-2"
                value={album.title}
                onChange={(e) => handleTitleChange(index, e.target.value)}
              />

              {/* <p className="small text-muted mb-2">
                {album.slug} &middot; {album._count?.images ?? 0} image
                {album._count?.images === 1 ? "" : "s"}
              </p> */}
               <p className="small text-muted mb-2">
                {album._count?.images ?? 0} image
                {album._count?.images === 1 ? "" : "s"}
              </p>


              <div className="form-check form-switch mb-2">
                <input
                  className="form-check-input"
                  type="checkbox"
                  checked={album.status}
                  onChange={(e) =>
                    handleStatusToggle(index, e.target.checked)
                  }
                />
                <label className="form-check-label small">
                  {album.status ? "Active" : "Inactive"}
                </label>
              </div>

              <Link
                href={`/admin/gallery-albums/${album.id}`}
                className="default-btn mb-2"
              >
                <i className="bi bi-images me-1" />
                Manage Images
              </Link>

              <div className="mt-auto d-flex gap-2">
                <button
                  className="btn btn-sm admin-theme-btn flex-fill"
                  disabled={!album.dirty || savingId === album.id}
                  onClick={() => handleSaveAlbum(index)}
                >
                  {savingId === album.id ? (
                    <span className="spinner-border spinner-border-sm" />
                  ) : (
                    <>
                      <i className="bi bi-check-lg me-1" />
                      Save
                    </>
                  )}
                </button>
                <button
                  className="btn btn-sm btn-outline-danger"
                  onClick={() => handleDeleteAlbum(album.id)}
                >
                  <i className="bi bi-trash" />
                </button>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}