import React, { useState, useEffect } from 'react';
import { Fertilizer } from '../types';
import { Plus, Search, Edit, Trash2, Sprout } from 'lucide-react';
import FertilizerForm from './FertilizerForm';
import { apiService } from '../services/api';

const FertilizerRegistry: React.FC = () => {
  const [fertilizers, setFertilizers] = useState<Fertilizer[]>([]);
  const [showForm, setShowForm] = useState(false);
  const [editingFertilizer, setEditingFertilizer] = useState<Fertilizer | null>(null);
  const [searchTerm, setSearchTerm] = useState('');
  const [filterType, setFilterType] = useState('all');
  const [loading, setLoading] = useState(true);

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

  const loadFertilizers = async () => {
    try {
      setLoading(true);
      const data = await apiService.getFertilizers();
      setFertilizers(data);
    } catch (error) {
      console.error('Error loading fertilizers:', error);
    } finally {
      setLoading(false);
    }
  };

  const filteredFertilizers = fertilizers.filter(fertilizer => {
    const matchesSearch = fertilizer.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         (fertilizer.brand && fertilizer.brand.toLowerCase().includes(searchTerm.toLowerCase()));
    const matchesType = filterType === 'all' || fertilizer.type === filterType;
    
    return matchesSearch && matchesType;
  });

  const handleSaveFertilizer = async (fertilizerData: Omit<Fertilizer, 'id' | 'createdAt' | 'updatedAt'>) => {
    try {
      if (editingFertilizer) {
        const updatedFertilizer = await apiService.updateFertilizer(editingFertilizer.id, fertilizerData);
        setFertilizers(fertilizers.map(f => f.id === editingFertilizer.id ? updatedFertilizer : f));
      } else {
        const newFertilizer = await apiService.createFertilizer(fertilizerData);
        setFertilizers([...fertilizers, newFertilizer]);
      }
      setShowForm(false);
      setEditingFertilizer(null);
    } catch (error) {
      console.error('Error saving fertilizer:', error);
    }
  };

  const handleDeleteFertilizer = async (fertilizerId: number) => {
    if (window.confirm('Are you sure you want to delete this fertilizer?')) {
      try {
        await apiService.deleteFertilizer(fertilizerId);
        setFertilizers(fertilizers.filter(f => f.id !== fertilizerId));
      } catch (error) {
        console.error('Error deleting fertilizer:', error);
      }
    }
  };

  const getTypeColor = (type: string) => {
    switch (type) {
      case 'organic': return 'bg-green-100 text-green-800';
      case 'synthetic': return 'bg-blue-100 text-blue-800';
      case 'liquid': return 'bg-cyan-100 text-cyan-800';
      case 'granular': return 'bg-yellow-100 text-yellow-800';
      case 'slow-release': return 'bg-purple-100 text-purple-800';
      default: return 'bg-gray-100 text-gray-800';
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center py-12">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-green-600"></div>
      </div>
    );
  }

  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={() => setShowForm(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 gap-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">Search</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="Search fertilizers..."
                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">Type</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">All Types</option>
              <option value="organic">Органическое</option>
              <option value="synthetic">Синтетическое</option>
              <option value="liquid">Жидкое</option>
              <option value="granular">Гранулированное</option>
              <option value="slow-release">Медленного действия</option>
            </select>
          </div>
        </div>
      </div>

      {/* Fertilizers Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {filteredFertilizers.map((fertilizer) => (
          <div key={fertilizer.id} className="bg-white rounded-lg shadow-sm border border-green-100 hover:shadow-md transition-shadow">
            <div className="p-6">
              <div className="flex justify-between items-start mb-4">
                <div className="flex items-center space-x-3">
                  <div className="bg-green-100 p-2 rounded-lg">
                    <Sprout className="h-5 w-5 text-green-600" />
                  </div>
                  <div>
                    <h3 className="text-lg font-semibold text-gray-900">{fertilizer.name}</h3>
                    {fertilizer.brand && (
                      <p className="text-sm text-gray-600">{fertilizer.brand}</p>
                    )}
                  </div>
                </div>
                <div className="flex space-x-2">
                  <button
                    onClick={() => {
                      setEditingFertilizer(fertilizer);
                      setShowForm(true);
                    }}
                    className="p-1 text-blue-600 hover:text-blue-700 transition-colors"
                  >
                    <Edit className="h-4 w-4" />
                  </button>
                  <button
                    onClick={() => handleDeleteFertilizer(fertilizer.id)}
                    className="p-1 text-red-600 hover:text-red-700 transition-colors"
                  >
                    <Trash2 className="h-4 w-4" />
                  </button>
                </div>
              </div>

              <div className="space-y-3">
                <div className="flex items-center justify-between">
                  <span className="text-sm text-gray-600">Type:</span>
                  <span className={`px-2 py-1 rounded-full text-xs font-medium ${getTypeColor(fertilizer.type)}`}>
                    {fertilizer.type}
                  </span>
                </div>

                {fertilizer.npkRatio && (
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-gray-600">NPK Ratio:</span>
                    <span className="text-sm font-medium text-gray-900">{fertilizer.npkRatio}</span>
                  </div>
                )}

                {fertilizer.applicationRate && (
                  <div>
                    <span className="text-sm text-gray-600">Норма расхода:</span>
                    <p className="text-sm text-gray-900 mt-1">{fertilizer.applicationRate}</p>
                  </div>
                )}

                {fertilizer.frequency && (
                  <div>
                    <span className="text-sm text-gray-600">Как часто применять:</span>
                    <p className="text-sm text-gray-900 mt-1">{fertilizer.frequency}</p>
                  </div>
                )}

                {fertilizer.season && (
                  <div>
                    <span className="text-sm text-gray-600">Время года:</span>
                    <p className="text-sm text-gray-900 mt-1">{fertilizer.season}</p>
                  </div>
                )}

                {fertilizer.description && (
                  <div className="border-t pt-3">
                    <span className="text-sm text-gray-600">Описание:</span>
                    <p className="text-sm text-gray-700 mt-1">{fertilizer.description}</p>
                  </div>
                )}

                {fertilizer.notes && (
                  <div className="border-t pt-3">
                    <span className="text-sm text-gray-600">Заметки:</span>
                    <p className="text-sm text-gray-700 mt-1">{fertilizer.notes}</p>
                  </div>
                )}
              </div>
            </div>
          </div>
        ))}
      </div>

      {filteredFertilizers.length === 0 && (
        <div className="text-center py-12">
          <p className="text-gray-500 text-lg">No fertilizers found.</p>
          <button
            onClick={() => setShowForm(true)}
            className="mt-4 text-green-600 hover:text-green-700 transition-colors"
          >
            Добавте первую запись о удобрении →
          </button>
        </div>
      )}

      {/* Fertilizer Form Modal */}
      {showForm && (
        <FertilizerForm
          fertilizer={editingFertilizer}
          onSave={handleSaveFertilizer}
          onCancel={() => {
            setShowForm(false);
            setEditingFertilizer(null);
          }}
        />
      )}
    </div>
  );
};

export default FertilizerRegistry;