All files / src/components/features/admin/ProductForm index.tsx

91.38% Statements 403/441
69.13% Branches 56/81
57.14% Functions 4/7
91.38% Lines 403/441

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 4421x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 25x 25x 25x 25x 25x       411x 411x 411x 29x 29x 29x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 25x 29x 24x 24x 24x 24x 24x 24x 24x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 167x 167x 167x 167x 167x 167x 1x 1x 1x 1x 1x 1x 167x 167x 411x 411x 411x 411x 196x 196x 196x 196x 196x 196x 196x 196x   196x 196x 196x 196x       411x 411x 411x 12x 12x 12x 5x 5x 5x 5x 7x 7x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 6x 6x 6x 6x 6x 6x 6x 12x 12x 12x 12x 12x 1x 1x 1x 12x 7x 7x 7x 411x 411x 411x 12x 12x 411x 411x 411x 411x 196x     196x 196x     196x 411x 411x 411x                                                 411x 411x 411x 411x 411x 411x 6x 6x 6x 411x 411x 376x 376x 376x 376x 376x 376x 376x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 1227x 1227x 1227x 411x 411x 411x 411x 411x 411x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 8x 8x 8x 8x 8x       8x 8x 411x 411x 411x 1x 1x 1x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x  
"use client";
 
import { useState, useEffect, useCallback } from "react";
import Image from "next/image";
import { ImageUploadWidget } from "./ImageUploadWidget";
import { validateProductForm } from "@/lib/core";
import { clientLogger } from "@/lib/logging/clientLogger";
import { useConfirm } from "@/hooks/useConfirm";
import { useDebounce } from "@/hooks/useDebounce";
import { Button, Input } from "@/components/ui";
 
interface Category {
  id: number;
  title: string;
}
 
interface ProductImage {
  id: number;
  url: string;
  thumbnailUrl: string;
  order: number;
}
 
interface ProductFormData {
  title: string;
  description: string;
  price: string | number;
  discountedPrice: string | number;
  stock: number;
  categoryId: string | number;
  sku: string;
  images?: ProductImage[];
}
 
interface ProductFormProps {
  productId?: number;
  initialData?: ProductFormData;
  onSubmit: (data: ProductFormData) => Promise<void>;
  categories: Category[];
  /** If true, hides the internal submit button (for external control) */
  hideSubmitButton?: boolean;
  /** Ref to expose form submission trigger */
  submitRef?: React.MutableRefObject<(() => void) | null>;
  /** Callback to report loading state changes */
  onLoadingChange?: (loading: boolean) => void;
  /** Callback to report validation errors */
  onErrorChange?: (hasErrors: boolean) => void;
}
 
export const ProductForm: React.FC<ProductFormProps> = ({
  productId,
  initialData,
  onSubmit,
  categories,
  hideSubmitButton = false,
  submitRef,
  onLoadingChange,
  onErrorChange,
}) => {
  const { confirm, ConfirmDialog } = useConfirm();
 
  // Get storage key based on whether we're editing or creating
  const storageKey = productId
    ? `product-form-edit-${productId}`
    : 'product-form-new';
 
  // Load saved data from localStorage on mount
  const getSavedData = () => {
    if (typeof window === 'undefined') return null;
    try {
      const saved = localStorage.getItem(storageKey);
      return saved ? JSON.parse(saved) : null;
    } catch (err) {
      clientLogger.error("Failed to load saved form data", err instanceof Error ? err : new Error(String(err)));
      return null;
    }
  };
 
  const [formData, setFormData] = useState(() => {
    // If initialData is provided (from server), use it
    // Only fall back to localStorage if no initialData (for draft recovery on new products)
    if (initialData) {
      return {
        title: initialData.title || "",
        description: initialData.description || "",
        price: initialData.price || "",
        discountedPrice: initialData.discountedPrice || "",
        stock: initialData.stock || 0,
        categoryId: initialData.categoryId || "",
        sku: initialData.sku || "",
      };
    }
    const savedData = getSavedData();
    return savedData || {
      title: "",
      description: "",
      price: "",
      discountedPrice: "",
      stock: 0,
      categoryId: "",
      sku: ""};
  });
 
  const [images, setImages] = useState<ProductImage[]>(initialData?.images || []);
  const [loading, setLoading] = useState(false);
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [successMessage, setSuccessMessage] = useState("");
  const [autoSaveStatus, setAutoSaveStatus] = useState<'saving' | 'saved' | null>(null);
 
  // Debounce formData to avoid saving too frequently
  const debouncedFormData = useDebounce(formData, 1000);
 
  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
    const { name, value } = e.target;
    setFormData((prev: ProductFormData) => ({
      ...prev,
      [name]: value}));
    // Clear error for this field
    if (errors[name]) {
      setErrors((prev: Record<string, string>) => {
        const newErrors = { ...prev };
        delete newErrors[name];
        return newErrors;
      });
    }
    // Show saving status when user types
    setAutoSaveStatus('saving');
  };
 
  // Auto-save to localStorage when debouncedFormData changes
  useEffect(() => {
    if (typeof window === 'undefined') return;
 
    try {
      localStorage.setItem(storageKey, JSON.stringify(debouncedFormData));
      setAutoSaveStatus('saved');
 
      // Clear saved status after 2 seconds
      const timeout = setTimeout(() => {
        setAutoSaveStatus(null);
      }, 2000);
 
      return () => clearTimeout(timeout);
    } catch (err) {
      clientLogger.error("Failed to auto-save form data", err instanceof Error ? err : new Error(String(err)));
      setAutoSaveStatus(null);
    }
  }, [debouncedFormData, storageKey]);
 
  const performSubmit = useCallback(async () => {
    // Validate
    const validation = validateProductForm(formData as unknown as Record<string, unknown>);
    if (!validation.valid) {
      setErrors(validation.errors);
      onErrorChange?.(true);
      return;
    }
 
    setLoading(true);
    onLoadingChange?.(true);
    setSuccessMessage("");
    try {
      const dataToSubmit = {
        ...formData,
        price: parseFloat(String(formData.price)),
        discountedPrice: formData.discountedPrice
          ? parseFloat(String(formData.discountedPrice))
          : parseFloat(String(formData.price)),
        categoryId: parseInt(String(formData.categoryId)),
        stock: parseInt(String(formData.stock)) || 0};
 
      await onSubmit(dataToSubmit);
 
      // Clear auto-saved data from localStorage on successful submit
      if (typeof window !== 'undefined') {
        localStorage.removeItem(storageKey);
      }
 
      setSuccessMessage(
        productId ? "Product updated successfully!" : "Product created successfully!"
      );
      setTimeout(() => setSuccessMessage(""), 3000);
      onErrorChange?.(false);
    } catch (err) {
      const error = err instanceof Error ? err : new Error("Failed to save product");
      setErrors({ submit: error.message });
      onErrorChange?.(true);
    } finally {
      setLoading(false);
      onLoadingChange?.(false);
    }
  }, [formData, onSubmit, productId, storageKey, onErrorChange, onLoadingChange]);
 
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    await performSubmit();
  };
 
  // Expose submit function via ref for external control
  useEffect(() => {
    if (submitRef) {
      submitRef.current = performSubmit;
    }
    return () => {
      if (submitRef) {
        submitRef.current = null;
      }
    };
  }, [submitRef, performSubmit]);
 
  const handleImageDelete = async (imageId: number) => {
    const confirmed = await confirm({
      title: "Delete Image",
      message: "Are you sure you want to delete this image? Both full-size and thumbnail versions will be removed.",
      confirmText: "Delete",
      cancelText: "Cancel",
      variant: "danger"});

    if (!confirmed) return;

    try {
      const response = await fetch(
        `/api/admin/products/images?id=${imageId}`,
        { method: "DELETE" }
      );

      if (response.ok) {
        setImages((prev) => prev.filter((img) => img.id !== imageId));
      } else {
        alert("Failed to delete image");
      }
    } catch (err) {
      clientLogger.error("Failed to delete image", err instanceof Error ? err : new Error(String(err)));
      alert("Failed to delete image");
    }
  };
 
  return (
    <form onSubmit={handleSubmit} className="max-w-[900px] mx-auto">
      <div className="flex justify-between items-center mb-5">
        {successMessage && (
          <div className="text-green-800 bg-green-100 border border-green-300 rounded py-3 px-4 mb-5 text-sm border-l-4 border-l-green-500">
            {successMessage}
          </div>
        )}
        {autoSaveStatus && !successMessage && (
          <div className={`py-2 px-3 rounded text-sm ml-auto ${
            autoSaveStatus === 'saved'
              ? 'bg-green-100 text-green-800 border border-green-300'
              : 'bg-yellow-100 text-yellow-700 border border-yellow-300'
          }`}>
            {autoSaveStatus === 'saving' ? '💾 Saving draft...' : '✓ Draft saved'}
          </div>
        )}
      </div>
 
      <div className="bg-white dark:bg-gray-800 p-8 md:p-5 rounded-lg mb-8 shadow-sm">
        <h2 className="text-xl m-0 mb-6 text-gray-800 dark:text-gray-100 border-b-2 border-gray-100 dark:border-gray-700 pb-4">Product Details</h2>
 
        <div className="mb-5">
          <Input
            label="Product Title *"
            id="title"
            name="title"
            type="text"
            value={formData.title}
            onChange={handleChange}
            placeholder="Enter product title"
            error={errors.title}
            state={errors.title ? 'error' : 'default'}
            fullWidth
          />
        </div>
 
        <div className="mb-5">
          <Input
            as="textarea"
            label="Description"
            id="description"
            name="description"
            value={formData.description}
            onChange={handleChange}
            placeholder="Enter product description"
            rows={4}
            fullWidth
            className="resize-y min-h-[100px]"
          />
        </div>
 
        <div className="grid grid-cols-2 md:grid-cols-1 gap-5">
          <div className="mb-5">
            <Input
              label="Price *"
              id="price"
              name="price"
              type="number"
              step={0.01}
              value={formData.price}
              onChange={handleChange}
              error={errors.price}
              state={errors.price ? 'error' : 'default'}
              fullWidth
            />
          </div>
 
          <div className="mb-5">
            <Input
              label="Discounted Price"
              id="discountedPrice"
              name="discountedPrice"
              type="number"
              step={0.01}
              value={formData.discountedPrice}
              onChange={handleChange}
              error={errors.discountedPrice}
              state={errors.discountedPrice ? 'error' : 'default'}
              fullWidth
            />
          </div>
        </div>
 
        <div className="grid grid-cols-2 md:grid-cols-1 gap-5">
          <div className="mb-5">
            <Input
              label="Stock"
              id="stock"
              name="stock"
              type="number"
              value={formData.stock}
              onChange={handleChange}
              fullWidth
            />
          </div>
 
          <div className="mb-5">
            <Input
              label="SKU"
              id="sku"
              name="sku"
              type="text"
              value={formData.sku}
              onChange={handleChange}
              placeholder="SKU-000001"
              fullWidth
            />
          </div>
        </div>
 
        <div className="mb-5">
          <Input
            as="select"
            label="Category *"
            id="categoryId"
            name="categoryId"
            value={formData.categoryId}
            onChange={handleChange}
            error={errors.categoryId}
            state={errors.categoryId ? 'error' : 'default'}
            fullWidth
          >
            <option value="">Select a category</option>
            {categories.map((cat) => (
              <option key={cat.id} value={cat.id}>
                {cat.title}
              </option>
            ))}
          </Input>
        </div>
      </div>
 
      {productId && (
        <div className="bg-white dark:bg-gray-800 p-8 md:p-5 rounded-lg mb-8 shadow-sm">
          <h2 className="text-xl m-0 mb-6 text-gray-800 dark:text-gray-100 border-b-2 border-gray-100 dark:border-gray-700 pb-4">Product Images</h2>
 
          <ImageUploadWidget
            productId={productId}
            onImageUploaded={(img) => setImages([...images, img])}
          />
 
          {images.length > 0 && (
            <div className="grid grid-cols-[repeat(auto-fill,minmax(150px,1fr))] md:grid-cols-[repeat(auto-fill,minmax(120px,1fr))] gap-4 mt-5">
              {images.filter((img) => img.thumbnailUrl || img.url).map((img, index) => (
                <div key={img.id ?? `img-${index}`} className="bg-white dark:bg-gray-700 border border-gray-200 dark:border-gray-600 rounded-lg overflow-hidden transition-all duration-300 hover:shadow-lg hover:border-blue-500">
                  <div className="w-[150px] md:w-[120px] h-[150px] md:h-[120px] overflow-hidden bg-gray-100 dark:bg-gray-600">
                    <Image
                      src={img.thumbnailUrl || img.url}
                      alt={`Product image ${img.id}`}
                      width={200}
                      height={200}
                      className="w-full h-full object-cover"
                    />
                  </div>
                  <div className="p-2.5 text-center">
                    <p className="text-xs text-gray-500 dark:text-gray-400 m-0 mb-2 font-semibold">
                      Image #{img.order}
                    </p>
                    <Button
                      type="button"
                      variant="danger"
                      size="sm"
                      onClick={() => handleImageDelete(img.id)}
                    >
                      Delete
                    </Button>
                  </div>
                </div>
              ))}
            </div>
          )}
 
          {images.length === 0 && (
            <div className="py-10 px-5 text-center bg-gray-50 dark:bg-gray-700 border-2 border-dashed border-gray-200 dark:border-gray-600 rounded-lg text-gray-500 dark:text-gray-400">
              <p className="m-0 text-sm">No images uploaded yet. Upload at least one preview and one thumbnail image.</p>
            </div>
          )}
        </div>
      )}
 
      {errors.submit && (
        <div className="text-red-600 text-xs mt-1.5 block bg-red-50 dark:bg-red-900/30 dark:text-red-400 py-3 px-4 rounded border-l-[3px] border-red-500 mb-5">
          {errors.submit}
        </div>
      )}
 
      {!hideSubmitButton && (
        <div className="flex gap-3 justify-end mt-8 md:flex-col">
          <Button
            type="submit"
            variant="primary"
            size="md"
            loading={loading}
            className="md:w-full"
          >
            {productId ? "Update Product" : "Create Product"}
          </Button>
        </div>
      )}
      <ConfirmDialog />
    </form>
  );
};