"use client";

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

interface GalleryImage {
  id: string;
  image: string;
  caption: string | null;
  sort_order: number;
  status: boolean;
  // client-only: staged replacement, not yet saved
  pendingFile?: File | null;
  pendingPreview?: string | null;
  dirty?: boolean;
}

export default function GalleryPage() {
  const [images, setImages] = useState<GalleryImage[]>([]);
  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");
      const json = await res.json();

      if (json.success) {
        // freshly fetched rows always start clean (not dirty)
        setImages(json.data.map((img: GalleryImage) => ({ ...img, dirty: false })));
      } else {
        setError(json.message || "Failed to load gallery");
      }
    } catch {
      setError("Failed to load gallery");
    } finally {
      setLoading(false);
    }
  };

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

  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", {
        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);
  };

  // Stage a replacement image locally — only uploaded when Save is clicked
  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", {
        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?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>
            <h2 className="admin-page-title">History Image Gallery</h2>
            <p className="admin-page-subtitle">
              Upload and manage photos in the history gallery
            </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 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 || "Gallery 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 me-1" />
                      Saving...
                    </>
                  ) : (
                    <>
                      <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>
  );
}