"use client";

import { useRouter } from "next/navigation";
import { useState } from "react";
import Link from "next/link";

interface PhotoItem {
  id: number;
  photo: string;
  username: string;
  userId: number;
  uploadDate: string;
  type: string;
  status: string;
}

export function ModerationActions({
  photos,
  currentStatus,
}: {
  photos: PhotoItem[];
  currentStatus: string;
}) {
  const router = useRouter();
  const [selected, setSelected] = useState<Set<number>>(new Set());
  const [loading, setLoading] = useState(false);
  const [rejectReason, setRejectReason] = useState("");
  const [showRejectModal, setShowRejectModal] = useState(false);

  function toggleSelect(id: number) {
    setSelected((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  }

  function selectAll() {
    if (selected.size === photos.length) {
      setSelected(new Set());
    } else {
      setSelected(new Set(photos.map((p) => p.id)));
    }
  }

  async function handleApprove() {
    if (selected.size === 0) return;
    setLoading(true);
    try {
      const res = await fetch("/api/admin/moderation/approve", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ photo_ids: Array.from(selected) }),
      });
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        alert(data.error || "Failed to approve");
      } else {
        setSelected(new Set());
        router.refresh();
      }
    } catch {
      alert("Failed to approve");
    } finally {
      setLoading(false);
    }
  }

  async function handleReject() {
    if (selected.size === 0) return;
    setLoading(true);
    try {
      const res = await fetch("/api/admin/moderation/reject", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          photo_ids: Array.from(selected),
          reason: rejectReason,
        }),
      });
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        alert(data.error || "Failed to reject");
      } else {
        setSelected(new Set());
        setRejectReason("");
        setShowRejectModal(false);
        router.refresh();
      }
    } catch {
      alert("Failed to reject");
    } finally {
      setLoading(false);
    }
  }

  return (
    <>
      {/* Bulk actions bar */}
      {currentStatus === "pending" && (
        <div className="bg-surface rounded-lg p-4 flex items-center gap-4">
          <button
            onClick={selectAll}
            className="bg-surface-light hover:bg-surface text-text-muted px-3 py-1.5 rounded-lg transition-colors text-sm"
          >
            {selected.size === photos.length ? "Deselect All" : "Select All"}
          </button>
          <span className="text-text-muted text-sm">
            {selected.size} selected
          </span>
          <div className="ml-auto flex gap-2">
            <button
              disabled={selected.size === 0 || loading}
              onClick={handleApprove}
              className="bg-green-600 hover:bg-green-700 text-white px-4 py-1.5 rounded-lg transition-colors text-sm disabled:opacity-50"
            >
              {loading ? "..." : "Approve Selected"}
            </button>
            <button
              disabled={selected.size === 0 || loading}
              onClick={() => setShowRejectModal(true)}
              className="bg-red-600 hover:bg-red-700 text-white px-4 py-1.5 rounded-lg transition-colors text-sm disabled:opacity-50"
            >
              Reject Selected
            </button>
          </div>
        </div>
      )}

      {/* Photo Grid */}
      <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-4">
        {photos.map((photo) => (
          <div
            key={photo.id}
            onClick={() => currentStatus === "pending" && toggleSelect(photo.id)}
            className={`bg-surface rounded-lg overflow-hidden cursor-pointer transition-all ${
              selected.has(photo.id)
                ? "ring-2 ring-primary"
                : "hover:ring-1 hover:ring-surface-light"
            }`}
          >
            <div className="relative aspect-square">
              <img
                src={photo.photo}
                alt=""
                className="w-full h-full object-cover"
              />
              {selected.has(photo.id) && (
                <div className="absolute top-2 right-2 w-6 h-6 bg-primary rounded-full flex items-center justify-center">
                  <svg
                    className="w-4 h-4 text-white"
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth={2}
                      d="M5 13l4 4L19 7"
                    />
                  </svg>
                </div>
              )}
            </div>
            <div className="p-2">
              <Link
                href={`/admin/users/${photo.userId}`}
                onClick={(e) => e.stopPropagation()}
                className="text-sm font-medium hover:text-primary transition-colors truncate block"
              >
                {photo.username}
              </Link>
              <p className="text-text-muted text-xs">
                {new Date(photo.uploadDate).toLocaleDateString()}
              </p>
              <p className="text-text-muted text-xs capitalize">{photo.type}</p>
            </div>
          </div>
        ))}
      </div>

      {/* Reject Modal */}
      {showRejectModal && (
        <div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50">
          <div className="bg-surface rounded-lg p-6 w-full max-w-md">
            <h3 className="text-lg font-semibold mb-4">
              Reject {selected.size} Photo{selected.size > 1 ? "s" : ""}
            </h3>
            <label className="block text-text-muted text-sm mb-1">
              Reason
            </label>
            <textarea
              value={rejectReason}
              onChange={(e) => setRejectReason(e.target.value)}
              className="w-full bg-surface-light border border-surface-light rounded-lg px-4 py-2 text-text focus:outline-none focus:ring-1 focus:ring-primary mb-4"
              rows={3}
              placeholder="Enter rejection reason..."
            />
            <div className="flex justify-end gap-2">
              <button
                onClick={() => setShowRejectModal(false)}
                className="bg-surface-light hover:bg-surface text-text-muted px-4 py-2 rounded-lg transition-colors text-sm"
              >
                Cancel
              </button>
              <button
                disabled={loading}
                onClick={handleReject}
                className="bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded-lg transition-colors text-sm disabled:opacity-50"
              >
                {loading ? "..." : "Confirm Reject"}
              </button>
            </div>
          </div>
        </div>
      )}
    </>
  );
}
