import React, { useState, useEffect } from 'react';
import { X, Timer, Cloud, FileText, Scissors, Zap } from './Icons';
import { MowingFormData, Mower } from '../types/zone';
import { api } from '../services/api';

interface MowingModalProps {
  zoneName: string;
  activityType?: 'mowing' | 'trimming';
  onSubmit: (data: MowingFormData) => void;
  onCancel: () => void;
  loading?: boolean;
}

const MowingModal: React.FC<MowingModalProps> = ({ 
  zoneName, 
  activityType = 'mowing',
  onSubmit, 
  onCancel, 
  loading = false 
}) => {
  const [formData, setFormData] = useState<MowingFormData>({
    notes: '',
    duration: undefined,
    weather: '',
    mowerId: undefined,
    activityType,
  });
  const [mowers, setMowers] = useState<Mower[]>([]);
  const [loadingMowers, setLoadingMowers] = useState(true);

  useEffect(() => {
    loadMowers();
  }, []);

  const loadMowers = async () => {
    try {
      const data = await api.getMowers();
      setMowers(data);
      // Auto-select first mower if only one exists
      if (data.length === 1) {
        setFormData(prev => ({ ...prev, mowerId: data[0].id }));
      }
    } catch (error) {
      console.error('Failed to load mowers:', error);
    } finally {
      setLoadingMowers(false);
    }
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    onSubmit(formData);
  };

  const weatherOptions = [
    'Солнечно',
    'Переменная облачность',
    'Облачно',
    'Пасмурно',
    'Небольшой дождь',
    'Ветренно',
    'Жарко',
    'Холодно',
    'Влажно'
  ];

  const getMowerIcon = (type: string) => {
    switch (type.toLowerCase()) {
      case 'battery':
        return '🔋';
      case 'electric':
        return '⚡';
      case 'gas':
      case 'petrol':
        return '⛽';
      default:
        return '🚜';
    }
  };

  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 max-w-md w-full">
        <div className="flex items-center justify-between p-6 border-b">
          <div>
            <h2 className="text-xl font-semibold text-gray-900 flex items-center gap-2">
              {activityType === 'trimming' ? (
                  <Zap className="h-6 w-6 text-purple-600" />
              ) : (
                  <Scissors className="h-6 w-6 text-green-600" />
              )}
              {activityType === 'trimming' ? 'Запись подравнивания' : 'Отметить как скошенное'}: {zoneName}
            </h2>
            {activityType === 'trimming' && (
                <p className="text-sm text-gray-600 mt-1">
                  Подравнивание сдвинет следующий покос на одну неделю
                </p>
            )}
          </div>
          <button
            onClick={onCancel}
            className="text-gray-400 hover:text-gray-600 transition-colors duration-200"
          >
            <X className="h-6 w-6" />
          </button>
        </div>

        <form onSubmit={handleSubmit} className="p-6 space-y-6">
          {/* Mower Selection */}
          <div>
            <label htmlFor="mowerId" className="block text-sm font-medium text-gray-700 mb-2">
              {activityType === 'trimming' ? (
                  <Zap className="h-4 w-4 inline mr-2" />
              ) : (
                  <Scissors className="h-4 w-4 inline mr-2" />
              )}
              {activityType === 'trimming' ? 'Использованный триммер' : 'Использованная газонокосилка'}
            </label>
            {loadingMowers ? (
                <div className="w-full px-3 py-2 border border-gray-300 rounded-md bg-gray-50">
                  <span className="text-gray-500">Loading mowers...</span>
                </div>
            ) : (
                <select
                    id="mowerId"
                    value={formData.mowerId || ''}
                    onChange={(e) => setFormData(prev => ({
                      ...prev,
                      mowerId: e.target.value ? parseInt(e.target.value) : undefined
                    }))}
                    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"
                    required={activityType === 'mowing'}
                >
                  <option value="">
                    {activityType === 'trimming' ? 'Вабор триммера (не обязательно)' : 'Выбор газонокосилки'}
                  </option>
                  {mowers.map(mower => (
                      <option key={mower.id} value={mower.id}>
                        {getMowerIcon(mower.type)} {mower.name} ({mower.type})
                      </option>
                  ))}
                </select>
            )}
            {mowers.length === 0 && !loadingMowers && (
                <p className="text-xs text-amber-600 mt-1">
                  No mowers found. You can still record the {activityType} session without selecting equipment.
                </p>
            )}
          </div>

          {/* Duration */}
          <div>
            <label htmlFor="duration" className="block text-sm font-medium text-gray-700 mb-2">
              <Timer className="h-4 w-4 inline mr-2" />
              Длительность (минуты)
            </label>
            <input
              type="number"
              id="duration"
              value={formData.duration || ''}
              onChange={(e) => setFormData(prev => ({ 
                ...prev, 
                duration: e.target.value ? parseInt(e.target.value) : undefined 
              }))}
              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"
              min="1"
              max="480"
              placeholder="например, 45"
            />
            <p className="text-xs text-gray-500 mt-1">
              Необязательно - сколько времени заняла {activityType}?
            </p>
          </div>

          {/* Weather */}
          <div>
            <label htmlFor="weather" className="block text-sm font-medium text-gray-700 mb-2">
              <Cloud className="h-4 w-4 inline mr-2" />
              Погодные условия
            </label>
            <select
              id="weather"
              value={formData.weather || ''}
              onChange={(e) => setFormData(prev => ({ ...prev, weather: e.target.value }))}
              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>
              {weatherOptions.map(weather => (
                <option key={weather} value={weather}>{weather}</option>
              ))}
            </select>
          </div>

          {/* Notes */}
          <div>
            <label htmlFor="notes" className="block text-sm font-medium text-gray-700 mb-2">
              <FileText className="h-4 w-4 inline mr-2" />
              Заметки
            </label>
            <textarea
              id="notes"
              value={formData.notes || ''}
              onChange={(e) => setFormData(prev => ({ ...prev, notes: e.target.value }))}
              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"
              rows={3}
              placeholder={
                activityType === 'trimming'
                    ? "Заметки о сеансе обрезки, обработанных участках, состоянии травы..."
                    : "Любые замечания, проблемы или специальные примечания..."
              }
            />
            <p className="text-xs text-gray-500 mt-1">
              Необязательно - запишите все особые замечания по поводу {activityType}
            </p>
          </div>

          {/* Form Actions */}
          <div className="flex gap-3 pt-4">
            <button
              type="button"
              onClick={onCancel}
              className="flex-1 py-2 px-4 border border-gray-300 text-gray-700 rounded-md hover:bg-gray-50 transition-colors duration-200"
            >
              Отмена
            </button>
            <button
              type="submit"
              disabled={loading}
              className={`flex-1 py-2 px-4 text-white rounded-md disabled:opacity-50 disabled:cursor-not-allowed transition-colors duration-200 ${
                  activityType === 'trimming'
                      ? 'bg-purple-600 hover:bg-purple-700'
                      : 'bg-green-600 hover:bg-green-700'
              }`}
            >
              {loading ? 'Recording...' : activityType === 'trimming' ? 'Подровнено' : 'Скошено'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
};

export default MowingModal;