"use client"; // Components/Car/CarImageGallery.tsx // Full-screen gallery modal for viewing, uploading and deleting car images. import { useCallback, useEffect, useRef, useState } from "react"; import { Spinner } from "../UI"; import { carService } from "../../services/car.service"; import { getStoredToken } from "../../lib/auth"; import type { Car, CarImage, ImageStage } from "../../types/car"; // ── Stage badge config ──────────────────────────────────────────────────────── const STAGE_MAP: Record = { BEFORE: { label: "قبل", color: "#854D0E", bg: "#FFFBEB" }, AFTER: { label: "بعد", color: "#166534", bg: "#DCFCE7" }, GENERAL: { label: "عام", color: "#1E40AF", bg: "#EFF6FF" }, }; // ── Props ───────────────────────────────────────────────────────────────────── interface CarImageGalleryProps { car: Car; onClose: () => void; } // ── Component ───────────────────────────────────────────────────────────────── export function CarImageGallery({ car, onClose }: CarImageGalleryProps) { const [images, setImages] = useState([]); const [loading, setLoading] = useState(true); const [uploading, setUploading] = useState(false); const [deleting, setDeleting] = useState(null); const [error, setError] = useState(null); const [lightbox, setLightbox] = useState(null); const [stage, setStage] = useState("GENERAL"); const [sortBy, setSortBy] = useState<"asc" | "desc">("desc"); const fileRef = useRef(null); // ── Fetch images ──────────────────────────────────────────────────────────── const fetchImages = useCallback(async () => { setLoading(true); setError(null); try { const token = getStoredToken(); const res = await carService.getImages(car.id, token, { sortBy }); const raw = (res as unknown as { data: CarImage[] }).data ?? []; setImages(raw); } catch (err: unknown) { setError(err instanceof Error ? err.message : "تعذّر تحميل الصور"); } finally { setLoading(false); } }, [car.id, sortBy]); useEffect(() => { fetchImages(); }, [fetchImages]); // Close on Escape useEffect(() => { const h = (e: KeyboardEvent) => { if (e.key === "Escape") { if (lightbox) setLightbox(null); else onClose(); } }; window.addEventListener("keydown", h); return () => window.removeEventListener("keydown", h); }, [lightbox, onClose]); // ── Upload handler ────────────────────────────────────────────────────────── const handleUpload = async (e: React.ChangeEvent) => { const files = Array.from(e.target.files ?? []); if (!files.length) return; setUploading(true); setError(null); try { const token = getStoredToken(); await carService.uploadImages(car.id, files, stage, token); await fetchImages(); } catch (err: unknown) { setError(err instanceof Error ? err.message : "فشل رفع الصور"); } finally { setUploading(false); if (fileRef.current) fileRef.current.value = ""; } }; // ── Delete handler ────────────────────────────────────────────────────────── const handleDelete = async (imageId: string) => { setDeleting(imageId); setError(null); try { const token = getStoredToken(); await carService.deleteImage(imageId, token); setImages(prev => prev.filter(img => img.id !== imageId)); if (lightbox?.id === imageId) setLightbox(null); } catch (err: unknown) { setError(err instanceof Error ? err.message : "فشل حذف الصورة"); } finally { setDeleting(null); } }; // ── Helpers ───────────────────────────────────────────────────────────────── /** Build full image URL — uses the proxy so no CORS issues */ const imgSrc = (img: CarImage) => img.url ?? `/api/proxy/car-photos/${img.image}`; // ── Render ─────────────────────────────────────────────────────────────────── return (
{ if (e.target === e.currentTarget) onClose(); }} style={{ position: "fixed", inset: 0, zIndex: 70, background: "rgba(15,23,42,0.7)", backdropFilter: "blur(6px)", display: "flex", flexDirection: "column", }} > {/* ── Header ── */}

معرض الصور

{car.manufacturer} {car.model} — {car.plateLetters} {car.plateNumber}

{/* Sort */} {/* Stage selector for upload */} {/* Upload button */} {/* Close */}
{/* ── Error ── */} {error && (
⚠ {error}
)} {/* ── Gallery Grid ── */}
{loading ? (
جارٍ تحميل الصور…
) : images.length === 0 ? (
📸

لا توجد صور بعد

اضغط على "رفع صور" لإضافة أولى الصور لهذه المركبة.

) : (
{images.map(img => { const stageInfo = STAGE_MAP[img.stage ?? "GENERAL"] ?? STAGE_MAP.GENERAL; const isDeleting = deleting === img.id; return (
{/* Image */}
setLightbox(img)} > {/* eslint-disable-next-line @next/next/no-img-element */} {`صورة { (e.target as HTMLImageElement).src = "/file.svg"; }} /> {/* Stage badge */} {stageInfo.label}
{/* Footer */}
{new Date(img.createdAt).toLocaleDateString("ar-SA", { month: "short", day: "numeric" })}
); })}
)}
{/* ── Lightbox ── */} {lightbox && (
setLightbox(null)} style={{ position: "fixed", inset: 0, zIndex: 80, background: "rgba(0,0,0,0.9)", display: "flex", alignItems: "center", justifyContent: "center", padding: "1rem", }} > {/* eslint-disable-next-line @next/next/no-img-element */} عرض مكبَّر e.stopPropagation()} onError={e => { (e.target as HTMLImageElement).src = "/file.svg"; }} />
)}
); }