import React, { useState } from 'react';
import { Plant, PlantObservation } from '../types';
import { Plus, Search, Edit, Trash2, Thermometer, Cloud, Tag } from 'lucide-react';
import ObservationForm from './ObservationForm';
import { apiService } from '../services/api';
import { ImagePreview } from "./utils/ImagePreview";

interface ObservationJournalProps {
  observations: PlantObservation[];
  plants: Plant[];
  onObservationsChange: (observations: PlantObservation[]) => void;
}

const ObservationJournal: React.FC<ObservationJournalProps> = ({ 
  observations, 
  plants, 
  onObservationsChange 
}) => {
  const [showObservationForm, setShowObservationForm] = useState(false);
  const [editingObservation, setEditingObservation] = useState<PlantObservation | null>(null);
  const [searchTerm, setSearchTerm] = useState('');
  const [filterPlant, setFilterPlant] = useState('all');
  const [filterTag, setFilterTag] = useState('all');
  const [filterYear, setFilterYear] = useState('all');
  const [filterMonth, setFilterMonth] = useState('all');

  const filteredObservations = observations.filter(observation => {
    const plant = plants.find(p => p.id === observation.plantId);
    const observationDate = new Date(observation.date);

    const matchesSearch = observation.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         observation.observation.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         (plant?.variety.toLowerCase().includes(searchTerm.toLowerCase()));
    const matchesPlant = filterPlant === 'all' || observation.plantId.toString() === filterPlant;
    const matchesTag = filterTag === 'all' || (observation.tags && observation.tags.includes(filterTag));

    const matchesYear = filterYear === 'all' || observationDate.getFullYear().toString() === filterYear;
    const matchesMonth = filterMonth === 'all' || (observationDate.getMonth() + 1).toString() === filterMonth;

    return matchesSearch && matchesPlant && matchesTag && matchesYear && matchesMonth;
  }).sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());

  const allTags = Array.from(new Set(
    observations
      .filter(obs => obs.tags)
      .flatMap(obs => obs.tags!.split(',').map(tag => tag.trim()))
  )).sort();

  // Get available years from observations
  const availableYears = Array.from(new Set(
      observations.map(obs => new Date(obs.date).getFullYear())
  )).sort((a, b) => b - a);

  // Month options
  const months = [
    { value: '1', label: 'Январь' },
    { value: '2', label: 'Февраль' },
    { value: '3', label: 'Март' },
    { value: '4', label: 'Апрель' },
    { value: '5', label: 'Май' },
    { value: '6', label: 'Июнь' },
    { value: '7', label: 'Июль' },
    { value: '8', label: 'Август' },
    { value: '9', label: 'Сентябрь' },
    { value: '10', label: 'Октябрь' },
    { value: '11', label: 'Ноябрь' },
    { value: '12', label: 'Декабрь' }
  ];

  const handleSaveObservation = async (observationData: Omit<PlantObservation, 'id' | 'createdAt' | 'updatedAt'>) => {
    try {
      if (editingObservation) {
        const updatedObservation = await apiService.updatePlantObservation(editingObservation.id, observationData);
        onObservationsChange(observations.map(o => o.id === editingObservation.id ? updatedObservation : o));
      } else {
        const newObservation = await apiService.createPlantObservation(observationData);
        onObservationsChange([...observations, newObservation]);
      }
      setShowObservationForm(false);
      setEditingObservation(null);
    } catch (error) {
      console.error('Error saving observation:', error);
    }
  };

  const handleDeleteObservation = async (observationId: number) => {
    if (window.confirm('Are you sure you want to delete this observation?')) {
      try {
        await apiService.deletePlantObservation(observationId);
        onObservationsChange(observations.filter(o => o.id !== observationId));
      } catch (error) {
        console.error('Error deleting observation:', error);
      }
    }
  };

  const formatTags = (tags: string) => {
    return tags.split(',').map(tag => tag.trim());
  };

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <div>
          <h2 className="text-3xl font-bold text-green-800">Дневник наблюдений</h2>
          <p className="text-green-600 mt-1">Ежедневные заметки и наблюдения за вашими растениями</p>
        </div>
        <button
          onClick={() => setShowObservationForm(true)}
          className="bg-green-600 hover:bg-green-700 text-white px-4 py-2 rounded-lg flex items-center space-x-2 transition-colors"
        >
          <Plus className="h-4 w-4" />
          <span>Наблюдение</span>
        </button>
      </div>

      {/* Filters */}
      <div className="bg-white p-6 rounded-lg shadow-sm border border-green-100">
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">Поиск</label>
            <div className="relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
              <input
                type="text"
                placeholder="Поиск по наблюдениям..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="pl-10 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>
            <select
                value={filterYear}
                onChange={(e) => setFilterYear(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="all">Все</option>
              {availableYears.map(year => (
                  <option key={year} value={year.toString()}>
                    {year}
                  </option>
              ))}
            </select>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">Месяц</label>
            <select
                value={filterMonth}
                onChange={(e) => setFilterMonth(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="all">Все</option>
              {months.map(month => (
                  <option key={month.value} value={month.value}>
                    {month.label}
                  </option>
              ))}
            </select>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">Растения</label>
            <select
              value={filterPlant}
              onChange={(e) => setFilterPlant(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="all">Все растения</option>
              {plants.map(plant => (
                <option key={plant.id} value={plant.id}>
                  {plant.variety}
                </option>
              ))}
            </select>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">Тег</label>
            <select
              value={filterTag}
              onChange={(e) => setFilterTag(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="all">Все теги</option>
              {allTags.map(tag => (
                <option key={tag} value={tag}>
                  {tag}
                </option>
              ))}
            </select>
          </div>
        </div>
      </div>

      {/* Observations List */}
      <div className="space-y-4">
        {filteredObservations.map((observation) => {
          const plant = plants.find(p => p.id === observation.plantId);

          return (
              <div
                  key={observation.id}
                  className="bg-white rounded-lg shadow-sm border border-green-100 p-6 hover:shadow-md transition-shadow"
              >
                <div className="flex items-start">
                  {/* Левая часть — картинка */}
                  {observation.photoUrl && (
                      <div className="w-40 h-40 flex-shrink-0 mr-6">
                        <ImagePreview
                            thumbnailSrc={observation.photoUrl.startsWith('/uploads')
                                ? `${import.meta.env.VITE_API_URL || '/api'}${observation.photoUrl}`.replace('/api/uploads', '/uploads')
                                : observation.photoUrl
                            }

                            fullSrc={observation.photoUrl.startsWith('/uploads')
                                ? `${import.meta.env.VITE_API_URL || '/api'}${observation.photoUrl}`.replace('/api/uploads', '/uploads')
                                : observation.photoUrl
                            }

                            alt={observation.title}
                            className="w-32 h-32 object-cover cursor-pointer rounded shadow"
                        />
                      </div>
                  )}

                  {/* Правая часть — текст */}
                  <div className="flex-1">
                    <div className="flex items-center justify-between mb-2">
                      <h3 className="text-lg font-semibold text-gray-900">{observation.title}</h3>
                      <span className="text-sm text-gray-500">
                          {new Date(observation.date).toLocaleDateString()}
                      </span>
                    </div>

                    {plant && (
                        <p className="text-sm text-gray-600 mb-3">
                          Растение: <span className="font-medium">{plant.variety}</span>
                        </p>
                    )}

                    <p className="text-gray-700 mb-4 leading-relaxed">{observation.observation}</p>

                    <div className="flex flex-wrap items-center gap-4 text-sm text-gray-600">
                      {observation.weatherConditions && (
                          <div className="flex items-center space-x-1">
                            <Cloud className="h-4 w-4" />
                            <span>{observation.weatherConditions}</span>
                          </div>
                      )}

                      {observation.temperature && (
                          <div className="flex items-center space-x-1">
                            <Thermometer className="h-4 w-4" />
                            <span>{observation.temperature}°C</span>
                          </div>
                      )}
                    </div>

                    {observation.tags && (
                        <div className="flex items-center space-x-2 mt-3">
                          <Tag className="h-4 w-4 text-gray-400" />
                          <div className="flex flex-wrap gap-1">
                            {formatTags(observation.tags).map((tag, index) => (
                                <span
                                    key={index}
                                    className="px-2 py-1 bg-green-100 text-green-700 text-xs rounded-full"
                                >
                    {tag}
                  </span>
                            ))}
                          </div>
                        </div>
                    )}
                  </div>

                  {/* Кнопки справа */}
                  <div className="flex space-x-2 ml-4">
                    <button
                        onClick={() => {
                          setEditingObservation(observation);
                          setShowObservationForm(true);
                        }}
                        className="p-1 text-blue-600 hover:text-blue-700 transition-colors"
                    >
                      <Edit className="h-4 w-4" />
                    </button>
                    <button
                        onClick={() => handleDeleteObservation(observation.id)}
                        className="p-1 text-red-600 hover:text-red-700 transition-colors"
                    >
                      <Trash2 className="h-4 w-4" />
                    </button>
                  </div>
                </div>
              </div>
          );
        })}
      </div>

      {filteredObservations.length === 0 && (
        <div className="text-center py-12">
          <p className="text-gray-500 text-lg">
            {searchTerm || filterYear !== 'all' || filterMonth !== 'all' || filterPlant !== 'all' || filterTag !== 'all'
                ? 'No observations found matching your filters.'
                : 'No observations found.'
            }
          </p>
          <button
            onClick={() => setShowObservationForm(true)}
            className="mt-4 text-green-600 hover:text-green-700 transition-colors"
          >
            {observations.length === 0 ? 'Добавить первое наблюдение →' : 'Добавить новое наблюдение →'}
          </button>
        </div>
      )}

      {/* Observation Form Modal */}
      {showObservationForm && (
        <ObservationForm
          observation={editingObservation}
          plants={plants}
          onSave={handleSaveObservation}
          onCancel={() => {
            setShowObservationForm(false);
            setEditingObservation(null);
          }}
        />
      )}
    </div>
  );
};

export default ObservationJournal;