import React, { useState, useEffect } from 'react';
import { Fertilizer } from '../types';
import { X } from 'lucide-react';

interface FertilizerFormProps {
  fertilizer?: Fertilizer | null;
  onSave: (fertilizer: Omit<Fertilizer, 'id' | 'createdAt' | 'updatedAt'>) => void;
  onCancel: () => void;
}

const FertilizerForm: React.FC<FertilizerFormProps> = ({ fertilizer, onSave, onCancel }) => {
  const [formData, setFormData] = useState({
    name: '',
    brand: '',
    type: 'organic' as Fertilizer['type'],
    npkRatio: '',
    description: '',
    applicationRate: '',
    frequency: '',
    season: '',
    notes: ''
  });

  useEffect(() => {
    if (fertilizer) {
      setFormData({
        name: fertilizer.name,
        brand: fertilizer.brand || '',
        type: fertilizer.type,
        npkRatio: fertilizer.npkRatio || '',
        description: fertilizer.description || '',
        applicationRate: fertilizer.applicationRate || '',
        frequency: fertilizer.frequency || '',
        season: fertilizer.season || '',
        notes: fertilizer.notes || ''
      });
    }
  }, [fertilizer]);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    onSave({
      ...formData,
      brand: formData.brand || undefined,
      npkRatio: formData.npkRatio || undefined,
      description: formData.description || undefined,
      applicationRate: formData.applicationRate || undefined,
      frequency: formData.frequency || undefined,
      season: formData.season || undefined,
      notes: formData.notes || undefined
    });
  };

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

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-lg shadow-xl max-w-2xl w-full max-h-[90vh] overflow-y-auto">
        <div className="flex justify-between items-center p-6 border-b border-gray-200">
          <h3 className="text-lg font-semibold text-gray-900">
            {fertilizer ? 'Редактировать данные' : 'Новое удобрение'}
          </h3>
          <button
            onClick={onCancel}
            className="text-gray-400 hover:text-gray-600 transition-colors"
          >
            <X className="h-5 w-5" />
          </button>
        </div>

        <form onSubmit={handleSubmit} className="p-6 space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label htmlFor="name" className="block text-sm font-medium text-gray-700 mb-1">
                Наименование *
              </label>
              <input
                type="text"
                id="name"
                name="name"
                value={formData.name}
                onChange={handleChange}
                placeholder="e.g., All-Purpose Garden Fertilizer"
                required
                className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500 focus:border-transparent"
              />
            </div>

            <div>
              <label htmlFor="brand" className="block text-sm font-medium text-gray-700 mb-1">
                Марка
              </label>
              <input
                type="text"
                id="brand"
                name="brand"
                value={formData.brand}
                onChange={handleChange}
                placeholder="e.g., Miracle-Gro"
                className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500 focus:border-transparent"
              />
            </div>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label htmlFor="type" className="block text-sm font-medium text-gray-700 mb-1">
                Тип *
              </label>
              <select
                id="type"
                name="type"
                value={formData.type}
                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 focus:border-transparent"
              >
                <option value="organic">Органическое</option>
                <option value="synthetic">Синтетическое</option>
                <option value="liquid">Жидкое</option>
                <option value="granular">Гранулированное</option>
                <option value="slow-release">Медленного действия</option>
              </select>
            </div>

            <div>
              <label htmlFor="npkRatio" className="block text-sm font-medium text-gray-700 mb-1">
                Азот-Фосфор-Калий (NPK)
              </label>
              <input
                type="text"
                id="npkRatio"
                name="npkRatio"
                value={formData.npkRatio}
                onChange={handleChange}
                placeholder="e.g., 10-10-10"
                className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500 focus:border-transparent"
              />
            </div>
          </div>

          <div>
            <label htmlFor="description" className="block text-sm font-medium text-gray-700 mb-1">
              Описание
            </label>
            <textarea
              id="description"
              name="description"
              value={formData.description}
              onChange={handleChange}
              placeholder="Brief description of the fertilizer..."
              rows={3}
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500 focus:border-transparent resize-none"
            />
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label htmlFor="applicationRate" className="block text-sm font-medium text-gray-700 mb-1">
                Норма расхода
              </label>
              <input
                type="text"
                id="applicationRate"
                name="applicationRate"
                value={formData.applicationRate}
                onChange={handleChange}
                placeholder="e.g., 1 tablespoon per gallon"
                className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500 focus:border-transparent"
              />
            </div>

            <div>
              <label htmlFor="frequency" className="block text-sm font-medium text-gray-700 mb-1">
                Как часто применять
              </label>
              <input
                type="text"
                id="frequency"
                name="frequency"
                value={formData.frequency}
                onChange={handleChange}
                placeholder="e.g., Every 2 weeks"
                className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500 focus:border-transparent"
              />
            </div>
          </div>

          <div>
            <label htmlFor="season" className="block text-sm font-medium text-gray-700 mb-1">
              Время года
            </label>
            <input
              type="text"
              id="season"
              name="season"
              value={formData.season}
              onChange={handleChange}
              placeholder="e.g., Spring-Summer"
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500 focus:border-transparent"
            />
          </div>

          <div>
            <label htmlFor="notes" className="block text-sm font-medium text-gray-700 mb-1">
              Заметки
            </label>
            <textarea
              id="notes"
              name="notes"
              value={formData.notes}
              onChange={handleChange}
              placeholder="Additional notes or special instructions..."
              rows={3}
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500 focus:border-transparent resize-none"
            />
          </div>

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

export default FertilizerForm;