import React, { useState } from 'react';
import {Plant, HarvestRecord, PlantTitles, Conditions, HarvestUnits} from '../types';
import { Plus, Search, Edit, Trash2, Calendar, Award, BarChart3, Grid3X3, List, Package } from 'lucide-react';
import PlantForm from './PlantForm';
import HarvestForm from './HarvestForm';
import PlantStatistics from './PlantStatistics';
import { apiService } from '../services/api';
import HarvestProcessingModal from './HarvestProcessingModal';
import { ImagePreview } from "./utils/ImagePreview.tsx";

interface PlantRegistryProps {
  plants: Plant[];
  onPlantsChange: (plants: Plant[]) => void;
  harvestRecords: HarvestRecord[];
  onHarvestRecordsChange: (records: HarvestRecord[]) => void;
  maintenanceRecords: any[];
}

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

const PlantRegistry: React.FC<PlantRegistryProps> = ({ 
  plants, 
  onPlantsChange,
  harvestRecords,
  onHarvestRecordsChange,
  maintenanceRecords
}) => {
  const [showPlantForm, setShowPlantForm] = useState(false);
  const [showHarvestForm, setShowHarvestForm] = useState(false);
  const [showStatistics, setShowStatistics] = useState(false);
  const [editingPlant, setEditingPlant] = useState<Plant | null>(null);
  const [selectedPlantForHarvest, setSelectedPlantForHarvest] = useState<Plant | null>(null);
  const [selectedPlantForStats, setSelectedPlantForStats] = useState<Plant | null>(null);
  const [showProcessingModal, setShowProcessingModal] = useState(false);
  const [selectedHarvestForProcessing, setSelectedHarvestForProcessing] = useState<HarvestRecord | null>(null);
  const [searchTerm, setSearchTerm] = useState('');
  const [filterType, setFilterType] = useState('all');
  const [filterStatus, setFilterStatus] = useState('all');
  const [viewMode, setViewMode] = useState<'cards' | 'table'>('cards');

  const filteredPlants = plants.filter(plant => {
    const matchesSearch = plant.variety.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         plant.type.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesType = filterType === 'all' || plant.type === filterType;
    const matchesStatus = filterStatus === 'all' || plant.healthStatus === filterStatus;
    
    return matchesSearch && matchesType && matchesStatus;
  });

  const plantTypes = [...new Set(plants.map(plant => plant.type))];

  const handleSavePlant = async (plantData: Omit<Plant, 'id' | 'createdAt' | 'updatedAt'>) => {
    try {
      if (editingPlant) {
        const updatedPlant = await apiService.updatePlant(editingPlant.id, plantData);
        onPlantsChange(plants.map(p => p.id === editingPlant.id ? updatedPlant : p));
      } else {
        const newPlant = await apiService.createPlant(plantData);
        onPlantsChange([...plants, newPlant]);
      }
      setShowPlantForm(false);
      setEditingPlant(null);
    } catch (error) {
      console.error('Error saving plant:', error);
    }
  };

  const handleDeletePlant = async (plantId: number) => {
    if (window.confirm('Are you sure you want to delete this plant?')) {
      try {
        await apiService.deletePlant(plantId);
        onPlantsChange(plants.filter(p => p.id !== plantId));
      } catch (error) {
        console.error('Error deleting plant:', error);
      }
    }
  };

  const handleSaveHarvest = async (harvestData: Omit<HarvestRecord, 'id' | 'createdAt' | 'updatedAt'>) => {
    try {
      const newHarvest = await apiService.createHarvestRecord(harvestData);
      onHarvestRecordsChange([...harvestRecords, newHarvest]);
      setShowHarvestForm(false);
      setSelectedPlantForHarvest(null);
    } catch (error) {
      console.error('Error saving harvest:', error);
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'good': return 'bg-green-100 text-green-800';
      case 'needs-attention': return 'bg-yellow-100 text-yellow-800';
      case 'dead': return 'bg-red-100 text-red-800';
      default: return 'bg-gray-100 text-gray-800';
    }
  };

  const getPlantHarvests = (plantId: number) => {
    return harvestRecords.filter(record => record.plantId === plantId);
  };

  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>

        <div className="flex items-center space-x-3">
          {/* View Mode Toggle */}
          <div className="flex bg-gray-100 rounded-lg p-1">
            <button
                onClick={() => setViewMode('cards')}
                className={`flex items-center space-x-2 px-3 py-2 rounded-md text-sm font-medium transition-colors ${
                    viewMode === 'cards'
                        ? 'bg-white text-green-600 shadow-sm'
                        : 'text-gray-600 hover:text-green-600'
                }`}
            >
              <Grid3X3 className="h-4 w-4" />
              <span>Карточки</span>
            </button>
            <button
                onClick={() => setViewMode('table')}
                className={`flex items-center space-x-2 px-3 py-2 rounded-md text-sm font-medium transition-colors ${
                    viewMode === 'table'
                        ? 'bg-white text-green-600 shadow-sm'
                        : 'text-gray-600 hover:text-green-600'
                }`}
            >
              <List className="h-4 w-4" />
              <span>Таблица</span>
            </button>
          </div>

          <button
              onClick={() => setShowPlantForm(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>
      </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>
              {plantTypes.map(type => (
                <option key={type} value={type} className="capitalize">{PlantTitles[type]}</option>
              ))}
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">Состояние</label>
            <select
              value={filterStatus}
              onChange={(e) => setFilterStatus(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="good">Хорошее</option>
              <option value="needs-attention">Требует внимания</option>
              <option value="dead">Погибло</option>
            </select>
          </div>
        </div>
      </div>

      {/* Plants Display */}
      {viewMode === 'cards' ? (
      /* Cards View */
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {filteredPlants.map((plant) => {
          const plantHarvests = getPlantHarvests(plant.id);
          const lastHarvest = plantHarvests.sort((a, b) => 
            new Date(b.date).getTime() - new Date(a.date).getTime()
          )[0];

          return (
            <div key={plant.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>
                    <h3 className="text-lg font-semibold text-gray-900">{plant.variety}</h3>
                    <p className="text-sm text-gray-600 capitalize">{PlantTitles[plant.type]}</p>
                    <p className="text-xs text-gray-500">Куплено в: {plant.purchaseLocation}</p>
                  </div>
                  <div className="flex space-x-2">
                    <button
                      onClick={() => {
                        setSelectedPlantForStats(plant);
                        setShowStatistics(true);
                      }}
                      className="p-1 text-purple-600 hover:text-purple-700 transition-colors"
                      title="Статистика"
                    >
                      <BarChart3 className="h-4 w-4" />
                    </button>
                    <button
                      onClick={() => {
                        setSelectedPlantForHarvest(plant);
                        setShowHarvestForm(true);
                      }}
                      className="p-1 text-green-600 hover:text-green-700 transition-colors"
                      title="Урожай"
                    >
                      <Award className="h-4 w-4" />
                    </button>
                    <button
                        onClick={() => {
                          const plantHarvests = getPlantHarvests(plant.id);
                          if (plantHarvests.length > 0) {
                            setSelectedHarvestForProcessing(plantHarvests[0]);
                            setShowProcessingModal(true);
                          } else {
                            alert('Урожай не доступен для обработки. Сначала добавьте урожай.');
                          }
                        }}
                        className="p-1 text-orange-600 hover:text-orange-700 transition-colors"
                        title="Process Harvest"
                    >
                      <Package className="h-4 w-4" />
                    </button>
                    <button
                      onClick={() => {
                        setEditingPlant(plant);
                        setShowPlantForm(true);
                      }}
                      className="p-1 text-blue-600 hover:text-blue-700 transition-colors"
                    >
                      <Edit className="h-4 w-4" />
                    </button>
                    <button
                      onClick={() => handleDeletePlant(plant.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-2">
                  {plant.photoUrl && (
                    <div className="mb-3">
                      <ImagePreview
                          thumbnailSrc={plant.photoUrl.startsWith('/uploads')
                          ? `${import.meta.env.VITE_API_URL || '/api'}${plant.photoUrl}`.replace('/api/uploads', '/uploads')
                          : plant.photoUrl
                          }

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

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

                  <div className="space-y-2">
                    <div className="flex items-center space-x-2">
                      <Calendar className="h-4 w-4 text-gray-400" />
                      <span className="text-sm text-gray-600">
                        Посажено: {new Date(plant.plantingDate).toLocaleDateString()} ({Math.floor((new Date().getTime() - new Date(plant.plantingDate).getTime()) / (1000 * 60 * 60 * 24 * 365))} лет)
                    </span>
                    </div>

                    <div className="text-sm text-gray-600">
                      Возраст саженца: {plant.seedlingAge} месяцев
                    </div>

                    <div className="text-sm text-gray-600">
                      Высота саженца: {plant.seedlingHeight} м
                    </div>

                    {plant.currentHeight && (
                        <div className="text-sm text-gray-600">
                          Текущая высота: {plant.currentHeight} м
                        </div>
                    )}

                    {plant.currentHeight && (
                        <div className="text-sm text-gray-600">
                          Прирост: +{(plant.currentHeight - plant.seedlingHeight).toFixed(1)} м
                        </div>
                    )}
                  </div>

                  <div className="flex items-center justify-between">
                    <span className="text-sm text-gray-600">Состояние:</span>
                    <span className={`px-2 py-1 rounded-full text-xs font-medium ${getStatusColor(plant.healthStatus)}`}>
                      {Conditions[plant.healthStatus].replace('-', ' ')}
                    </span>
                  </div>

                  {lastHarvest && (
                    <div className="bg-green-50 p-3 rounded-lg">
                      <p className="text-sm font-medium text-green-800">Последний урожай:</p>
                      <p className="text-sm text-green-600">
                        {lastHarvest.quantity} {HarvestUnits[lastHarvest.unit]}
                        {lastHarvest.weight && ` (${lastHarvest.weight} ${lastHarvest.weightUnit})`}
                        {' '} {new Date(lastHarvest.date).toLocaleDateString()}
                      </p>
                    </div>
                  )}

                  {plant.notes && (
                    <div className="border-t pt-3">
                      <p className="text-sm text-gray-600">{plant.notes}</p>
                    </div>
                  )}
                </div>
              </div>
            </div>
          );
        })}
      </div>
      ) : (
          /* Table View */
          <div className="bg-white rounded-lg shadow-sm border border-green-100 overflow-hidden">
            <div className="overflow-x-auto">
              <table className="min-w-full divide-y divide-gray-200">
                <thead className="bg-gray-50">
                <tr>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Растение
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Тип
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Посажено
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Высота
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Состояние
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Последний урожай
                  </th>
                  <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Действия
                  </th>
                </tr>
                </thead>
                <tbody className="bg-white divide-y divide-gray-200">
                {filteredPlants.map((plant) => {
                  const plantHarvests = getPlantHarvests(plant.id);
                  const lastHarvest = plantHarvests.sort((a, b) =>
                      new Date(b.date).getTime() - new Date(a.date).getTime()
                  )[0];

                  return (
                      <tr key={plant.id} className="hover:bg-gray-50">
                        <td className="px-6 py-4 whitespace-nowrap">
                          <div className="flex items-center">
                            {plant.photoUrl && (
                                <div className="flex-shrink-0 h-10 w-10 mr-3">
                                  <ImagePreview
                                      thumbnailSrc={plant.photoUrl.startsWith('/uploads')
                                          ? `${import.meta.env.VITE_API_URL || '/api'}${plant.photoUrl}`.replace('/api/uploads', '/uploads')
                                          : plant.photoUrl
                                      }

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

                                      alt={plant.variety}
                                      className="h-10 w-10 rounded-full object-cover"
                                  />
                                </div>
                            )}
                            <div>
                              <div className="text-sm font-medium text-gray-900">{plant.variety}</div>
                              <div className="text-sm text-gray-500">{plant.purchaseLocation}</div>
                            </div>
                          </div>
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap">
                          <span className="text-sm text-gray-900 capitalize">{plant.type}</span>
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap">
                          <div className="text-sm text-gray-900">
                            {new Date(plant.plantingDate).toLocaleDateString()}
                          </div>
                          <div className="text-sm text-gray-500">
                            ({Math.floor((new Date().getTime() - new Date(plant.plantingDate).getTime()) / (1000 * 60 * 60 * 24 * 365))} years)
                          </div>
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap">
                          <div className="text-sm text-gray-900">
                            {plant.currentHeight ? `${plant.currentHeight}cm` : `${plant.seedlingHeight}cm`}
                          </div>
                          {plant.currentHeight && (
                              <div className="text-sm text-gray-500">
                                +{(plant.currentHeight - plant.seedlingHeight).toFixed(1)}cm growth
                              </div>
                          )}
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap">
                        <span className={`inline-flex px-2 py-1 text-xs font-semibold rounded-full ${getStatusColor(plant.healthStatus)}`}>
                          {plant.healthStatus.replace('-', ' ')}
                        </span>
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap">
                          {lastHarvest ? (
                              <div className="text-sm text-gray-900">
                                <div>
                                  {lastHarvest.quantity} {lastHarvest.unit}
                                  {lastHarvest.weight && (
                                      <div className="text-gray-500">({lastHarvest.weight} {lastHarvest.weightUnit})</div>
                                  )}
                                </div>
                                <div className="text-gray-500">{new Date(lastHarvest.date).toLocaleDateString()}</div>
                              </div>
                          ) : (
                              <span className="text-sm text-gray-500">No harvests</span>
                          )}
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap">
                          {(plant.estimatedRipeningStart || plant.estimatedRipeningEnd) ? (
                              <div className="text-sm text-gray-900">
                                <div>
                                  {plant.estimatedRipeningStart && `Day ${plant.estimatedRipeningStart}`}
                                  {plant.estimatedRipeningStart && plant.estimatedRipeningEnd && ' - '}
                                  {plant.estimatedRipeningEnd && `Day ${plant.estimatedRipeningEnd}`}
                                </div>
                                {plant.ripeningNotes && (
                                    <div className="text-xs text-gray-500 truncate max-w-32" title={plant.ripeningNotes}>
                                      {plant.ripeningNotes}
                                    </div>
                                )}
                              </div>
                          ) : (
                              <span className="text-sm text-gray-500">Not set</span>
                          )}
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                          <div className="flex justify-end space-x-2">
                            <button
                                onClick={() => {
                                  setSelectedPlantForStats(plant);
                                  setShowStatistics(true);
                                }}
                                className="text-purple-600 hover:text-purple-700 transition-colors"
                                title="View Statistics"
                            >
                              <BarChart3 className="h-4 w-4" />
                            </button>
                            <button
                                onClick={() => {
                                  setSelectedPlantForHarvest(plant);
                                  setShowHarvestForm(true);
                                }}
                                className="text-green-600 hover:text-green-700 transition-colors"
                                title="Добавить урожай"
                            >
                              <Award className="h-4 w-4" />
                            </button>
                            <button
                                onClick={() => {
                                  const plantHarvests = getPlantHarvests(plant.id);
                                  if (plantHarvests.length > 0) {
                                    setSelectedHarvestForProcessing(plantHarvests[0]);
                                    setShowProcessingModal(true);
                                  } else {
                                    alert('Урожай не доступен для обработки. Сначала добавьте урожай.');
                                  }
                                }}
                                className="text-orange-600 hover:text-orange-700 transition-colors"
                                title="Process Harvest"
                            >
                              <Package className="h-4 w-4" />
                            </button>
                            <button
                                onClick={() => {
                                  setEditingPlant(plant);
                                  setShowPlantForm(true);
                                }}
                                className="text-blue-600 hover:text-blue-700 transition-colors"
                            >
                              <Edit className="h-4 w-4" />
                            </button>
                            <button
                                onClick={() => handleDeletePlant(plant.id)}
                                className="text-red-600 hover:text-red-700 transition-colors"
                            >
                              <Trash2 className="h-4 w-4" />
                            </button>
                          </div>
                        </td>
                      </tr>
                  );
                })}
                </tbody>
              </table>
            </div>
          </div>
      )}

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

      {/* Plant Form Modal */}
      {showPlantForm && (
        <PlantForm
          plant={editingPlant}
          onSave={handleSavePlant}
          onCancel={() => {
            setShowPlantForm(false);
            setEditingPlant(null);
          }}
        />
      )}

      {/* Harvest Form Modal */}
      {showHarvestForm && selectedPlantForHarvest && (
        <HarvestForm
          plant={selectedPlantForHarvest}
          onSave={handleSaveHarvest}
          onCancel={() => {
            setShowHarvestForm(false);
            setSelectedPlantForHarvest(null);
          }}
        />
      )}

      {/* Plant Statistics Modal */}
      {showStatistics && selectedPlantForStats && (
        <PlantStatistics
          plant={selectedPlantForStats}
          harvestRecords={harvestRecords}
          maintenanceRecords={maintenanceRecords}
          onClose={() => {
            setShowStatistics(false);
            setSelectedPlantForStats(null);
          }}
        />
      )}

      {/* Harvest Processing Modal */}
      {showProcessingModal && selectedHarvestForProcessing && (
          <HarvestProcessingModal
              isOpen={showProcessingModal}
              harvest={selectedHarvestForProcessing}
              plant={plants.find(p => p.id === selectedHarvestForProcessing.plantId)!}
              onClose={() => {
                setShowProcessingModal(false);
                setSelectedHarvestForProcessing(null);
              }}
              onProcessingAdded={() => {
                // Refresh data if needed
              }}
          />
      )}
    </div>
  );
};

export default PlantRegistry;