finsh user,car,driver pages also add validator layer to app build trip page

This commit is contained in:
m7amedez5511
2026-06-18 16:51:31 +03:00
parent a23d21f222
commit c1b77f89cd
45 changed files with 4128 additions and 1690 deletions

View File

@@ -5,40 +5,12 @@
import { useEffect, useState } from "react";
import { Spinner } from "../UI";
import { CarImageGallery } from "./CarImageGallery";
import { carService } from "../../services/car.service";
import { getStoredToken } from "../../lib/auth";
import type { Car, CarStatus, InsuranceStatus } from "../../types/car";
// ── Status config ─────────────────────────────────────────────────────────────
const STATUS_MAP: Record<CarStatus, { label: string; color: string; bg: string; border: string }> = {
Active: { label: "نشط", color: "#166534", bg: "#DCFCE7", border: "#BBF7D0" },
InMaintenance: { label: "صيانة", color: "#854D0E", bg: "#FFFBEB", border: "#FDE68A" },
InTrip: { label: "في رحلة", color: "#1E40AF", bg: "#EFF6FF", border: "#BFDBFE" },
Inactive: { label: "غير نشط", color: "#64748B", bg: "#F1F5F9", border: "#E2E8F0" },
};
const INS_MAP: Record<InsuranceStatus, { label: string; color: string }> = {
Valid: { label: "سارٍ", color: "#16A34A" },
Expired: { label: "منتهي", color: "#DC2626" },
NotInsured: { label: "غير مؤمَّن", color: "#D97706" },
};
// ── Helper: format date ───────────────────────────────────────────────────────
function fmtDate(iso?: string | null): string {
if (!iso) return "—";
return new Date(iso).toLocaleDateString("ar-SA", {
year: "numeric", month: "long", day: "numeric",
});
}
/** Returns true if the date is within 90 days in the future (or already past) */
function isExpiringSoon(iso?: string | null): boolean {
if (!iso) return false;
const diff = new Date(iso).getTime() - Date.now();
return diff <= 90 * 86_400_000;
}
import { useCarDetail } from "../../hooks/useCars";
import { STATUS_MAP, INS_MAP, fmtDate, isExpiringSoon } from "../../types/car";
import type { Car, InsuranceStatus } from "../../types/car";
// ── Props ─────────────────────────────────────────────────────────────────────
interface CarDetailPanelProps {
carId: string;
onClose: () => void;
@@ -47,7 +19,10 @@ interface CarDetailPanelProps {
}
// ── Row component ─────────────────────────────────────────────────────────────
function DetailRow({ label, value, mono = false, warn = false }: { label: string; value: string; mono?: boolean; warn?: boolean }) {
function DetailRow({ label, value, mono = false, warn = false }: {
label: string; value: string; mono?: boolean; warn?: boolean;
}) {
return (
<div style={{
display: "flex", justifyContent: "space-between", alignItems: "baseline",
@@ -68,22 +43,10 @@ function DetailRow({ label, value, mono = false, warn = false }: { label: string
}
// ── Component ─────────────────────────────────────────────────────────────────
export function CarDetailPanel({ carId, onClose, onEdit, onDelete }: CarDetailPanelProps) {
const [car, setCar] = useState<Car | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [gallery, setGallery] = useState(false);
useEffect(() => {
const token = getStoredToken();
setLoading(true);
setError(null);
carService
.getById(carId, token)
.then(res => setCar((res as unknown as { data: Car }).data))
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
}, [carId]);
export function CarDetailPanel({ carId, onClose, onEdit, onDelete }: CarDetailPanelProps) {
const { car, loading, error } = useCarDetail(carId);
const [gallery, setGallery] = useState(false);
useEffect(() => {
const h = (e: KeyboardEvent) => { if (e.key === "Escape" && !gallery) onClose(); };
@@ -91,7 +54,6 @@ export function CarDetailPanel({ carId, onClose, onEdit, onDelete }: CarDetailPa
return () => window.removeEventListener("keydown", h);
}, [gallery, onClose]);
// ── Render ───────────────────────────────────────────────────────────────────
return (
<>
{/* Backdrop */}
@@ -169,7 +131,7 @@ export function CarDetailPanel({ carId, onClose, onEdit, onDelete }: CarDetailPa
);
})()}
{car.insuranceStatus && (() => {
const ins = INS_MAP[car.insuranceStatus!];
const ins = INS_MAP[car.insuranceStatus as InsuranceStatus];
return (
<span style={{ borderRadius: "var(--radius-full)", border: `1px solid ${ins.color}33`, background: `${ins.color}11`, padding: "0.3rem 0.875rem", fontSize: 12, fontWeight: 700, color: ins.color }}>
تأمين: {ins.label}
@@ -197,31 +159,31 @@ export function CarDetailPanel({ carId, onClose, onEdit, onDelete }: CarDetailPa
<p style={{ fontSize: 11, letterSpacing: "0.25em", textTransform: "uppercase", color: "var(--color-text-hint)", fontWeight: 700, margin: "1.25rem 0 0.5rem" }}>
بيانات اللوحة
</p>
<DetailRow label="رقم اللوحة" value={`${car.plateLetters} ${car.plateNumber}`} mono />
<DetailRow label="نوع اللوحة" value={car.plateType ?? "—"} />
<DetailRow label="رقم الاستمارة" value={car.registrationNumber ?? "—"} mono />
<DetailRow label="رقم اللوحة" value={`${car.plateLetters} ${car.plateNumber}`} mono />
<DetailRow label="نوع اللوحة" value={car.plateType ?? "—"} />
<DetailRow label="رقم الاستمارة" value={car.registrationNumber ?? "—"} mono />
<DetailRow label="رقم الهيكل (VIN)" value={car.vinNumber ?? "—"} mono />
{/* Section: Regulatory */}
<p style={{ fontSize: 11, letterSpacing: "0.25em", textTransform: "uppercase", color: "var(--color-text-hint)", fontWeight: 700, margin: "1.25rem 0 0.5rem" }}>
الترخيص والتأمين
</p>
<DetailRow label="انتهاء الاستمارة" value={fmtDate(car.registrationExpiryDate)} warn={isExpiringSoon(car.registrationExpiryDate)} />
<DetailRow label="انتهاء التأمين" value={fmtDate(car.insuranceExpiryDate)} warn={isExpiringSoon(car.insuranceExpiryDate)} />
<DetailRow label="انتهاء الفحص الدوري" value={fmtDate(car.inspectionExpiryDate)} warn={isExpiringSoon(car.inspectionExpiryDate)} />
<DetailRow label="رقم بطاقة التشغيل" value={car.operationCardNumber ?? "—"} mono />
<DetailRow label="انتهاء الاستمارة" value={fmtDate(car.registrationExpiryDate)} warn={isExpiringSoon(car.registrationExpiryDate)} />
<DetailRow label="انتهاء التأمين" value={fmtDate(car.insuranceExpiryDate)} warn={isExpiringSoon(car.insuranceExpiryDate)} />
<DetailRow label="انتهاء الفحص الدوري" value={fmtDate(car.inspectionExpiryDate)} warn={isExpiringSoon(car.inspectionExpiryDate)} />
<DetailRow label="رقم بطاقة التشغيل" value={car.operationCardNumber ?? "—"} mono />
<DetailRow label="انتهاء بطاقة التشغيل" value={fmtDate(car.operationCardExpiry)} />
{/* Section: Operational */}
<p style={{ fontSize: 11, letterSpacing: "0.25em", textTransform: "uppercase", color: "var(--color-text-hint)", fontWeight: 700, margin: "1.25rem 0 0.5rem" }}>
بيانات تشغيلية
</p>
<DetailRow label="رقم GPS" value={car.gpsDeviceId ?? "—"} mono />
<DetailRow label="الطاقة الاستيعابية" value={car.capacity != null ? String(car.capacity) : "—"} />
<DetailRow label="الوزن (كجم)" value={car.weight != null ? String(car.weight) : "—"} />
<DetailRow label="حالة الحجز" value={car.currentImpoundStatus ?? "بدون"} />
<DetailRow label="تاريخ الإضافة" value={fmtDate(car.createdAt)} />
<DetailRow label="آخر تحديث" value={fmtDate(car.updatedAt)} />
<DetailRow label="رقم GPS" value={car.gpsDeviceId ?? "—"} mono />
<DetailRow label="الطاقة الاستيعابية" value={car.capacity != null ? String(car.capacity) : "—"} />
<DetailRow label="الوزن (كجم)" value={car.weight != null ? String(car.weight) : "—"} />
<DetailRow label="حالة الحجز" value={car.currentImpoundStatus ?? "بدون"} />
<DetailRow label="تاريخ الإضافة" value={fmtDate(car.createdAt)} />
<DetailRow label="آخر تحديث" value={fmtDate(car.updatedAt)} />
{/* Status History */}
{car.statusHistory && car.statusHistory.length > 0 && (
@@ -263,7 +225,6 @@ export function CarDetailPanel({ carId, onClose, onEdit, onDelete }: CarDetailPa
display: "flex", gap: "0.75rem",
flexShrink: 0,
}}>
{/* Gallery */}
<button type="button" onClick={() => setGallery(true)}
style={{ flex: 1, height: 40, borderRadius: "var(--radius-md)", border: "1px solid var(--color-border)", background: "var(--color-surface)", fontSize: 13, fontWeight: 600, color: "var(--color-text-secondary)", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center", gap: 8, fontFamily: "var(--font-sans)" }}>
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
@@ -273,8 +234,6 @@ export function CarDetailPanel({ carId, onClose, onEdit, onDelete }: CarDetailPa
</svg>
الصور
</button>
{/* Edit */}
<button type="button" onClick={() => onEdit(car)}
style={{ flex: 2, height: 40, borderRadius: "var(--radius-md)", border: "none", background: "var(--color-brand-600)", fontSize: 13, fontWeight: 700, color: "#FFF", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center", gap: 8, fontFamily: "var(--font-sans)" }}>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
@@ -283,8 +242,6 @@ export function CarDetailPanel({ carId, onClose, onEdit, onDelete }: CarDetailPa
</svg>
تعديل
</button>
{/* Delete */}
<button type="button" onClick={() => onDelete(car)}
style={{ height: 40, padding: "0 1rem", borderRadius: "var(--radius-md)", border: "1px solid #FECACA", background: "#FEF2F2", fontSize: 13, fontWeight: 700, color: "#DC2626", cursor: "pointer", fontFamily: "var(--font-sans)" }}>
حذف
@@ -293,7 +250,6 @@ export function CarDetailPanel({ carId, onClose, onEdit, onDelete }: CarDetailPa
)}
</aside>
{/* Image gallery overlay */}
{gallery && car && (
<CarImageGallery car={car} onClose={() => setGallery(false)} />
)}

View File

@@ -1,18 +1,23 @@
"use client";
// Components/Car/CarFormModal.tsx
import { useEffect, useRef, useState } from "react";
import * as yup from "yup";
import { Alert, Spinner } from "../UI";
import { get } from "../../services/api";
import { getStoredToken } from "../../lib/auth";
import { createCarSchema, updateCarSchema } from "@/validations/car.validator";
import type {
Car,
CarFormErrors,
CreateCarPayload,
InsuranceStatus,
UpdateCarPayload,
} from "../../types/car";
import type { Branch } from "../../types/branch";
// ── Shared input style ───────────────────────────────────────────────────────
// ── Shared input style ───────────────────────────────────────────────────────
const inputBase: React.CSSProperties = {
width: "100%",
height: 40,
@@ -41,34 +46,39 @@ const errorTextStyle: React.CSSProperties = {
fontWeight: 500,
};
// ── Validation ───────────────────────────────────────────────────────────────
function validate(form: Partial<CreateCarPayload>): CarFormErrors {
const e: CarFormErrors = {};
if (!form.manufacturer?.trim()) e.manufacturer = "الشركة المصنعة مطلوبة";
if (!form.model?.trim()) e.model = "الموديل مطلوب";
if (
!form.year ||
form.year < 1900 ||
form.year > new Date().getFullYear() + 1
)
e.year = "سنة غير صالحة";
if (!form.plateNumber?.trim()) e.plateNumber = "رقم اللوحة مطلوب";
if (!form.plateLetters?.trim()) e.plateLetters = "حروف اللوحة مطلوبة";
return e;
// ── yup validation ────────────────────────────────────────────────────────────
async function validate(
form: Partial<CreateCarPayload>,
isNew: boolean,
): Promise<CarFormErrors> {
const schema = isNew ? createCarSchema : updateCarSchema;
try {
await schema.validate(form, { abortEarly: false });
return {};
} catch (err) {
if (err instanceof yup.ValidationError) {
return err.inner.reduce<CarFormErrors>((acc, e) => {
const field = e.path as keyof CarFormErrors;
if (field && !acc[field]) acc[field] = e.message;
return acc;
}, {});
}
return {};
}
}
// ── Date helper ──────────────────────────────────────────────────────────────
// <input type="date"> gives "YYYY-MM-DD"; the backend z.string().datetime()
// requires a full ISO-8601 string ("YYYY-MM-DDTHH:mm:ss.sssZ").
// We keep state as the short form (so the input renders correctly) and convert
// only at submit time.
// ── Date helper ──────────────────────────────────────────────────────────────
// <input type="date"> gives "YYYY-MM-DD"; backend expects full ISO-8601.
function toIsoDateTime(val: string): string {
if (!val) return val;
if (val.includes("T")) return val; // Already in ISO format, likely from an existing record — just return as-is.
return `${val}T00:00:00.000Z`; // transform "2026-12-31" → "2026-12-31T00:00:00.000Z"
if (val.includes("T")) return val;
return `${val}T00:00:00.000Z`;
}
// ── Props ────────────────────────────────────────────────────────────────────
// ── Props ────────────────────────────────────────────────────────────────────
interface CarFormModalProps {
editCar: Car | null;
/** Pass pre-loaded branches or an empty array — the modal will auto-fetch if empty. */
@@ -80,7 +90,8 @@ interface CarFormModalProps {
) => Promise<boolean>;
}
// ── Component ────────────────────────────────────────────────────────────────
// ── Component ────────────────────────────────────────────────────────────────
export function CarFormModal({
editCar,
branches: branchesProp,
@@ -104,13 +115,12 @@ export function CarFormModal({
setBranches(list);
})
.catch(() => {
/* silently ignore — user can still submit */
/* silently ignore */
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// ── Form state — each field correctly typed ────────────────────────────────
// String fields
// ── Form state ─────────────────────────────────────────────────────────────
const [manufacturer, setManufacturer] = useState(editCar?.manufacturer ?? "");
const [model, setModel] = useState(editCar?.model ?? "");
const [color, setColor] = useState(editCar?.color ?? "");
@@ -122,11 +132,11 @@ export function CarFormModal({
);
const [vinNumber, setVinNumber] = useState(editCar?.vinNumber ?? "");
const [branchId, setBranchId] = useState(editCar?.branch?.id ?? "");
const [currentStatus, setCurrentStatus] = useState(
const [currentStatus, setCurrentStatus] = useState<Car["currentStatus"]>(
editCar?.currentStatus ?? "Active",
);
const [insuranceStatus, setInsuranceStatus] = useState(
editCar?.insuranceStatus ?? "Valid",
const [insuranceStatus, setInsuranceStatus] = useState<InsuranceStatus>(
(editCar?.insuranceStatus as InsuranceStatus) ?? "Valid",
);
const [registrationExpiryDate, setRegistrationExpiryDate] = useState(
editCar?.registrationExpiryDate?.slice(0, 10) ?? "",
@@ -138,7 +148,6 @@ export function CarFormModal({
editCar?.inspectionExpiryDate?.slice(0, 10) ?? "",
);
const [gpsDeviceId, setGpsDeviceId] = useState(editCar?.gpsDeviceId ?? "");
// Numeric fields — undefined when blank
const [year, setYear] = useState<number | undefined>(
editCar?.year ?? new Date().getFullYear(),
);
@@ -165,11 +174,9 @@ export function CarFormModal({
return () => window.removeEventListener("keydown", h);
}, [onClose]);
// ── Number input helper ───────────────────────────────────────────────────
const parseNum = (v: string): number | undefined =>
v.trim() === "" ? undefined : Number(v);
// ── Input error style ─────────────────────────────────────────────────────
const inputStyle = (field: keyof CarFormErrors): React.CSSProperties => ({
...inputBase,
...(errors[field]
@@ -181,26 +188,39 @@ export function CarFormModal({
setErrors((p) => ({ ...p, [field]: undefined }));
// ── Submit ────────────────────────────────────────────────────────────────
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
// Build a partial payload for validation (only required fields matter here)
const forValidation: Partial<CreateCarPayload> = {
// Build snapshot for yup — include all fields so optional rules also run
const formSnapshot: Partial<CreateCarPayload> = {
manufacturer,
model,
year,
plateNumber,
plateLetters,
currentStatus,
insuranceStatus,
registrationNumber,
vinNumber,
...(color && { color }),
...(plateType && { plateType }),
...(branchId && { branchId }),
...(registrationExpiryDate && { registrationExpiryDate }),
...(insuranceExpiryDate && { insuranceExpiryDate }),
...(inspectionExpiryDate && { inspectionExpiryDate }),
...(gpsDeviceId && { gpsDeviceId }),
...(capacity !== undefined && { capacity }),
...(weight !== undefined && { weight }),
};
const errs = validate(forValidation);
const errs = await validate(formSnapshot, isNew);
if (Object.keys(errs).length) {
setErrors(errs);
return;
}
// Build the full payload — strip empty strings to avoid schema rejection.
// We use `unknown` cast here to satisfy TypeScript while we construct the
// object dynamically; the structure still fully matches CreateCarPayload.
// Build final payload — convert date strings to ISO-8601 for the backend
const raw: Record<string, unknown> = {
manufacturer,
model,
@@ -209,8 +229,6 @@ export function CarFormModal({
plateLetters,
currentStatus,
};
// Optional string fields — only include if non-empty
if (color) raw.color = color;
if (plateType) raw.plateType = plateType;
if (registrationNumber) raw.registrationNumber = registrationNumber;
@@ -223,16 +241,11 @@ export function CarFormModal({
raw.insuranceExpiryDate = toIsoDateTime(insuranceExpiryDate);
if (inspectionExpiryDate)
raw.inspectionExpiryDate = toIsoDateTime(inspectionExpiryDate);
if (gpsDeviceId) raw.gpsDeviceId = gpsDeviceId;
// Numeric optional fields
if (capacity !== undefined) raw.capacity = capacity;
if (weight !== undefined) raw.weight = weight;
// Cast to CreateCarPayload — structure is identical, we just built it dynamically
const payload = raw as unknown as CreateCarPayload;
setSaving(true);
setApiError("");
const ok = await onSubmit(payload, isNew);
@@ -242,6 +255,7 @@ export function CarFormModal({
};
// ── Render ────────────────────────────────────────────────────────────────
return (
<div
role="dialog"
@@ -358,7 +372,7 @@ export function CarFormModal({
/>
)}
{/* Section: Basic Info */}
{/* ── Section: Basic Info ── */}
<p
style={{
fontSize: 11,
@@ -379,7 +393,6 @@ export function CarFormModal({
gap: "0.75rem",
}}
>
{/* Manufacturer — directly mapped to CreateCarPayload.manufacturer */}
<label style={labelStyle}>
الشركة المصنعة *
<input
@@ -398,8 +411,6 @@ export function CarFormModal({
<span style={errorTextStyle}>{errors.manufacturer}</span>
)}
</label>
{/* Model — directly mapped to CreateCarPayload.model */}
<label style={labelStyle}>
الموديل *
<input
@@ -425,7 +436,6 @@ export function CarFormModal({
gap: "0.75rem",
}}
>
{/* Year — maps to CreateCarPayload.year (number) */}
<label style={labelStyle}>
سنة الصنع *
<input
@@ -464,7 +474,7 @@ export function CarFormModal({
</label>
</div>
{/* Section: Plate */}
{/* ── Section: Plate ── */}
<p
style={{
fontSize: 11,
@@ -484,7 +494,6 @@ export function CarFormModal({
gap: "0.75rem",
}}
>
{/* plateNumber — directly mapped to CreateCarPayload.plateNumber */}
<label style={labelStyle}>
رقم اللوحة *
<input
@@ -501,8 +510,6 @@ export function CarFormModal({
<span style={errorTextStyle}>{errors.plateNumber}</span>
)}
</label>
{/* plateLetters — directly mapped to CreateCarPayload.plateLetters */}
<label style={labelStyle}>
حروف اللوحة *
<input
@@ -521,7 +528,7 @@ export function CarFormModal({
</label>
</div>
{/* Section: Registration & Legal */}
{/* ── Section: Registration & Legal ── */}
<p
style={{
fontSize: 11,
@@ -542,24 +549,36 @@ export function CarFormModal({
}}
>
<label style={labelStyle}>
رقم الاستمارة
رقم الاستمارة *
<input
style={inputBase}
style={inputStyle("registrationNumber")}
value={registrationNumber}
onChange={(e) => setRegistrationNumber(e.target.value)}
onChange={(e) => {
setRegistrationNumber(e.target.value);
clearFieldError("registrationNumber");
}}
placeholder="SA-001234"
dir="ltr"
/>
{errors.registrationNumber && (
<span style={errorTextStyle}>{errors.registrationNumber}</span>
)}
</label>
<label style={labelStyle}>
رقم الهيكل (VIN)
<input
style={inputBase}
style={inputStyle("vinNumber")}
value={vinNumber}
onChange={(e) => setVinNumber(e.target.value)}
onChange={(e) => {
setVinNumber(e.target.value);
clearFieldError("vinNumber");
}}
placeholder="1HGBH41JXMN109186"
dir="ltr"
/>
{errors.vinNumber && (
<span style={errorTextStyle}>{errors.vinNumber}</span>
)}
</label>
<label style={labelStyle}>
انتهاء الاستمارة
@@ -574,11 +593,9 @@ export function CarFormModal({
حالة التأمين
<select
style={{ ...inputBase, cursor: "pointer" }}
value={insuranceStatus ?? "Valid"}
value={insuranceStatus}
onChange={(e) =>
setInsuranceStatus(
e.target.value as Car["insuranceStatus"] | undefined,
)
setInsuranceStatus(e.target.value as InsuranceStatus)
}
dir="rtl"
>
@@ -607,7 +624,7 @@ export function CarFormModal({
</label>
</div>
{/* Section: Operational */}
{/* ── Section: Operational ── */}
<p
style={{
fontSize: 11,
@@ -669,35 +686,45 @@ export function CarFormModal({
dir="ltr"
/>
</label>
{/* capacity — maps to CreateCarPayload.capacity (number | undefined) */}
<label style={labelStyle}>
الطاقة الاستيعابية
<input
style={inputBase}
style={inputStyle("capacity")}
type="number"
min={0}
value={capacity ?? ""}
onChange={(e) => setCapacity(parseNum(e.target.value))}
onChange={(e) => {
setCapacity(parseNum(e.target.value));
clearFieldError("capacity");
}}
placeholder="0"
dir="ltr"
/>
{errors.capacity && (
<span style={errorTextStyle}>{errors.capacity}</span>
)}
</label>
{/* weight — maps to CreateCarPayload.weight (number | undefined) */}
<label style={labelStyle}>
الوزن (كجم)
<input
style={inputBase}
style={inputStyle("weight")}
type="number"
min={0}
value={weight ?? ""}
onChange={(e) => setWeight(parseNum(e.target.value))}
onChange={(e) => {
setWeight(parseNum(e.target.value));
clearFieldError("weight");
}}
placeholder="0"
dir="ltr"
/>
{errors.weight && (
<span style={errorTextStyle}>{errors.weight}</span>
)}
</label>
</div>
{/* Actions */}
{/* ── Actions ── */}
<div
style={{
display: "flex",
@@ -758,4 +785,4 @@ export function CarFormModal({
</div>
</div>
);
}
}

View File

@@ -2,110 +2,57 @@
// Components/Car/CarImageGallery.tsx
// Full-screen gallery modal for viewing, uploading and deleting car images.
import { useCallback, useEffect, useRef, useState } from "react";
import { useRef, useState } from "react";
import { Spinner } from "../UI";
import { carService } from "../../services/car.service";
import { getStoredToken } from "../../lib/auth";
import { useCarImages } from "../../hooks/useCars";
import { STAGE_MAP } from "../../types/car";
import type { Car, CarImage, ImageStage } from "../../types/car";
// ── Stage badge config ────────────────────────────────────────────────────────
const STAGE_MAP: Record<ImageStage, { label: string; color: string; bg: string }> = {
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<CarImage[]>([]);
const [loading, setLoading] = useState(true);
const [uploading, setUploading] = useState(false);
const [deleting, setDeleting] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [lightbox, setLightbox] = useState<CarImage | null>(null);
const [stage, setStage] = useState<ImageStage>("GENERAL");
const [sortBy, setSortBy] = useState<"asc" | "desc">("desc");
const fileRef = useRef<HTMLInputElement>(null);
const [stage, setStage] = useState<ImageStage>("GENERAL");
const [sortBy, setSortBy] = useState<"asc" | "desc">("desc");
const [lightbox, setLightbox] = useState<CarImage | null>(null);
const fileRef = useRef<HTMLInputElement>(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]);
const {
images, loading, uploading, deleting, error, setError,
uploadImages, deleteImage,
} = useCarImages(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<HTMLInputElement>) => {
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 = "";
}
await uploadImages(files, stage);
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);
const ok = await deleteImage(imageId);
if (ok && lightbox?.id === imageId) setLightbox(null);
};
const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === "Escape") {
if (lightbox) setLightbox(null);
else onClose();
}
};
// ── Helpers ─────────────────────────────────────────────────────────────────
/** Build full image URL — uses the proxy so no CORS issues */
const imgSrc = (img: CarImage) =>
img.url ?? `/api/proxy/car-photos/${img.image}`;
const imgSrc = (img: CarImage) => img.url ?? `/api/proxy/car-photos/${img.image}`;
// ── Render ───────────────────────────────────────────────────────────────────
return (
<div
role="dialog" aria-modal="true" aria-label="معرض صور المركبة"
onKeyDown={handleKeyDown}
onClick={e => { if (e.target === e.currentTarget) onClose(); }}
style={{
position: "fixed", inset: 0, zIndex: 70,
@@ -131,56 +78,23 @@ export function CarImageGallery({ car, onClose }: CarImageGalleryProps) {
</div>
<div style={{ display: "flex", alignItems: "center", gap: "0.75rem" }}>
{/* Sort */}
<select
value={sortBy}
onChange={e => setSortBy(e.target.value as "asc" | "desc")}
style={{
height: 36, borderRadius: "var(--radius-md)",
border: "1px solid var(--color-border)",
background: "var(--color-surface)",
fontSize: 12, color: "var(--color-text-secondary)",
padding: "0 0.75rem", outline: "none",
fontFamily: "var(--font-sans)",
}}
>
<select value={sortBy} onChange={e => setSortBy(e.target.value as "asc" | "desc")}
style={{ height: 36, borderRadius: "var(--radius-md)", border: "1px solid var(--color-border)", background: "var(--color-surface)", fontSize: 12, color: "var(--color-text-secondary)", padding: "0 0.75rem", outline: "none", fontFamily: "var(--font-sans)" }}>
<option value="desc">الأحدث أولاً</option>
<option value="asc">الأقدم أولاً</option>
</select>
{/* Stage selector for upload */}
<select
value={stage}
onChange={e => setStage(e.target.value as ImageStage)}
style={{
height: 36, borderRadius: "var(--radius-md)",
border: "1px solid var(--color-border)",
background: "var(--color-surface)",
fontSize: 12, color: "var(--color-text-secondary)",
padding: "0 0.75rem", outline: "none",
fontFamily: "var(--font-sans)",
}}
>
<select value={stage} onChange={e => setStage(e.target.value as ImageStage)}
style={{ height: 36, borderRadius: "var(--radius-md)", border: "1px solid var(--color-border)", background: "var(--color-surface)", fontSize: 12, color: "var(--color-text-secondary)", padding: "0 0.75rem", outline: "none", fontFamily: "var(--font-sans)" }}>
<option value="GENERAL">عام</option>
<option value="BEFORE">قبل</option>
<option value="AFTER">بعد</option>
</select>
{/* Upload button */}
<button
type="button"
onClick={() => fileRef.current?.click()}
disabled={uploading}
style={{
height: 36, padding: "0 1rem",
borderRadius: "var(--radius-md)",
border: "none",
background: uploading ? "var(--color-brand-400)" : "var(--color-brand-600)",
fontSize: 13, fontWeight: 700, color: "#FFF",
cursor: uploading ? "not-allowed" : "pointer",
display: "flex", alignItems: "center", gap: 8,
fontFamily: "var(--font-sans)",
}}
>
<button type="button" onClick={() => fileRef.current?.click()} disabled={uploading}
style={{ height: 36, padding: "0 1rem", borderRadius: "var(--radius-md)", border: "none", background: uploading ? "var(--color-brand-400)" : "var(--color-brand-600)", fontSize: 13, fontWeight: 700, color: "#FFF", cursor: uploading ? "not-allowed" : "pointer", display: "flex", alignItems: "center", gap: 8, fontFamily: "var(--font-sans)" }}>
{uploading
? <><Spinner size="sm" className="text-white" /> جارٍ الرفع</>
: <>
@@ -191,14 +105,7 @@ export function CarImageGallery({ car, onClose }: CarImageGalleryProps) {
</>
}
</button>
<input
ref={fileRef}
type="file"
accept="image/*"
multiple
style={{ display: "none" }}
onChange={handleUpload}
/>
<input ref={fileRef} type="file" accept="image/*" multiple style={{ display: "none" }} onChange={handleUpload} />
{/* Close */}
<button type="button" onClick={onClose} aria-label="إغلاق"
@@ -228,53 +135,36 @@ export function CarImageGallery({ car, onClose }: CarImageGalleryProps) {
<div style={{ fontSize: 48, marginBottom: 12 }}>📸</div>
<p style={{ fontSize: 15, color: "var(--color-text-muted)", fontWeight: 600 }}>لا توجد صور بعد</p>
<p style={{ fontSize: 13, color: "var(--color-text-hint)", marginTop: 4 }}>
اضغط على "رفع صور" لإضافة أولى الصور لهذه المركبة.
اضغط على &quot;رفع صور&quot; لإضافة أولى الصور لهذه المركبة.
</p>
</div>
) : (
<div style={{
display: "grid",
gridTemplateColumns: "repeat(auto-fill, minmax(220px, 1fr))",
gap: "1rem",
}}>
<div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(220px, 1fr))", gap: "1rem" }}>
{images.map(img => {
const stageInfo = STAGE_MAP[img.stage ?? "GENERAL"] ?? STAGE_MAP.GENERAL;
const isDeleting = deleting === img.id;
return (
<div
key={img.id}
style={{
borderRadius: "var(--radius-xl)",
border: "1px solid var(--color-border)",
background: "var(--color-surface)",
overflow: "hidden",
boxShadow: "var(--shadow-card)",
opacity: isDeleting ? 0.5 : 1,
transition: "opacity 200ms",
}}
>
{/* Image */}
<div
style={{ position: "relative", paddingBottom: "70%", cursor: "pointer" }}
onClick={() => setLightbox(img)}
>
<div key={img.id} style={{
borderRadius: "var(--radius-xl)",
border: "1px solid var(--color-border)",
background: "var(--color-surface)",
overflow: "hidden",
boxShadow: "var(--shadow-card)",
opacity: isDeleting ? 0.5 : 1,
transition: "opacity 200ms",
}}>
<div style={{ position: "relative", paddingBottom: "70%", cursor: "pointer" }} onClick={() => setLightbox(img)}>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={imgSrc(img)}
alt={`صورة ${stageInfo.label}`}
style={{
position: "absolute", inset: 0,
width: "100%", height: "100%",
objectFit: "cover",
}}
style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover" }}
onError={e => { (e.target as HTMLImageElement).src = "/file.svg"; }}
/>
{/* Stage badge */}
<span style={{
position: "absolute", top: 8, right: 8,
borderRadius: "var(--radius-full)",
background: stageInfo.bg,
color: stageInfo.color,
background: stageInfo.bg, color: stageInfo.color,
padding: "0.2rem 0.625rem",
fontSize: 10, fontWeight: 700,
boxShadow: "0 1px 4px rgba(0,0,0,.12)",
@@ -283,30 +173,12 @@ export function CarImageGallery({ car, onClose }: CarImageGalleryProps) {
</span>
</div>
{/* Footer */}
<div style={{
display: "flex", alignItems: "center", justifyContent: "space-between",
padding: "0.6rem 0.75rem",
borderTop: "1px solid var(--color-border)",
}}>
<div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "0.6rem 0.75rem", borderTop: "1px solid var(--color-border)" }}>
<span style={{ fontSize: 11, color: "var(--color-text-muted)" }}>
{new Date(img.createdAt).toLocaleDateString("ar-SA", { month: "short", day: "numeric" })}
</span>
<button
type="button"
onClick={() => handleDelete(img.id)}
disabled={isDeleting}
aria-label="حذف الصورة"
style={{
width: 28, height: 28,
borderRadius: "var(--radius-sm)",
border: "1px solid #FECACA",
background: "#FEF2F2",
color: "#DC2626",
cursor: isDeleting ? "not-allowed" : "pointer",
display: "flex", alignItems: "center", justifyContent: "center",
}}
>
<button type="button" onClick={() => handleDelete(img.id)} disabled={isDeleting} aria-label="حذف الصورة"
style={{ width: 28, height: 28, borderRadius: "var(--radius-sm)", border: "1px solid #FECACA", background: "#FEF2F2", color: "#DC2626", cursor: isDeleting ? "not-allowed" : "pointer", display: "flex", alignItems: "center", justifyContent: "center" }}>
{isDeleting
? <Spinner size="sm" className="text-red-600" />
: <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
@@ -325,15 +197,7 @@ export function CarImageGallery({ car, onClose }: CarImageGalleryProps) {
{/* ── Lightbox ── */}
{lightbox && (
<div
onClick={() => setLightbox(null)}
style={{
position: "fixed", inset: 0, zIndex: 80,
background: "rgba(0,0,0,0.9)",
display: "flex", alignItems: "center", justifyContent: "center",
padding: "1rem",
}}
>
<div onClick={() => 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 */}
<img
src={imgSrc(lightbox)}
@@ -342,16 +206,7 @@ export function CarImageGallery({ car, onClose }: CarImageGalleryProps) {
onClick={e => e.stopPropagation()}
onError={e => { (e.target as HTMLImageElement).src = "/file.svg"; }}
/>
<button
onClick={() => setLightbox(null)}
style={{
position: "absolute", top: 24, right: 24,
width: 40, height: 40, borderRadius: "50%",
background: "rgba(255,255,255,0.15)", border: "none",
color: "#fff", fontSize: 20, cursor: "pointer",
display: "flex", alignItems: "center", justifyContent: "center",
}}
>
<button onClick={() => setLightbox(null)} style={{ position: "absolute", top: 24, right: 24, width: 40, height: 40, borderRadius: "50%", background: "rgba(255,255,255,0.15)", border: "none", color: "#fff", fontSize: 20, cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center" }}>
×
</button>
</div>