import React, { useState, useRef } from 'react';
import { X, Upload, Calendar, Clock } from './Icons';
import { Zone, ZoneFormData } from '../types/zone';
import { api } from '../services/api';

interface ZoneFormProps {
  zone: Zone | null;
  onSubmit: () => void;
  onCancel: () => void;
}

const APP_MODE = import.meta.env.VITE_ENV;
const API_BASE = APP_MODE == "development" ? import.meta.env.VITE_API_URL : "";

const ZoneForm: React.FC<ZoneFormProps> = ({ zone, onSubmit, onCancel }) => {
  const [formData, setFormData] = useState<ZoneFormData>({
    name: zone?.name || '',
    intervalDays: zone?.intervalDays || 7,
    lastMowedDate: zone?.lastMowedDate ? zone.lastMowedDate.split('T')[0] : '',
    nextMowDate: zone?.nextMowDate ? zone.nextMowDate.split('T')[0] : '',
    scheduleType: zone?.scheduleType || 'interval',
    area: zone?.area || 0,
  });
  const [imagePreview, setImagePreview] = useState<string | null>(
    zone?.imagePath ? `${API_BASE}${zone.imagePath}` : null
  );
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      setFormData(prev => ({ ...prev, image: file }));
      
      const reader = new FileReader();
      reader.onload = (e) => {
        setImagePreview(e.target?.result as string);
      };
      reader.readAsDataURL(file);
    }
  };

  const handleScheduleTypeChange = (scheduleType: 'interval' | 'specific') => {
    setFormData(prev => ({
      ...prev,
      scheduleType,
      // Clear the other scheduling field when switching types
      ...(scheduleType === 'interval' ? { nextMowDate: '' } : { intervalDays: undefined })
    }));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError(null);

    // Validation
    if (formData.scheduleType === 'interval' && (!formData.intervalDays || formData.intervalDays < 1)) {
      setError('Please specify a valid mowing interval (1+ days)');
      setLoading(false);
      return;
    }

    if (formData.scheduleType === 'specific' && !formData.nextMowDate) {
      setError('Please specify the next mowing date');
      setLoading(false);
      return;
    }

    try {
      if (zone) {
        await api.updateZone(zone.id, formData);
      } else {
        await api.createZone(formData);
      }
      onSubmit();
    } catch (error) {
      setError(error instanceof Error ? error.message : 'An error occurred');
    } finally {
      setLoading(false);
    }
  };

  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 max-h-[90vh] overflow-y-auto">
        <div className="flex items-center justify-between p-6 border-b">
          <h2 className="text-xl font-semibold text-gray-900">
            {zone ? 'Редактирование Зоны' : 'Создание новой Зоны'}
          </h2>
          <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">
          {error && (
            <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-md">
              {error}
            </div>
          )}

          {/* Zone Name */}
          <div>
            <label htmlFor="name" className="block text-sm font-medium text-gray-700 mb-2">
              Наименование зоны
            </label>
            <input
              type="text"
              id="name"
              value={formData.name}
              onChange={(e) => setFormData(prev => ({ ...prev, name: 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"
              required
              placeholder="например Задний Двор, Входная Зона"
            />
          </div>

          {/* Площадь */}
          <div>
            <label htmlFor="area" className="block text-sm font-medium text-gray-700 mb-2">
              Площадь (квадратные метры)
            </label>
            <input
              type="number"
              id="area"
              value={formData.area}
              onChange={(e) => setFormData(prev => ({ ...prev, area: parseFloat(e.target.value) || 0 }))}
              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="0"
              step="0.1"
              placeholder="например, 150.5"
            />
            <p className="text-xs text-gray-500 mt-1">Дополнительно - помогает отслеживать общую площадь газона</p>
          </div>

          {/* Schedule Type */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-3">
              Распасание покоса
            </label>
            <div className="space-y-3">
              <label className="flex items-center">
                <input
                    type="radio"
                    name="scheduleType"
                    value="interval"
                    checked={formData.scheduleType === 'interval'}
                    onChange={(e) => handleScheduleTypeChange(e.target.value as 'interval')}
                    className="mr-3 text-green-600 focus:ring-green-500"
                />
                <div className="flex items-center gap-2">
                  <Clock className="h-4 w-4 text-gray-500" />
                  <span className="text-sm text-gray-700">Регулярный интервал (каждые X дней)</span>
                </div>
              </label>

              <label className="flex items-center">
                <input
                    type="radio"
                    name="scheduleType"
                    value="specific"
                    checked={formData.scheduleType === 'specific'}
                    onChange={(e) => handleScheduleTypeChange(e.target.value as 'specific')}
                    className="mr-3 text-green-600 focus:ring-green-500"
                />
                <div className="flex items-center gap-2">
                  <Calendar className="h-4 w-4 text-gray-500" />
                  <span className="text-sm text-gray-700">Определенная дата</span>
                </div>
              </label>
            </div>
          </div>

          {/* Conditional Schedule Fields */}
          {formData.scheduleType === 'interval' ? (
              <div>
                <label htmlFor="intervalDays" className="block text-sm font-medium text-gray-700 mb-2">
                  Интервал покоса (дни)
                </label>
                <input
                    type="number"
                    id="intervalDays"
                    value={formData.intervalDays || ''}
                    onChange={(e) => setFormData(prev => ({ ...prev, intervalDays: 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
                    min="1"
                    max="365"
                    placeholder="например, 7"
                />
                <p className="text-xs text-gray-500 mt-1">Как часто следует косить эту зону?</p>
              </div>
          ) : (
              <div>
                <label htmlFor="nextMowDate" className="block text-sm font-medium text-gray-700 mb-2">
                  Дата следующего покоса
                </label>
                <input
                    type="date"
                    id="nextMowDate"
                    value={formData.nextMowDate || ''}
                    onChange={(e) => setFormData(prev => ({ ...prev, nextMowDate: 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"
                    required
                    min={new Date().toISOString().split('T')[0]}
                />
                <p className="text-xs text-gray-500 mt-1">When should this zone be mowed next?</p>
              </div>
          )}

          {/* Last Mowed Date (only for editing existing zones) */}
          {zone && (
              <div>
                <label htmlFor="lastMowedDate" className="block text-sm font-medium text-gray-700 mb-2">
                  Дата последнего покоса
                </label>
                <input
                    type="date"
                    id="lastMowedDate"
                    value={formData.lastMowedDate || ''}
                    onChange={(e) => setFormData(prev => ({ ...prev, lastMowedDate: 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"
                />
                <p className="text-xs text-gray-500 mt-1">Оставьте пустым, если эта зона еще не была скошена</p>
              </div>
          )}

          {/* New Zone Notice */}
          {!zone && (
              <div className="bg-blue-50 border border-blue-200 rounded-md p-3">
                <p className="text-sm text-blue-800">
                  <strong>Новая зона:</strong> Эта зона будет помечена как "еще не скошенная" до тех пор, пока вы не запишете первый выход на покос.
                </p>
              </div>
          )}

          {/* Zone Image */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              Изображение зоны (не обязательно)
            </label>
            
            {imagePreview ? (
              <div className="relative">
                <img
                  src={imagePreview}
                  alt="Zone preview"
                  className="w-full h-48 object-cover rounded-md border"
                />
                <button
                  type="button"
                  onClick={() => {
                    setImagePreview(null);
                    setFormData(prev => ({ ...prev, image: undefined }));
                    if (fileInputRef.current) {
                      fileInputRef.current.value = '';
                    }
                  }}
                  className="absolute top-2 right-2 bg-red-500 text-white p-1.5 rounded-full hover:bg-red-600 transition-colors duration-200"
                >
                  <X className="h-4 w-4" />
                </button>
              </div>
            ) : (
              <div
                onClick={() => fileInputRef.current?.click()}
                className="border-2 border-dashed border-gray-300 rounded-md p-6 text-center cursor-pointer hover:border-green-500 hover:bg-green-50 transition-colors duration-200"
              >
                <Upload className="mx-auto h-8 w-8 text-gray-400 mb-2" />
                <p className="text-sm text-gray-600">Нажмите для загрузки изображения зоны</p>
                <p className="text-xs text-gray-500 mt-1">PNG, JPG до 5MB</p>
              </div>
            )}
            
            <input
              ref={fileInputRef}
              type="file"
              accept="image/*"
              onChange={handleImageChange}
              className="hidden"
            />
          </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 bg-green-600 text-white rounded-md hover:bg-green-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors duration-200"
            >
              {loading ? 'Сохраняется...' : zone ? 'Изменить Зону' : 'Создать Зону'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
};

export default ZoneForm;