import React, { useState, useEffect } from 'react';
import { X, Sun, Snowflake, Settings } from './Icons';
import { SeasonSettings } from '../types/zone';
import { api } from '../services/api';

interface SeasonSettingsProps {
  onClose: () => void;
}

const SeasonSettingsComponent: React.FC<SeasonSettingsProps> = ({ onClose }) => {
  const [settings, setSettings] = useState<SeasonSettings>({
    startMonth: 5,
    startDay: 1,
    endMonth: 9,
    endDay: 30,
    isActive: true,
  });
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);

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

  const loadSettings = async () => {
    try {
      const data = await api.getSeasonSettings();
      setSettings(data);
    } catch (error) {
      console.error('Failed to load season settings:', error);
      // Use default settings if none exist
    } finally {
      setLoading(false);
    }
  };

  const handleSave = async () => {
    setSaving(true);
    setError(null);

    // Validation
    if (settings.startMonth < 1 || settings.startMonth > 12 ||
        settings.endMonth < 1 || settings.endMonth > 12) {
      setError('Months must be between 1 and 12');
      setSaving(false);
      return;
    }

    if (settings.startDay < 1 || settings.startDay > 31 ||
        settings.endDay < 1 || settings.endDay > 31) {
      setError('Days must be between 1 and 31');
      setSaving(false);
      return;
    }

    try {
      await api.updateSeasonSettings(settings);
      onClose();
    } catch (error) {
      setError(error instanceof Error ? error.message : 'Failed to save settings');
    } finally {
      setSaving(false);
    }
  };

  const monthNames = [
    'Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь',
    'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'
  ];

  const formatDate = (month: number, day: number) => {
    return `${monthNames[month - 1]} ${day}`;
  };

  const isCurrentlyInSeason = () => {
    const now = new Date();
    const currentMonth = now.getMonth() + 1;
    const currentDay = now.getDate();

    const startDate = new Date(now.getFullYear(), settings.startMonth - 1, settings.startDay);
    const endDate = new Date(now.getFullYear(), settings.endMonth - 1, settings.endDay);
    const currentDate = new Date(now.getFullYear(), currentMonth - 1, currentDay);

    if (startDate <= endDate) {
      // Same year season
      return currentDate >= startDate && currentDate <= endDate;
    } else {
      // Cross-year season (e.g., Nov to Mar)
      return currentDate >= startDate || currentDate <= endDate;
    }
  };

  if (loading) {
    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 p-8">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-green-600 mx-auto"></div>
          </div>
        </div>
    );
  }

  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">
            <h2 className="text-xl font-semibold text-gray-900 flex items-center gap-2">
              <Settings className="h-6 w-6 text-green-600" />
              Настройки сезона покосов
            </h2>
            <button
                onClick={onClose}
                className="text-gray-400 hover:text-gray-600 transition-colors duration-200"
            >
              <X className="h-6 w-6" />
            </button>
          </div>

          <div className="p-6 space-y-6">
            {error && (
                <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-md">
                  {error}
                </div>
            )}

            {/* Season Status */}
            <div className={`p-4 rounded-lg border ${
                settings.isActive && isCurrentlyInSeason()
                    ? 'bg-green-50 border-green-200'
                    : 'bg-gray-50 border-gray-200'
            }`}>
              <div className="flex items-center gap-3">
                {settings.isActive && isCurrentlyInSeason() ? (
                    <Sun className="h-6 w-6 text-green-600" />
                ) : (
                    <Snowflake className="h-6 w-6 text-gray-600" />
                )}
                <div>
                  <h3 className="font-medium text-gray-900">
                    {settings.isActive && isCurrentlyInSeason() ? 'Сезон' : 'Не сезон'}
                  </h3>
                  <p className="text-sm text-gray-600">
                    {settings.isActive && isCurrentlyInSeason()
                        ? 'Активны графики скашивания'
                        : 'All zones are considered maintained'
                    }
                  </p>
                </div>
              </div>
            </div>

            {/* Enable/Disable Season */}
            <div>
              <label className="flex items-center">
                <input
                    type="checkbox"
                    checked={settings.isActive}
                    onChange={(e) => setSettings(prev => ({ ...prev, isActive: e.target.checked }))}
                    className="mr-3 text-green-600 focus:ring-green-500"
                />
                <span className="text-sm font-medium text-gray-700">
                Включить сезон скашивания (отключить, чтобы обеспечить круглогодичный уход за всеми зонами)
              </span>
              </label>
            </div>

            {settings.isActive && (
                <>
                  {/* Season Start */}
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-3">
                      Начало сезона
                    </label>
                    <div className="grid grid-cols-2 gap-3">
                      <div>
                        <label className="block text-xs text-gray-500 mb-1">Месяц</label>
                        <select
                            value={settings.startMonth}
                            onChange={(e) => setSettings(prev => ({ ...prev, startMonth: parseInt(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"
                        >
                          {monthNames.map((month, index) => (
                              <option key={index} value={index + 1}>{month}</option>
                          ))}
                        </select>
                      </div>
                      <div>
                        <label className="block text-xs text-gray-500 mb-1">День</label>
                        <input
                            type="number"
                            min="1"
                            max="31"
                            value={settings.startDay}
                            onChange={(e) => setSettings(prev => ({ ...prev, startDay: parseInt(e.target.value) || 1 }))}
                            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>
                    <p className="text-xs text-gray-500 mt-1">
                      Сезон начинается: {formatDate(settings.startMonth, settings.startDay)}
                    </p>
                  </div>

                  {/* Season End */}
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-3">
                      Конец сезона
                    </label>
                    <div className="grid grid-cols-2 gap-3">
                      <div>
                        <label className="block text-xs text-gray-500 mb-1">Месяц</label>
                        <select
                            value={settings.endMonth}
                            onChange={(e) => setSettings(prev => ({ ...prev, endMonth: parseInt(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"
                        >
                          {monthNames.map((month, index) => (
                              <option key={index} value={index + 1}>{month}</option>
                          ))}
                        </select>
                      </div>
                      <div>
                        <label className="block text-xs text-gray-500 mb-1">День</label>
                        <input
                            type="number"
                            min="1"
                            max="31"
                            value={settings.endDay}
                            onChange={(e) => setSettings(prev => ({ ...prev, endDay: parseInt(e.target.value) || 1 }))}
                            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>
                    <p className="text-xs text-gray-500 mt-1">
                      Сезон завершается: {formatDate(settings.endMonth, settings.endDay)}
                    </p>
                  </div>

                  {/* Season Info */}
                  <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
                    <h4 className="text-sm font-medium text-blue-900 mb-2">Как это работает:</h4>
                    <ul className="text-sm text-blue-800 space-y-1">
                      <li>• В течение сезона: применяется обычный график скашивания</li>
                      <li>• Межсезонье: Все зоны отображаются как "обслуженные"</li>
                      <li>• Запись скашивания/подравнивание по-прежнему может производиться круглый год</li>
                      <li>• Уведомления отправляются только в активный сезон</li>
                    </ul>
                  </div>
                </>
            )}
          </div>

          <div className="flex gap-3 p-6 border-t">
            <button
                type="button"
                onClick={onClose}
                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
                onClick={handleSave}
                disabled={saving}
                className="flex-1 py-2 px-4 bg-green-600 text-white rounded-md hover:bg-green-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors duration-200"
            >
              {saving ? 'Сохранение...' : 'Сохранить настройки'}
            </button>
          </div>
        </div>
      </div>
  );
};

export default SeasonSettingsComponent;