"use client";

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

interface AlbumImage {
  id: string;
  image: string;
  caption: string | null;
  sort_order: number;
  status: boolean;
  pendingFile?: File | null;
  pendingPreview?: string | null;
  dirty?: boolean;
}

interface Album {
  id: string;
  title: string;
  slug: string;
}

export default function GalleryAlbumImagesPage() {
  const params = useParams();
  const albumId = params?.albumId as string;

  const [album, setAlbum] = useState<Album | null>(null);
  const [images, setImages] = useState<AlbumImage[]>([]);
  const [loading, setLoading] = useState(true);
  const [uploading, setUploading] = useState(false);
  const [savingId, setSavingId] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  const fileInputRef = useRef<HTMLInputElement>(null);

  const fetchImages = async () => {
    try {
      setLoading(true);
      const res = await fetch(`/api/admin/gallery-albums/${albumId}/images`);
      const json = await res.json();

      if (json.success) {
        setAlbum(json.album);
        setImages(json.data.map((img: AlbumImage) => ({ ...img, dirty: false })));
      } else {
        setError(json.message || "Failed to load images");
      }
    } catch {
      setError("Failed to load images");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (albumId) fetchImages();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [albumId]);

  const handleFilesSelected = async (
    e: React.ChangeEvent<HTMLInputElement>
  ) => {
    const files = e.target.files;
    if (!files || files.length === 0) return;

    setError(null);
    setUploading(true);

    try {
      const formData = new FormData();
      Array.from(files).forEach((file) => formData.append("images", file));

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

      const json = await res.json();

      if (!json.success) {
        setError(json.message || "Upload failed");
      } else {
        await fetchImages();
      }
    } catch {
      setError("Upload failed");
    } finally {
      setUploading(false);
      if (fileInputRef.current) fileInputRef.current.value = "";
    }
  };

  const handleCaptionChange = (index: number, value: string) => {
    const updated = [...images];
    updated[index] = { ...updated[index], caption: value, dirty: true };
    setImages(updated);
  };

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

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

    const updated = [...images];
    updated[index] = {
      ...updated[index],
      pendingFile: file,
      pendingPreview: URL.createObjectURL(file),
      dirty: true,
    };
    setImages(updated);
  };

  const handleSaveRow = async (index: number) => {
    const item = images[index];
    setSavingId(item.id);
    setError(null);

    try {
      const formData = new FormData();
      formData.append("id", item.id);
      formData.append("caption", item.caption || "");
      formData.append("status", String(item.status));
      if (item.pendingFile) formData.append("image", item.pendingFile);

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

      const json = await res.json();

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

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

  const handleDelete = async (id: string) => {
    if (!confirm("Delete this image? This cannot be undone.")) return;

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

      if (json.success) {
        setImages(images.filter((img) => img.id !== id));
      } else {
        setError(json.message || "Failed to delete");
      }
    } catch {
      setError("Failed to delete");
    }
  };

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

  return (
    <div className="admin-page-wrapper">
      <div className="admin-page-header mb-4">
        <div className="d-flex justify-content-between align-items-center">
          <div>
            <Link
              href="/admin/gallery-albums"
              className="d-inline-block back-btn mb-1"
            >
              &laquo; Back to Albums
            </Link>
            <h2 className="admin-page-title">
              {album?.title || "Album"} — Images
            </h2>
            {/* <p className="admin-page-subtitle">/{album?.slug}</p> */}
          </div>

          <div>
            <input
              ref={fileInputRef}
              type="file"
              accept="image/*"
              multiple
              hidden
              onChange={handleFilesSelected}
            />
            <button
              className="admin-theme-btn"
              disabled={uploading}
              onClick={() => fileInputRef.current?.click()}
            >
              {uploading ? (
                <>
                  <span className="spinner-border spinner-border-sm me-2" />
                  Uploading...
                </>
              ) : (
                <>
                  <i className="bi bi-cloud-upload me-2" />
                  Upload Images
                </>
              )}
            </button>
          </div>
        </div>
      </div>

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

      <div className="row g-4">
        {images.length === 0 && (
          <div className="col-12 text-center py-5 text-muted">
            No images in this album yet. Click "Upload Images" to add some.
          </div>
        )}

        {images.map((img, index) => (
          <div className="col-lg-3 col-md-4 col-sm-6 col-12" key={img.id}>
            <div className="card-theme p-3 h-100 d-flex flex-column">
              <div
                className="position-relative mb-2"
                style={{ aspectRatio: "4/3" }}
              >
                <Image
                  src={img.pendingPreview || img.image}
                  alt={img.caption || "Album image"}
                  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" />
                Replace
                <input
                  type="file"
                  accept="image/*"
                  hidden
                  onChange={(e) => handleStageReplaceImage(index, e)}
                />
              </label>

              {/* <input
                type="text"
                className="form-control form-control-sm mb-2"
                placeholder="Caption (optional)"
                value={img.caption || ""}
                onChange={(e) => handleCaptionChange(index, e.target.value)}
              /> */}

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

              <div className="mt-auto d-flex gap-2">
                <button
                  className="btn btn-sm admin-theme-btn flex-fill"
                  disabled={!img.dirty || savingId === img.id}
                  onClick={() => handleSaveRow(index)}
                >
                  {savingId === img.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={() => handleDelete(img.id)}
                >
                  <i className="bi bi-trash" />
                </button>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}