import React, { useState, useEffect } from 'react';
import { Chemical } from '../types';
import { Plus, Search, Edit, Trash2, Beaker } from 'lucide-react';
import ChemicalForm from './ChemicalForm';
import { apiService } from '../services/api';

const ChemicalRegistry: React.FC = () => {
  const [chemicals, setChemicals] = useState<Chemical[]>([]);
  const [showForm, setShowForm] = useState(false);
  const [editingChemical, setEditingChemical] = useState<Chemical | null>(null);
  const [searchTerm, setSearchTerm] = useState('');
  const [filterType, setFilterType] = useState('all');
  const [loading, setLoading] = useState(true);

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

  const loadChemicals = async () => {
    try {
      setLoading(true);
      const data = await apiService.getChemicals();
      setChemicals(data);
    } catch (error) {
      console.error('Error loading chemicals:', error);
    } finally {
      setLoading(false);
    }
  };

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

  const handleSaveChemical = async (chemicalData: Omit<Chemical, 'id' | 'createdAt' | 'updatedAt'>) => {
    try {
      if (editingChemical) {
        const updatedChemical = await apiService.updateChemical(editingChemical.id, chemicalData);
        setChemicals(chemicals.map(c => c.id === editingChemical.id ? updatedChemical : c));
      } else {
        const newChemical = await apiService.createChemical(chemicalData);
        setChemicals([...chemicals, newChemical]);
      }
      setShowForm(false);
      setEditingChemical(null);
    } catch (error) {
      console.error('Error saving chemical:', error);
    }
  };

  const handleDeleteChemical = async (chemicalId: number) => {
    if (window.confirm('Are you sure you want to delete this chemical?')) {
      try {
        await apiService.deleteChemical(chemicalId);
        setChemicals(chemicals.filter(c => c.id !== chemicalId));
      } catch (error) {
        console.error('Error deleting chemical:', error);
      }
    }
  };

  const getTypeColor = (type: string) => {
    switch (type) {
      case 'pesticide': return 'bg-red-100 text-red-800';
      case 'herbicide': return 'bg-orange-100 text-orange-800';
      case 'fungicide': return 'bg-yellow-100 text-yellow-800';
      case 'insecticide': return 'bg-blue-100 text-blue-800';
      case 'miticide': 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">Chemical Registry</h2>
          <p className="text-green-600 mt-1">Manage your chemical inventory and safety information</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 chemicals..."
                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="pesticide">Pesticide</option>
              <option value="herbicide">Herbicide</option>
              <option value="fungicide">Fungicide</option>
              <option value="insecticide">Insecticide</option>
              <option value="miticide">Miticide</option>
            </select>
          </div>
        </div>
      </div>

      {/* Chemicals Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {filteredChemicals.map((chemical) => (
          <div key={chemical.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-red-100 p-2 rounded-lg">
                    <Beaker className="h-5 w-5 text-red-600" />
                  </div>
                  <div>
                    <h3 className="text-lg font-semibold text-gray-900">{chemical.name}</h3>
                    {chemical.brand && (
                      <p className="text-sm text-gray-600">{chemical.brand}</p>
                    )}
                  </div>
                </div>
                <div className="flex space-x-2">
                  <button
                    onClick={() => {
                      setEditingChemical(chemical);
                      setShowForm(true);
                    }}
                    className="p-1 text-blue-600 hover:text-blue-700 transition-colors"
                  >
                    <Edit className="h-4 w-4" />
                  </button>
                  <button
                    onClick={() => handleDeleteChemical(chemical.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(chemical.type)}`}>
                    {chemical.type}
                  </span>
                </div>

                {chemical.activeIngredient && (
                  <div>
                    <span className="text-sm text-gray-600">Активные ингредиенты:</span>
                    <p className="text-sm text-gray-900 mt-1">{chemical.activeIngredient}</p>
                  </div>
                )}

                {chemical.concentration && (
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-gray-600">Концентрация:</span>
                    <span className="text-sm font-medium text-gray-900">{chemical.concentration}</span>
                  </div>
                )}

                {chemical.targetPests && (
                  <div>
                    <span className="text-sm text-gray-600">Потив вредителей:</span>
                    <p className="text-sm text-gray-900 mt-1">{chemical.targetPests}</p>
                  </div>
                )}

                {chemical.applicationMethod && (
                  <div>
                    <span className="text-sm text-gray-600">Application:</span>
                    <p className="text-sm text-gray-900 mt-1">{chemical.applicationMethod}</p>
                  </div>
                )}

                {chemical.safetyPeriod && (
                  <div className="bg-yellow-50 p-3 rounded-lg">
                    <span className="text-sm font-medium text-yellow-800">Безопасный период:</span>
                    <p className="text-sm text-yellow-700 mt-1">{chemical.safetyPeriod} days</p>
                  </div>
                )}

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

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

      {/* Chemical Form Modal */}
      {showForm && (
        <ChemicalForm
          chemical={editingChemical}
          onSave={handleSaveChemical}
          onCancel={() => {
            setShowForm(false);
            setEditingChemical(null);
          }}
        />
      )}
    </div>
  );
};

export default ChemicalRegistry;