import { useState, useEffect } from 'react';
import { Sprout, Calendar, CheckSquare, Activity, BookOpen, Beaker, FlaskConical, Archive } from 'lucide-react';
import { Plant, Task, MaintenanceRecord, HarvestRecord, PlantObservation } from './types';
import Dashboard from './components/Dashboard';
import PlantRegistry from './components/PlantRegistry';
import TaskPlanner from './components/TaskPlanner';
import MaintenanceLog from './components/MaintenanceLog';
import ObservationJournal from './components/ObservationJournal';
import FertilizerRegistry from './components/FertilizerRegistry';
import ChemicalRegistry from './components/ChemicalRegistry';
import HarvestStockManager from './components/HarvestStockManager';
import { apiService } from './services/api';

function App() {
  const [activeTab, setActiveTab] = useState('dashboard');
  const [plants, setPlants] = useState<Plant[]>([]);
  const [tasks, setTasks] = useState<Task[]>([]);
  const [maintenanceRecords, setMaintenanceRecords] = useState<MaintenanceRecord[]>([]);
  const [harvestRecords, setHarvestRecords] = useState<HarvestRecord[]>([]);
  const [observations, setObservations] = useState<PlantObservation[]>([]);
  const [loading, setLoading] = useState(true);

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

  const loadData = async () => {
    try {
      setLoading(true);
      
      // Test backend connection first
      await apiService.healthCheck();
      
      const [plantsData, tasksData, maintenanceData, harvestData, observationsData] = await Promise.all([
        apiService.getPlants(),
        apiService.getTasks(),
        apiService.getMaintenanceRecords(),
        apiService.getHarvestRecords(),
        apiService.getPlantObservations()
      ]);
      
      setPlants(plantsData);
      setTasks(tasksData);
      setMaintenanceRecords(maintenanceData);
      setHarvestRecords(harvestData);
      setObservations(observationsData);
    } catch (error) {
      console.error('Error loading data:', error);
      // You could add a toast notification or error state here
      alert(`Failed to load data: ${error instanceof Error ? error.message : 'Unknown error'}`);
    } finally {
      setLoading(false);
    }
  };

  const navItems = [
    { id: 'dashboard', label: 'Панель', icon: Activity },
    { id: 'plants', label: 'Реестр растений', icon: Sprout },
    { id: 'tasks', label: 'План работ', icon: CheckSquare },
    { id: 'maintenance', label: 'Выполненные работы', icon: Calendar },
    { id: 'observations', label: 'Дневник', icon: BookOpen },
    { id: 'fertilizers', label: 'Удобрения', icon: FlaskConical },
    { id: 'chemicals', label: 'Химикаты', icon: Beaker },
    { id: 'stock', label: 'Заготовки', icon: Archive },
  ];

  if (loading) {
    return (
      <div className="min-h-screen bg-green-50 flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-green-600 mx-auto mb-4"></div>
          <p className="text-green-700">Loading GardenTrack...</p>
        </div>
      </div>
    );
  }

  return (
      <div className="min-h-screen bg-green-50 flex">
        {/* Left Sidebar */}
        <div className="hidden md:flex md:w-64 md:flex-col">
          <div className="flex flex-col flex-grow bg-white shadow-sm border-r border-green-100">
            {/* Logo */}
            <div className="flex items-center space-x-3 px-6 py-4 border-b border-green-100">
              <Sprout className="h-8 w-8 text-green-600" />
              <h1 className="text-xl font-bold text-green-800">GardenTrack</h1>
            </div>

            {/* Navigation */}
            <nav className="flex-1 px-4 py-6 space-y-2">
              {navItems.map((item) => {
                const Icon = item.icon;
                return (
                    <button
                        key={item.id}
                        onClick={() => setActiveTab(item.id)}
                        className={`w-full flex items-center space-x-3 px-4 py-3 rounded-lg text-sm font-medium transition-colors ${
                            activeTab === item.id
                                ? 'bg-green-100 text-green-700 border border-green-200'
                                : 'text-gray-600 hover:text-green-600 hover:bg-green-50'
                        }`}
                    >
                      <Icon className="h-5 w-5" />
                      <span>{item.label}</span>
                    </button>
                );
              })}
            </nav>
          </div>
        </div>

        {/* Main Content */}
        <div className="flex-1 flex flex-col">
          {/* Mobile Header */}
          <header className="md:hidden bg-white shadow-sm border-b border-green-100">
            <div className="px-4 py-4">
              <div className="flex items-center space-x-3">
                <Sprout className="h-6 w-6 text-green-600" />
                <h1 className="text-lg font-bold text-green-800">GardenTrack</h1>
              </div>
            </div>
          </header>

          {/* Main Content Area */}
          <main className="flex-1 px-4 sm:px-6 lg:px-8 py-8 overflow-auto">
            {activeTab === 'dashboard' && (
                <Dashboard
                    plants={plants}
                    tasks={tasks}
                    maintenanceRecords={maintenanceRecords}
                    harvestRecords={harvestRecords}
                    onNavigate={setActiveTab}
                />
            )}
            {activeTab === 'plants' && (
                <PlantRegistry
                    plants={plants}
                    onPlantsChange={setPlants}
                    harvestRecords={harvestRecords}
                    onHarvestRecordsChange={setHarvestRecords}
                    maintenanceRecords={maintenanceRecords}
                />
            )}
            {activeTab === 'tasks' && (
                <TaskPlanner
                    tasks={tasks}
                    plants={plants}
                    onTasksChange={setTasks}
                />
            )}
            {activeTab === 'maintenance' && (
                <MaintenanceLog
                    maintenanceRecords={maintenanceRecords}
                    plants={plants}
                    onMaintenanceChange={setMaintenanceRecords}
                />
            )}
            {activeTab === 'observations' && (
                <ObservationJournal
                    observations={observations}
                    plants={plants}
                    onObservationsChange={setObservations}
                />
            )}
            {activeTab === 'fertilizers' && (
                <FertilizerRegistry />
            )}
            {activeTab === 'chemicals' && (
                <ChemicalRegistry />
            )}
            {activeTab === 'stock' && (
                <HarvestStockManager plants={plants} />
            )}
          </main>
        </div>

        {/* Mobile Navigation */}
        <nav className="md:hidden fixed bottom-0 left-0 right-0 bg-white border-t border-green-100 px-2 py-2">
          <div className="flex justify-around">
            {navItems.map((item) => {
              const Icon = item.icon;
              return (
                  <button
                      key={item.id}
                      onClick={() => setActiveTab(item.id)}
                      className={`flex flex-col items-center py-2 px-2 rounded-md transition-colors ${
                          activeTab === item.id
                              ? 'text-green-600'
                              : 'text-gray-400 hover:text-green-600'
                      }`}
                  >
                    <Icon className="h-5 w-5" />
                    <span className="text-xs mt-1 text-center leading-tight">{item.label.split(' ')[0]}</span>
                  </button>
              );
            })}
          </div>
        </nav>
      </div>
  );
}


export default App;