import React, { useState } from 'react';
import {Plant, MaintenanceRecord, Fertilizer, Chemical, PlantTitles} from '../types';
import { X } from 'lucide-react';
import { apiService } from '../services/api';

interface MaintenanceFormProps {
  plants: Plant[];
  onSave: (maintenance: Omit<MaintenanceRecord, 'id' | 'createdAt' | 'updatedAt'>) => void;
  onCancel: () => void;
}

const MaintenanceForm: React.FC<MaintenanceFormProps> = ({ plants, onSave, onCancel }) => {
  const [formData, setFormData] = useState({
    plantId: '',
    date: new Date().toISOString().split('T')[0],
    type: 'other' as MaintenanceRecord['type'],
    description: '',
    amount: '',
    fertilizerId: '',
    chemicalId: '',
    isPlanned: false,
    isCompleted: true
  });

  const [fertilizers, setFertilizers] = useState<Fertilizer[]>([]);
  const [chemicals, setChemicals] = useState<Chemical[]>([]);

  React.useEffect(() => {
    loadRegisters();
  }, []);

  const loadRegisters = async () => {
    try {
      const [fertilizersData, chemicalsData] = await Promise.all([
        apiService.getFertilizers(),
        apiService.getChemicals()
      ]);
      setFertilizers(fertilizersData);
      setChemicals(chemicalsData);
    } catch (error) {
      console.error('Error loading registers:', error);
    }
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    onSave({
      ...formData,
      plantId: parseInt(formData.plantId),
      amount: formData.amount || undefined,
      fertilizerId: formData.fertilizerId ? parseInt(formData.fertilizerId) : undefined,
      chemicalId: formData.chemicalId ? parseInt(formData.chemicalId) : undefined,
      isPlanned: formData.isPlanned,
      isCompleted: formData.isCompleted
    });
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => {
    const { name, value, type } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: type === 'checkbox' ? (e.target as HTMLInputElement).checked : 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-md 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">Выполненная работа</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>
            <label htmlFor="plantId" className="block text-sm font-medium text-gray-700 mb-1">
              Растение *
            </label>
            <select
              id="plantId"
              name="plantId"
              value={formData.plantId}
              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="">Выбор растения</option>
              {plants.map(plant => (
                <option key={plant.id} value={plant.id}>
                  {plant.variety} ({PlantTitles[plant.type]})
                </option>
              ))}
            </select>
          </div>

          <div>
            <label htmlFor="date" className="block text-sm font-medium text-gray-700 mb-1">
              Дата *
            </label>
            <input
              type="date"
              id="date"
              name="date"
              value={formData.date}
              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"
            />
          </div>

          <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="other">Другое</option>
              <option value="chemical">Обработка химикатами</option>
              <option value="fertilizer">Подкормка удобрением</option>
              <option value="watering">Полив</option>
              <option value="pruning">Обрезка</option>
              <option value="transplanting">Пересадка</option>
            </select>
          </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="Опишите мероприятия по работам..."
              required
              rows={4}
              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>

          {/* Fertilizer Selection */}
          {formData.type === 'fertilizer' && (
              <div>
                <label htmlFor="fertilizerId" className="block text-sm font-medium text-gray-700 mb-1">
                  Выбор удобрения
                </label>
                <select
                    id="fertilizerId"
                    name="fertilizerId"
                    value={formData.fertilizerId}
                    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 focus:border-transparent"
                >
                  <option value="">Выбор удобрения (не обязательно)</option>
                  {fertilizers.map(fertilizer => (
                      <option key={fertilizer.id} value={fertilizer.id}>
                        {fertilizer.name} {fertilizer.brand && `- ${fertilizer.brand}`} ({fertilizer.npkRatio})
                      </option>
                  ))}
                </select>
                {formData.fertilizerId && (
                    <div className="mt-2 p-2 bg-green-50 rounded text-sm">
                      {(() => {
                        const selected = fertilizers.find(f => f.id === parseInt(formData.fertilizerId));
                        return selected ? (
                            <div>
                              <p><strong>Норма расхода:</strong> {selected.applicationRate}</p>
                              <p><strong>Как часто применять:</strong> {selected.frequency}</p>
                              {selected.notes && <p><strong>Заметки:</strong> {selected.notes}</p>}
                            </div>
                        ) : null;
                      })()}
                    </div>
                )}
              </div>
          )}

          {/* Chemical Selection */}
          {formData.type === 'chemical' && (
              <div>
                <label htmlFor="chemicalId" className="block text-sm font-medium text-gray-700 mb-1">
                  Выбор химикатов
                </label>
                <select
                    id="chemicalId"
                    name="chemicalId"
                    value={formData.chemicalId}
                    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 focus:border-transparent"
                >
                  <option value="">Выбор химикатов (не обязательно)</option>
                  {chemicals.map(chemical => (
                      <option key={chemical.id} value={chemical.id}>
                        {chemical.name} {chemical.brand && `- ${chemical.brand}`} ({chemical.type})
                      </option>
                  ))}
                </select>
                {formData.chemicalId && (
                    <div className="mt-2 p-2 bg-red-50 rounded text-sm">
                      {(() => {
                        const selected = chemicals.find(c => c.id === parseInt(formData.chemicalId));
                        return selected ? (
                            <div>
                              <p><strong>Активные ингредиенты:</strong> {selected.activeIngredient}</p>
                              <p><strong>Против вредителей:</strong> {selected.targetPests}</p>
                              <p><strong>Безопасный период:</strong> {selected.safetyPeriod} days</p>
                              {selected.notes && <p><strong>Заметки:</strong> {selected.notes}</p>}
                            </div>
                        ) : null;
                      })()}
                    </div>
                )}
              </div>
          )}

          <div>
            <label htmlFor="amount" className="block text-sm font-medium text-gray-700 mb-1">
              Количество (необязательно)
            </label>
            <input
              type="text"
              id="amount"
              name="amount"
              value={formData.amount}
              onChange={handleChange}
              placeholder="например, 2 чашки, 1 кг., 500 мл."
              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 className="grid grid-cols-2 gap-4">
            <div className="flex items-center">
              <input
                type="checkbox"
                id="isPlanned"
                name="isPlanned"
                checked={formData.isPlanned}
                onChange={handleChange}
                className="h-4 w-4 text-green-600 focus:ring-green-500 border-gray-300 rounded"
              />
              <label htmlFor="isPlanned" className="ml-2 block text-sm text-gray-700">
                Запланированная работа
              </label>
            </div>

            <div className="flex items-center">
              <input
                type="checkbox"
                id="isCompleted"
                name="isCompleted"
                checked={formData.isCompleted}
                onChange={handleChange}
                className="h-4 w-4 text-green-600 focus:ring-green-500 border-gray-300 rounded"
              />
              <label htmlFor="isCompleted" className="ml-2 block text-sm text-gray-700">
                Завершена
              </label>
            </div>
          </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"
            >
              Выполнено
            </button>
          </div>
        </form>
      </div>
    </div>
  );
};

export default MaintenanceForm;