import { useRef, useState } from "react";
import "../../styles/AddImageModal.css";

export default function AddImageModal({ itemName, onClose, onAddImage }) {
  const [selectedImage, setSelectedImage] = useState(null);
  const [imagePreview, setImagePreview] = useState(null);
  const cameraInputRef = useRef(null);
  const galleryInputRef = useRef(null);

  const handleFileSelect = (e) => {
    const file = e.target.files[0];
    if (file) {
      setSelectedImage(file);
      const reader = new FileReader();
      reader.onloadend = () => {
        setImagePreview(reader.result);
      };
      reader.readAsDataURL(file);
    }
  };

  const handleCameraClick = () => {
    cameraInputRef.current?.click();
  };

  const handleGalleryClick = () => {
    galleryInputRef.current?.click();
  };

  const handleConfirm = () => {
    if (selectedImage) {
      onAddImage(selectedImage);
    }
  };

  const removeImage = () => {
    setSelectedImage(null);
    setImagePreview(null);
  };

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <h2 className="modal-title">Add Image</h2>
        <p className="text-center mb-4" style={{ color: 'var(--color-text-secondary)', fontSize: '0.95em' }}>
          There's no image for <strong className="text-primary">"{itemName}"</strong> yet. Add a new image?
        </p>

        {!imagePreview ? (
          <div className="add-image-options">
            <button onClick={handleCameraClick} className="add-image-option-btn camera">
              📷 Use Camera
            </button>
            <button onClick={handleGalleryClick} className="add-image-option-btn gallery">
              🖼️ Choose from Gallery
            </button>
          </div>
        ) : (
          <div className="add-image-preview-container">
            <div className="add-image-preview">
              <img src={imagePreview} alt="Preview" />
              <button type="button" onClick={removeImage} className="add-image-remove">
                ×
              </button>
            </div>
          </div>
        )}

        <input
          ref={cameraInputRef}
          type="file"
          accept="image/*"
          capture="environment"
          onChange={handleFileSelect}
          style={{ display: "none" }}
        />

        <input
          ref={galleryInputRef}
          type="file"
          accept="image/*"
          onChange={handleFileSelect}
          style={{ display: "none" }}
        />

        <div className="modal-actions">
          <button onClick={onClose} className="btn btn-outline flex-1">
            Cancel
          </button>
          {imagePreview && (
            <button onClick={handleConfirm} className="btn btn-success flex-1">
              Add Image
            </button>
          )}
        </div>
      </div>
    </div>
  );
}
