'use client';

/**
 * MenuItemForm — create or edit a menu item.
 * Req 8.1: form with name, description, price, image upload, category, active status.
 * Req 8.4: supports editing existing menu items.
 * Req 8.6: category selection from provided list.
 */

import { useState, useRef } from 'react';
import { Input } from '../ui/input';
import { Button } from '../ui/button';

/**
 * @param {{
 *   initialData?: {
 *     name?: string,
 *     categoryId?: number|string,
 *     description?: string,
 *     price?: number|string,
 *     isActive?: boolean,
 *     imageUrl?: string,
 *   },
 *   categories: Array<{ id: number|string, name: string }>,
 *   onSubmit: (formData: FormData) => void,
 *   onCancel: () => void,
 *   loading?: boolean,
 *   error?: string,
 * }} props
 */
export default function MenuItemForm({
  initialData = {},
  categories = [],
  onSubmit,
  onCancel,
  loading = false,
  error,
}) {
  const [name, setName] = useState(initialData.name ?? '');
  const [categoryId, setCategoryId] = useState(
    initialData.categoryId != null ? String(initialData.categoryId) : ''
  );
  const [description, setDescription] = useState(initialData.description ?? '');
  const [price, setPrice] = useState(
    initialData.price != null ? String(initialData.price) : ''
  );
  const [isActive, setIsActive] = useState(initialData.isActive ?? true);
  const [imageFile, setImageFile] = useState(null);
  const [imagePreview, setImagePreview] = useState(null);

  const [fieldErrors, setFieldErrors] = useState({});
  const fileInputRef = useRef(null);

  const isEditMode = Boolean(initialData.name);

  function handleImageChange(e) {
    const file = e.target.files?.[0] ?? null;
    setImageFile(file);
    if (file) {
      const reader = new FileReader();
      reader.onload = (ev) => setImagePreview(ev.target.result);
      reader.readAsDataURL(file);
    } else {
      setImagePreview(null);
    }
  }

  function validate() {
    const errors = {};
    if (!name.trim()) errors.name = 'Name is required.';
    if (!categoryId) errors.categoryId = 'Category is required.';
    if (price === '' || price === null) {
      errors.price = 'Price is required.';
    } else if (isNaN(Number(price)) || Number(price) < 0) {
      errors.price = 'Price must be a non-negative number.';
    }
    return errors;
  }

  function handleSubmit(e) {
    e.preventDefault();
    const errors = validate();
    if (Object.keys(errors).length > 0) {
      setFieldErrors(errors);
      return;
    }
    setFieldErrors({});

    const formData = new FormData();
    formData.append('name', name.trim());
    formData.append('categoryId', categoryId);
    formData.append('description', description.trim());
    formData.append('price', price);
    formData.append('isActive', String(isActive));
    if (imageFile) {
      formData.append('image', imageFile);
    }

    onSubmit(formData);
  }

  const currentImageUrl = initialData.imageUrl;
  const previewSrc = imagePreview ?? currentImageUrl ?? null;

  return (
    <form onSubmit={handleSubmit} noValidate className="flex flex-col gap-4">
      {/* Form-level error */}
      {error && (
        <div
          role="alert"
          className="rounded-md border border-red-300 bg-red-50 px-4 py-3 text-sm text-red-700"
        >
          {error}
        </div>
      )}

      {/* Name */}
      <Input
        id="menu-item-name"
        label="Name *"
        type="text"
        value={name}
        onChange={(e) => setName(e.target.value)}
        error={fieldErrors.name}
        placeholder="e.g. Grilled Chicken"
        required
      />

      {/* Category */}
      <div className="flex flex-col gap-1">
        <label
          htmlFor="menu-item-category"
          className="text-sm font-medium text-secondary"
        >
          Category *
        </label>
        <select
          id="menu-item-category"
          value={categoryId}
          onChange={(e) => setCategoryId(e.target.value)}
          aria-describedby={fieldErrors.categoryId ? 'menu-item-category-error' : undefined}
          aria-invalid={fieldErrors.categoryId ? 'true' : undefined}
          required
          className={[
            'w-full rounded-md border px-3 py-2 text-base text-secondary',
            'min-h-[44px] bg-white',
            'transition-colors',
            'focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-1',
            fieldErrors.categoryId
              ? 'border-red-500 bg-red-50 focus:ring-red-500'
              : 'border-secondary-200 hover:border-secondary-400',
          ]
            .filter(Boolean)
            .join(' ')}
        >
          <option value="">Select a category…</option>
          {categories.map((cat) => (
            <option key={cat.id} value={String(cat.id)}>
              {cat.name}
            </option>
          ))}
        </select>
        {fieldErrors.categoryId && (
          <p
            id="menu-item-category-error"
            role="alert"
            className="text-sm text-red-600"
          >
            {fieldErrors.categoryId}
          </p>
        )}
      </div>

      {/* Description */}
      <div className="flex flex-col gap-1">
        <label
          htmlFor="menu-item-description"
          className="text-sm font-medium text-secondary"
        >
          Description
        </label>
        <textarea
          id="menu-item-description"
          value={description}
          onChange={(e) => setDescription(e.target.value)}
          placeholder="Optional description…"
          rows={3}
          className={[
            'w-full rounded-md border px-3 py-2 text-base text-secondary',
            'placeholder:text-secondary-400',
            'transition-colors resize-y',
            'focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-1',
            'border-secondary-200 bg-white hover:border-secondary-400',
          ].join(' ')}
        />
      </div>

      {/* Price */}
      <Input
        id="menu-item-price"
        label="Price *"
        type="number"
        min="0"
        step="0.01"
        value={price}
        onChange={(e) => setPrice(e.target.value)}
        error={fieldErrors.price}
        placeholder="0.00"
        required
      />

      {/* Active status */}
      <div className="flex items-center gap-3">
        <input
          id="menu-item-is-active"
          type="checkbox"
          checked={isActive}
          onChange={(e) => setIsActive(e.target.checked)}
          className="h-5 w-5 cursor-pointer rounded border-secondary-300 text-primary focus:ring-primary"
        />
        <label
          htmlFor="menu-item-is-active"
          className="cursor-pointer text-sm font-medium text-secondary"
        >
          Active (visible to customers)
        </label>
      </div>

      {/* Image upload */}
      <div className="flex flex-col gap-2">
        <span className="text-sm font-medium text-secondary">
          {isEditMode ? 'Replace Image' : 'Image'}
        </span>

        {/* Preview */}
        {previewSrc && (
          <div className="relative h-40 w-40 overflow-hidden rounded-md border border-secondary-200">
            {/* eslint-disable-next-line @next/next/no-img-element */}
            <img
              src={previewSrc}
              alt={imagePreview ? 'Selected image preview' : 'Current image'}
              className="h-full w-full object-cover"
            />
            {imagePreview && (
              <span className="absolute bottom-1 left-1 rounded bg-black/60 px-1.5 py-0.5 text-xs text-white">
                Preview
              </span>
            )}
          </div>
        )}

        {/* Current image URL (edit mode, no new file selected) */}
        {isEditMode && currentImageUrl && !imagePreview && (
          <p className="text-xs text-secondary-500 break-all">
            Current: {currentImageUrl}
          </p>
        )}

        <input
          ref={fileInputRef}
          id="menu-item-image"
          type="file"
          accept="image/*"
          onChange={handleImageChange}
          className="block w-full text-sm text-secondary-600
            file:mr-3 file:cursor-pointer file:rounded-md file:border-0
            file:bg-primary file:px-3 file:py-2 file:text-sm file:font-medium file:text-white
            hover:file:bg-primary-600"
        />
      </div>

      {/* Actions */}
      <div className="flex justify-end gap-3 pt-2">
        <Button
          type="button"
          variant="ghost"
          onClick={onCancel}
          disabled={loading}
        >
          Cancel
        </Button>
        <Button type="submit" variant="default" loading={loading}>
          {isEditMode ? 'Save Changes' : 'Create Item'}
        </Button>
      </div>
    </form>
  );
}
