import React, { useState } from 'react';
import { X, Loader2, Sparkles } from 'lucide-react';
import { inventoryAPI } from '../../utils/api';
import { lookupBarcode, mapCategory } from '../../utils/openFoodFacts';

interface AddItemModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSuccess: () => void;
  categories: any[];
}

const AddItemModal: React.FC<AddItemModalProps> = ({ isOpen, onClose, onSuccess, categories }) => {
  const [formData, setFormData] = useState({
    name: '',
    description: '',
    quantity: 0,
    unit: '',
    expiryDate: '',
    categoryId: '',
    lowStockThreshold: 5,
    barcode: '',
    imageUrl: '',
  });
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [lookupLoading, setLookupLoading] = useState(false);
  const [productFound, setProductFound] = useState(false);
  const [productImage, setProductImage] = useState<string | null>(null);

  const resetForm = () => {
    setFormData({
      name: '',
      description: '',
      quantity: 0,
      unit: '',
      expiryDate: '',
      categoryId: '',
      lowStockThreshold: 5,
      barcode: '',
      imageUrl: '',
    });
    setError('');
    setLookupLoading(false);
    setProductFound(false);
    setProductImage(null);
  };

  const handleClose = () => {
    resetForm();
    onClose();
  };

  const handleManualBarcodeEntry = async () => {
    if (!formData.barcode || formData.barcode.length < 8) return;
    
    setLookupLoading(true);
    setProductFound(false);
    setError('');
    
    try {
      const productData = await lookupBarcode(formData.barcode);
      
      if (productData) {
        const mappedCategoryId = mapCategory(productData.category, productData.name, categories);
        
        setFormData({
          ...formData,
          name: productData.name + (productData.brand ? ` - ${productData.brand}` : ''),
          description: productData.description || '',
          categoryId: mappedCategoryId,
          imageUrl: productData.imageUrl || '',
        });
        setProductImage(productData.imageUrl || null);
        setProductFound(true);
      } else {
        setError('Product not found. Please enter details manually.');
      }
    } catch (err) {
      console.error('Lookup error:', err);
      setError('Failed to lookup product.');
    } finally {
      setLookupLoading(false);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError('');

    try {
      await inventoryAPI.create(formData);
      onSuccess();
      resetForm();
      onClose();
    } catch (err: any) {
      setError(err.message || 'Failed to add item');
    } finally {
      setLoading(false);
    }
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-xl shadow-xl max-w-2xl w-full max-h-[90vh] overflow-y-auto">
        <div className="sticky top-0 bg-white border-b border-light-gray px-6 py-4 flex justify-between items-center">
          <h3 className="text-lg font-semibold text-deep-forest">Add New Item</h3>
          <button onClick={handleClose} className="p-2 hover:bg-gray-100 rounded-lg transition-colors">
            <X className="h-5 w-5 text-secondary-text" />
          </button>
        </div>

        <form onSubmit={handleSubmit} className="p-6 space-y-4">
          {error && (
            <div className="bg-warning/10 border border-warning text-warning px-4 py-3 rounded-lg text-sm">
              {error}
            </div>
          )}

          {lookupLoading && (
            <div className="bg-stable/10 border border-stable text-stable px-4 py-3 rounded-lg text-sm flex items-center gap-2">
              <Loader2 className="h-4 w-4 animate-spin" />
              Looking up product information...
            </div>
          )}

          {productFound && (
            <div className="bg-fresh/10 border border-fresh text-primary-green px-4 py-3 rounded-lg text-sm">
              <div className="flex items-center gap-2 mb-2">
                <Sparkles className="h-4 w-4" />
                Product found! Information auto-filled. Please review and add quantity.
              </div>
              {productImage && (
                <div className="mt-2 flex items-center gap-3">
                  <img 
                    src={productImage} 
                    alt="Product" 
                    className="w-16 h-16 object-cover rounded border border-primary-green/30"
                  />
                  <span className="text-xs text-secondary-text">Product image loaded</span>
                </div>
              )}
            </div>
          )}

          {/* Barcode Entry Section */}
          <div className="border-2 border-dashed border-primary-green/30 rounded-lg p-4 bg-primary-green/5">
            <label className="block text-sm font-semibold text-deep-forest mb-2">
              🔍 Enter Barcode
            </label>
            <input
              type="text"
              value={formData.barcode}
              onChange={(e) => setFormData({ ...formData, barcode: e.target.value })}
              onBlur={handleManualBarcodeEntry}
              className="w-full px-3 py-2 border border-light-gray rounded-lg focus:ring-2 focus:ring-primary-green focus:border-primary-green text-primary-text"
              placeholder="Enter barcode manually or use keyboard scanner"
            />
            <p className="text-xs text-secondary-text mt-2">
              Enter barcode to auto-fill product details from Open Food Facts database. Compatible with keyboard barcode scanners.
            </p>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-primary-text mb-2">
                Item Name *
              </label>
              <input
                type="text"
                required
                value={formData.name}
                onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                className="w-full px-3 py-2 border border-light-gray rounded-lg focus:ring-2 focus:ring-primary-green focus:border-primary-green text-primary-text"
                placeholder="e.g., Fresh Apples"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-primary-text mb-2">
                Category
              </label>
              <select
                value={formData.categoryId}
                onChange={(e) => setFormData({ ...formData, categoryId: e.target.value })}
                className="w-full px-3 py-2 border border-light-gray rounded-lg focus:ring-2 focus:ring-primary-green focus:border-primary-green text-primary-text"
              >
                <option value="">Select category</option>
                {categories.map((cat) => (
                  <option key={cat.id} value={cat.id}>
                    {cat.name}
                  </option>
                ))}
              </select>
            </div>

            <div>
              <label className="block text-sm font-medium text-primary-text mb-2">
                Quantity *
              </label>
              <input
                type="number"
                required
                min="0"
                value={formData.quantity}
                onChange={(e) => setFormData({ ...formData, quantity: parseInt(e.target.value) })}
                className="w-full px-3 py-2 border border-light-gray rounded-lg focus:ring-2 focus:ring-primary-green focus:border-primary-green text-primary-text"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-primary-text mb-2">
                Unit (Optional)
              </label>
              <input
                type="text"
                value={formData.unit}
                onChange={(e) => setFormData({ ...formData, unit: e.target.value })}
                className="w-full px-3 py-2 border border-light-gray rounded-lg focus:ring-2 focus:ring-primary-green focus:border-primary-green text-primary-text"
                placeholder="e.g., lbs, cans, loaves"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-primary-text mb-2">
                Expiry Date
              </label>
              <input
                type="date"
                value={formData.expiryDate}
                onChange={(e) => setFormData({ ...formData, expiryDate: e.target.value })}
                className="w-full px-3 py-2 border border-light-gray rounded-lg focus:ring-2 focus:ring-primary-green focus:border-primary-green text-primary-text"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-primary-text mb-2">
                Low Stock Threshold (Minimum 5)
              </label>
              <input
                type="number"
                min="0"
                value={formData.lowStockThreshold}
                onChange={(e) => setFormData({ ...formData, lowStockThreshold: parseInt(e.target.value) })}
                className="w-full px-3 py-2 border border-light-gray rounded-lg focus:ring-2 focus:ring-primary-green focus:border-primary-green text-primary-text"
              />
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium text-primary-text mb-2">
              Description
            </label>
            <textarea
              rows={3}
              value={formData.description}
              onChange={(e) => setFormData({ ...formData, description: e.target.value })}
              className="w-full px-3 py-2 border border-light-gray rounded-lg focus:ring-2 focus:ring-primary-green focus:border-primary-green text-primary-text"
              placeholder="Optional description..."
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-primary-text mb-2">
              Image URL (Optional)
            </label>
            <input
              type="url"
              value={formData.imageUrl}
              onChange={(e) => setFormData({ ...formData, imageUrl: e.target.value })}
              className="w-full px-3 py-2 border border-light-gray rounded-lg focus:ring-2 focus:ring-primary-green focus:border-primary-green text-primary-text"
              placeholder="https://example.com/image.jpg"
            />
            <p className="text-xs text-secondary-text mt-1">
              Add a custom image URL or use barcode lookup to auto-fill
            </p>
          </div>

          <div className="flex gap-3 pt-4">
            <button
              type="button"
              onClick={handleClose}
              className="flex-1 px-4 py-2 border-2 border-light-gray text-primary-text rounded-lg hover:bg-card-hover transition-colors font-medium"
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={loading}
              className="flex-1 px-4 py-2 bg-btn-primary text-white rounded-lg hover:bg-btn-primary-hover active:bg-btn-primary-active transition-colors font-medium shadow-sm disabled:opacity-50 flex items-center justify-center"
            >
              {loading ? (
                <>
                  <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                  Adding...
                </>
              ) : (
                'Add Item'
              )}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
};

export default AddItemModal;

