import React, { useState } from 'react';
import { Plant, MaintenanceRecord, Maintenances } from '../types';
import { Plus, Calendar, Search, Scissors, Droplets, Beaker, Sprout } from 'lucide-react';
import MaintenanceForm from './MaintenanceForm';
import { apiService } from '../services/api';

interface MaintenanceLogProps {
  maintenanceRecords: MaintenanceRecord[];
  plants: Plant[];
  onMaintenanceChange: (records: MaintenanceRecord[]) => void;
}

const MaintenanceLog: React.FC<MaintenanceLogProps> = ({ 
  maintenanceRecords, 
  plants, 
  onMaintenanceChange 
}) => {
  const [showMaintenanceForm, setShowMaintenanceForm] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const [filterType, setFilterType] = useState('all');
  const [filterPlant, setFilterPlant] = useState('all');

  const filteredRecords = maintenanceRecords.filter(record => {
    const plant = plants.find(p => p.id === record.plantId);
    const matchesSearch = record.description.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         (plant?.variety.toLowerCase().includes(searchTerm.toLowerCase()));
    const matchesType = filterType === 'all' || record.type === filterType;
    const matchesPlant = filterPlant === 'all' || record.plantId.toString() === filterPlant;
    
    return matchesSearch && matchesType && matchesPlant;
  }).sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());

  const handleSaveMaintenance = async (maintenanceData: Omit<MaintenanceRecord, 'id' | 'createdAt' | 'updatedAt'>) => {
    try {
      const newRecord = await apiService.createMaintenanceRecord(maintenanceData);
      onMaintenanceChange([...maintenanceRecords, newRecord]);
      setShowMaintenanceForm(false);
    } catch (error) {
      console.error('Error saving maintenance record:', error);
    }
  };

  const getMaintenanceIcon = (type: string) => {
    switch (type) {
      case 'chemical': return Beaker;
      case 'fertilizer': return Sprout;
      case 'watering': return Droplets;
      case 'pruning': return Scissors;
      case 'transplanting': return Sprout;
      default: return Calendar;
    }
  };

  const getTypeColor = (type: string) => {
    switch (type) {
      case 'chemical': return 'bg-red-100 text-red-800';
      case 'fertilizer': return 'bg-green-100 text-green-800';
      case 'watering': return 'bg-blue-100 text-blue-800';
      case 'pruning': return 'bg-yellow-100 text-yellow-800';
      case 'transplanting': return 'bg-purple-100 text-purple-800';
      default: return 'bg-gray-100 text-gray-800';
    }
  };

  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={() => setShowMaintenanceForm(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-3 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={filterType}
              onChange={(e) => setFilterType(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>
              <option value="chemical">Химическая обработка</option>
              <option value="fertilizer">Удобрение</option>
              <option value="watering">Полив</option>
              <option value="pruning">Обрезка</option>
              <option value="transplanting">Пересадка</option>
              <option value="other">Другое</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>
      </div>

      {/* Maintenance Records */}
      <div className="space-y-4">
        {filteredRecords.map((record) => {
          const plant = plants.find(p => p.id === record.plantId);
          const Icon = getMaintenanceIcon(record.type);

          return (
            <div key={record.id} className="bg-white rounded-lg shadow-sm border border-green-100 p-6 hover:shadow-md transition-shadow">
              <div className="flex items-start space-x-4">
                <div className="bg-green-100 p-3 rounded-lg">
                  <Icon className="h-6 w-6 text-green-600" />
                </div>

                <div className="flex-1 min-w-0">
                  <div className="flex items-center justify-between mb-2">
                    <div className="flex items-center space-x-3">
                      <h3 className="text-lg font-semibold text-gray-900 capitalize">{Maintenances[record.type]}</h3>
                      <span className={`px-2 py-1 rounded-full text-xs font-medium ${getTypeColor(record.type)}`}>
                         {Maintenances[record.type]}
                      </span>
                      {record.fertilizerName && (
                          <span className="px-2 py-1 bg-green-200 text-green-800 text-xs rounded-full">
                          {record.fertilizerName}
                        </span>
                      )}
                      {record.chemicalName && (
                          <span className="px-2 py-1 bg-red-200 text-red-800 text-xs rounded-full">
                          {record.chemicalName}
                        </span>
                      )}
                    </div>
                    <span className="text-sm text-gray-500">
                      {new Date(record.date).toLocaleDateString()}
                    </span>
                  </div>

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

                  <p className="text-gray-700 mb-2">{record.description}</p>

                  {record.amount && (
                    <p className="text-sm text-gray-600">
                      Количество: <span className="font-medium">{record.amount}</span>
                    </p>
                  )}
                </div>
              </div>
            </div>
          );
        })}
      </div>

      {filteredRecords.length === 0 && (
        <div className="text-center py-12">
          <p className="text-gray-500 text-lg">Записей о работах не найдено.</p>
          <button
            onClick={() => setShowMaintenanceForm(true)}
            className="mt-4 text-green-600 hover:text-green-700 transition-colors"
          >
            Записать свое первое действие в журнал →
          </button>
        </div>
      )}

      {/* Maintenance Form Modal */}
      {showMaintenanceForm && (
        <MaintenanceForm
          plants={plants}
          onSave={handleSaveMaintenance}
          onCancel={() => setShowMaintenanceForm(false)}
        />
      )}
    </div>
  );
};

export default MaintenanceLog;