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

interface BulkMowingModalProps {
  zones: Zone[];
  activityType?: 'mowing' | 'trimming';
  onSubmit: (data: BulkMowingFormData) => void;
  onCancel: () => void;
  loading?: boolean;
}

const BulkMowingModal: React.FC<BulkMowingModalProps> = ({ 
  zones, 
  activityType = 'mowing',
  onSubmit, 
  onCancel, 
  loading = false 
}) => {
  const [formData, setFormData] = useState<BulkMowingFormData>({
    selectedZoneIds: [],
    notes: '',
    totalDuration: 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();
    if (formData.selectedZoneIds.length === 0) {
      alert('Please select at least one zone to mow.');
      return;
    }
    onSubmit(formData);
  };

  const handleZoneToggle = (zoneId: number) => {
    setFormData(prev => ({
      ...prev,
      selectedZoneIds: prev.selectedZoneIds.includes(zoneId)
        ? prev.selectedZoneIds.filter(id => id !== zoneId)
        : [...prev.selectedZoneIds, zoneId]
    }));
  };

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

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

  const getZoneStatusColor = (zone: Zone) => {
    switch (zone.status) {
      case 'overdue':
        return 'border-red-200 bg-red-50';
      case 'due':
        return 'border-orange-200 bg-orange-50';
      case 'new':
        return 'border-blue-200 bg-blue-50';
      default:
        return 'border-green-200 bg-green-50';
    }
  };

  const getZoneStatusText = (zone: Zone) => {
    if (zone.isNew) {
      return 'Еще не косилась';
    } else if (zone.isOverdue) {
      return `${Math.abs(zone.daysUntilNext!)} дней посроченно`;
    } else if (zone.isDueToday) {
      return 'Срок - сегодня';
    } else {
      return `${zone.daysUntilNext} дней осталось`;
    }
  };

  const selectedZones = zones.filter(zone => formData.selectedZoneIds.includes(zone.id));
  const totalSelectedArea = selectedZones.reduce((sum, zone) => sum + zone.area, 0);

  // Calculate time distribution preview
  const getTimeDistribution = () => {
    if (!formData.totalDuration || totalSelectedArea === 0) return [];
    
    return selectedZones.map(zone => {
      const proportion = zone.area / totalSelectedArea;
      const allocatedTime = Math.round(formData.totalDuration! * proportion);
      return {
        zone,
        proportion: proportion * 100,
        allocatedTime
      };
    });
  };

  const timeDistribution = getTimeDistribution();

  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-4xl w-full 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 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' ? 'Сеанс массового подравнивания' : 'Сеанс массового покоса'}
            </h2>
            <p className="text-sm text-gray-600 mt-1">
              {activityType === 'trimming'
                  ? 'Выберите несколько зон, обрезанных за один сеанс (сдвиг скашивания на одну неделю в каждой зоне).'
                  : 'Выберите несколько зон, скошенных за один сеанс'
              }
            </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">
          {/* Zone Selection */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-3">
              Выберите скошенные зоны ({formData.selectedZoneIds.length} выбрано)
            </label>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3 max-h-60 overflow-y-auto border rounded-lg p-3">
              {zones.map(zone => (
                <div
                  key={zone.id}
                  className={`relative border rounded-lg p-3 cursor-pointer transition-all duration-200 ${
                    formData.selectedZoneIds.includes(zone.id)
                      ? 'border-green-500 bg-green-50 ring-2 ring-green-200'
                      : `${getZoneStatusColor(zone)} hover:border-gray-300`
                  }`}
                  onClick={() => handleZoneToggle(zone.id)}
                >
                  <div className="flex items-start justify-between">
                    <div className="flex-1">
                      <h4 className="font-medium text-gray-900">{zone.name}</h4>
                      <p className="text-xs text-gray-600 mt-1">
                        {getZoneStatusText(zone)}
                      </p>
                      <div className="flex items-center gap-2 mt-2 text-xs text-gray-500">
                        <Square className="h-3 w-3" />
                        <span>{zone.area.toLocaleString()} м2</span>
                      </div>
                    </div>
                    {formData.selectedZoneIds.includes(zone.id) && (
                      <CheckCircle className="h-5 w-5 text-green-600 flex-shrink-0" />
                    )}
                  </div>
                </div>
              ))}
            </div>
            {formData.selectedZoneIds.length > 0 && (
              <div className="mt-3 p-3 bg-blue-50 rounded-md">
                <p className="text-sm text-blue-800">
                  <strong>Выбрано:</strong> {selectedZones.map(z => z.name).join(', ')}
                  <span className="ml-2">
                    (Общая площадь: {totalSelectedArea.toLocaleString()} м2)
                  </span>
                </p>
              </div>
            )}
          </div>

          {/* Session Details */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-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>
              )}
            </div>

            {/* Total Duration */}
            <div>
              <label htmlFor="totalDuration" 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="totalDuration"
                value={formData.totalDuration || ''}
                onChange={(e) => setFormData(prev => ({ 
                  ...prev, 
                  totalDuration: 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="например, 90"
              />
              <p className="text-xs text-gray-500 mt-1">
                Время будет распределено пропорционально площади зоны
              </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'
                    ? "Заметки о сеансе подравнивания..."
                    : "Заметки о сеансе кошения..."
                }
              />
            </div>
          </div>

          {/* Time Distribution Preview */}
          {timeDistribution.length > 0 && formData.totalDuration && (
            <div className="bg-gray-50 rounded-lg p-4">
              <h4 className="text-sm font-medium text-gray-900 mb-3 flex items-center gap-2">
                <Timer className="h-4 w-4" />
                {activityType === 'trimming' ? 'Подравнивание' : 'Покос'} Time Distribution Preview
              </h4>
              <div className="space-y-2">
                {timeDistribution.map(({ zone, proportion, allocatedTime }) => (
                  <div key={zone.id} className="flex items-center justify-between text-sm">
                    <div className="flex items-center gap-2">
                      <span className="font-medium">{zone.name}</span>
                      <span className="text-gray-500">
                        ({zone.area.toLocaleString()} м2)
                      </span>
                    </div>
                    <div className="flex items-center gap-2">
                      <div className="w-20 bg-gray-200 rounded-full h-2">
                        <div 
                          className="bg-green-500 h-2 rounded-full"
                          style={{ width: `${proportion}%` }}
                        ></div>
                      </div>
                      <span className="font-medium text-gray-900 w-12 text-right">
                        {allocatedTime}м
                      </span>
                    </div>
                  </div>
                ))}
              </div>
              <div className="mt-3 pt-3 border-t border-gray-200 flex justify-between text-sm font-medium">
                <span>Всего:</span>
                <span>{formData.totalDuration}м</span>
              </div>
            </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 || formData.selectedZoneIds.length === 0}
              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 
                ? 'Запись сессии...'
                : `Запись ${activityType === 'trimming' ? 'Подравнивания' : 'Кошения'} сессии (${formData.selectedZoneIds.length} зон)`
              }
            </button>
          </div>
        </form>
      </div>
    </div>
  );
};

export default BulkMowingModal;