import React, { useState } from 'react';
import { HarvestRecord, Plant, HarvestProcessing } from '../types';
import { X } from 'lucide-react';
import { apiService } from '../services/api';

interface HarvestProcessingModalProps {
  isOpen: boolean;
  harvest: HarvestRecord;
  plant: Plant;
  onClose: () => void;
  onProcessingAdded: () => void;
}

export const processTypes = [
  { value: 'fresh', label: 'Fresh/Raw', color: 'bg-green-100 text-green-800' },
  { value: 'frozen', label: 'Frozen', color: 'bg-blue-100 text-blue-800' },
  { value: 'jam', label: 'Jam/Preserves', color: 'bg-purple-100 text-purple-800' },
  { value: 'dried', label: 'Dried', color: 'bg-yellow-100 text-yellow-800' },
  { value: 'canned', label: 'Canned', color: 'bg-orange-100 text-orange-800' },
  { value: 'juice', label: 'Juice', color: 'bg-pink-100 text-pink-800' },
  { value: 'sauce', label: 'Sauce', color: 'bg-red-100 text-red-800' },
  { value: 'pickled', label: 'Pickled', color: 'bg-indigo-100 text-indigo-800' },
  { value: 'other', label: 'Other', color: 'bg-gray-100 text-gray-800' }
];

export default function HarvestProcessingModal({ 
  isOpen, 
  harvest, 
  plant, 
  onClose, 
  onProcessingAdded 
}: HarvestProcessingModalProps) {
  const [formData, setFormData] = useState({
    processType: 'fresh' as HarvestProcessing['processType'],
    quantity: harvest.quantity.toString(),
    unit: harvest.unit,
    processDate: new Date().toISOString().split('T')[0],
    expiryDate: '',
    storageLocation: '',
    notes: ''
  });

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    try {
      await apiService.createHarvestProcessing({
        harvestId: harvest.id,
        processType: formData.processType,
        quantity: parseFloat(formData.quantity),
        unit: formData.unit,
        processDate: formData.processDate,
        expiryDate: formData.expiryDate || undefined,
        storageLocation: formData.storageLocation || undefined,
        notes: formData.notes || undefined
      });
      
      onProcessingAdded();
      onClose();
    } catch (error) {
      console.error('Error creating harvest processing:', error);
      alert('Failed to create harvest processing record');
    }
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;

    if (name === 'unit') {
      // Check if the new unit requires integer values
      const countableUnits = ['pieces', 'jars', 'bottles', 'bags'];
      const requiresInteger = countableUnits.includes(value);

      setFormData(prev => ({
        ...prev,
        [name]: value,
        // Convert quantity to integer if switching to a countable unit
        quantity: requiresInteger ? Math.floor(parseFloat(prev.quantity) || 0).toString() : prev.quantity
      }));
    } else {
      setFormData(prev => ({ ...prev, [name]: value }));
    }
  };

  if (!isOpen) return null;

  // Determine if current unit requires integer values
  const countableUnits = ['pieces', 'jars', 'bottles', 'bags'];
  const requiresInteger = countableUnits.includes(formData.unit);

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
      <div className="bg-white rounded-lg shadow-xl w-full max-w-2xl max-h-[90vh] overflow-y-auto">
        <div className="flex items-center justify-between p-6 border-b">
          <div>
            <h2 className="text-xl font-semibold text-gray-900">Обработка урожая</h2>
            <p className="text-sm text-gray-600 mt-1">
              {plant.variety} - {harvest.quantity} {harvest.unit} собрано {new Date(harvest.date).toLocaleDateString()}
            </p>
          </div>
          <button
            onClick={onClose}
            className="text-gray-400 hover:text-gray-600 transition-colors"
          >
            <X className="w-6 h-6" />
          </button>
        </div>

        <form onSubmit={handleSubmit} className="p-6 space-y-6">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Тип заготовки *
              </label>
              <select
                name="processType"
                value={formData.processType}
                onChange={handleChange}
                required
                className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500"
              >
                {processTypes.map(type => (
                  <option key={type.value} value={type.value}>
                    {type.label}
                  </option>
                ))}
              </select>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Дата обработки *
              </label>
              <input
                type="date"
                name="processDate"
                value={formData.processDate}
                onChange={handleChange}
                required
                className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Количество *
              </label>
              <input
                type="number"
                name="quantity"
                value={formData.quantity}
                onChange={handleChange}
                step={requiresInteger ? "1" : "0.1"}
                min="0"
                max={harvest.quantity}
                required
                className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500"
              />
              {requiresInteger && (
                  <p className="text-xs text-gray-500 mt-1">
                    Для этого типа требуются только целые числа
                  </p>
              )}
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Единицы
              </label>
              <select
                name="unit"
                value={formData.unit}
                onChange={handleChange}
                className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500"
              >
                <option value="kg">Килограммы (кг)</option>
                <option value="pieces">Штуки</option>
                <option value="jars">Банки</option>
                <option value="bottles">Бутылки</option>
                <option value="bags">Мешки</option>
                <option value="liters">Литры</option>
              </select>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Срок годности
              </label>
              <input
                type="date"
                name="expiryDate"
                value={formData.expiryDate}
                onChange={handleChange}
                className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Место хранения
              </label>
              <input
                type="text"
                name="storageLocation"
                value={formData.storageLocation}
                onChange={handleChange}
                placeholder="Морозилка, Кладовая, Подвал"
                className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500"
              />
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              Заметки
            </label>
            <textarea
              name="notes"
              value={formData.notes}
              onChange={handleChange}
              rows={3}
              placeholder="Используемая рецептура, способ обработки, характеристики качества..."
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500 resize-none"
            />
          </div>

          <div className="flex justify-end space-x-3 pt-4 border-t">
            <button
              type="button"
              onClick={onClose}
              className="px-4 py-2 text-gray-700 bg-gray-100 rounded-md hover:bg-gray-200 transition-colors"
            >
              Отмена
            </button>
            <button
              type="submit"
              className="px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 transition-colors"
            >
              Добавить
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}