import React, { useState, useEffect } from 'react';
import {Plant, PlantObservation, PlantTitles} from '../types';
import { X } from 'lucide-react';
import ImageUpload from './ImageUpload';
import { apiService } from '../services/api';

interface ObservationFormProps {
  observation?: PlantObservation | null;
  plants: Plant[];
  onSave: (observation: Omit<PlantObservation, 'id' | 'createdAt' | 'updatedAt'>) => void;
  onCancel: () => void;
}

const ObservationForm: React.FC<ObservationFormProps> = ({ observation, plants, onSave, onCancel }) => {
  const [formData, setFormData] = useState({
    plantId: '',
    date: new Date().toISOString().split('T')[0],
    title: '',
    observation: '',
    weatherConditions: '',
    temperature: '',
    photoUrl: '',
    tags: ''
  });

  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [uploading, setUploading] = useState(false);

  useEffect(() => {
    if (observation) {
      setFormData({
        plantId: observation.plantId.toString(),
        date: observation.date,
        title: observation.title,
        observation: observation.observation,
        weatherConditions: observation.weatherConditions || '',
        temperature: observation.temperature?.toString() || '',
        photoUrl: observation.photoUrl || '',
        tags: observation.tags || ''
      });
    }
  }, [observation]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    let finalPhotoUrl = formData.photoUrl;

    // Upload image if a file is selected
    if (selectedFile) {
      try {
        setUploading(true);
        const result = await apiService.uploadPhoto(selectedFile);
        finalPhotoUrl = result.photoUrl;
      } catch (error) {
        console.error('Error uploading photo:', error);
        alert('Failed to upload photo. Please try again.');
        setUploading(false);
        return;
      } finally {
        setUploading(false);
      }
    }

    onSave({
      ...formData,
      plantId: parseInt(formData.plantId),
      temperature: formData.temperature ? parseFloat(formData.temperature) : undefined,
      weatherConditions: formData.weatherConditions || undefined,
      photoUrl: finalPhotoUrl || undefined,
      tags: formData.tags || undefined
    });
  };

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

  const handleFileSelect = (file: File) => {
    setSelectedFile(file);
  };

  const handleImageChange = (imageUrl: string) => {
    setFormData(prev => ({ ...prev, photoUrl: imageUrl }));
  };

  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">
            {observation ? 'Изменить запись' : 'Добавить запись'}
          </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="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>

          <div>
            <label htmlFor="title" className="block text-sm font-medium text-gray-700 mb-1">
              Наименование *
            </label>
            <input
              type="text"
              id="title"
              name="title"
              value={formData.title}
              onChange={handleChange}
              placeholder="например, появились первые бутоны, замечены повреждения от вредителей"
              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="observation" className="block text-sm font-medium text-gray-700 mb-1">
              Наблюдение *
            </label>
            <textarea
              id="observation"
              name="observation"
              value={formData.observation}
              onChange={handleChange}
              placeholder="Наблюдение за состоянием растения, его ростом или любыми замеченными изменениями..."
              required
              rows={5}
              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="weatherConditions" className="block text-sm font-medium text-gray-700 mb-1">
                Погодные условия
              </label>
              <input
                type="text"
                id="weatherConditions"
                name="weatherConditions"
                value={formData.weatherConditions}
                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 focus:border-transparent"
              />
            </div>

            <div>
              <label htmlFor="temperature" className="block text-sm font-medium text-gray-700 mb-1">
                Температура (°C)
              </label>
              <input
                type="number"
                id="temperature"
                name="temperature"
                value={formData.temperature}
                onChange={handleChange}
                step="0.1"
                placeholder="например, 22.5"
                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 className="block text-sm font-medium text-gray-700 mb-2">
              Фотография
            </label>
            <ImageUpload
                currentImageUrl={formData.photoUrl}
                onImageChange={handleImageChange}
                onFileSelect={handleFileSelect}
                uploading={uploading}
            />
          </div>

          <div>
            <label htmlFor="tags" className="block text-sm font-medium text-gray-700 mb-1">
              Теги
            </label>
            <input
              type="text"
              id="tags"
              name="tags"
              value={formData.tags}
              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 focus:border-transparent"
            />
            <p className="text-xs text-gray-500 mt-1">
              Разделите несколько тегов запятыми
            </p>
          </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"
                disabled={uploading}
                className="px-4 py-2 bg-green-600 hover:bg-green-700 text-white rounded-md transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {uploading ? 'Загружается...' : (observation ? 'Изменить' : 'Добавить')}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
};

export default ObservationForm;