import { useState } from 'react';
import { Truck } from 'lucide-react';
import { Dashboard } from './pages/Dashboard';
import { DeliveryListPage } from './pages/DeliveryListPage';
import { DeliveryForm } from './components/delivery/DeliveryForm';
import { useDeliveryStore } from './stores/deliveryStore';

function App() {
  const [view, setView] = useState<'dashboard' | 'delivery-list'>('dashboard');
  const [selectedDate, setSelectedDate] = useState<string>('');
  const [isFormOpen, setIsFormOpen] = useState(false);
  const [formDate, setFormDate] = useState<string>('');

  const addDelivery = useDeliveryStore(state => state.addDelivery);

  const handleDateSelect = (date: string) => {
    setSelectedDate(date);
    setView('delivery-list');
  };

  const handleBackToDashboard = () => {
    setView('dashboard');
    setSelectedDate('');
  };

  const handleAddDelivery = () => {
    const today = new Date().toLocaleDateString('ru-RU').split('.').join('-');
    setFormDate(today);
    setIsFormOpen(true);
  };

  const handleFormSubmit = (data: Parameters<typeof addDelivery>[0]) => {
    addDelivery(data);
    setIsFormOpen(false);
    
    if (data.date !== new Date().toLocaleDateString('ru-RU').split('.').join('-')) {
      setSelectedDate(data.date);
      setView('delivery-list');
    }
  };

  return (
    <div className="min-h-screen bg-[#fbf8fb]">
      <header className="sticky top-0 z-40 bg-[#1B263B] text-white shadow-md">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex items-center justify-between h-14">
            <div className="flex items-center gap-3">
              <div className="p-2 bg-white/10 rounded-lg">
                <Truck size={24} className="text-white" />
              </div>
              <h1 className="text-lg font-semibold hidden sm:block">Delivery Tracker</h1>
            </div>
            <div className="text-sm text-white/70">
              {view === 'dashboard' ? 'Панель управления' : `Доставки на ${selectedDate}`}
            </div>
          </div>
        </div>
      </header>

      <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
        {view === 'dashboard' ? (
          <Dashboard 
            onDateSelect={handleDateSelect}
            onAddDelivery={handleAddDelivery}
          />
        ) : (
          <DeliveryListPage 
            selectedDate={selectedDate}
            onBack={handleBackToDashboard}
          />
        )}
      </main>

      <DeliveryForm
        isOpen={isFormOpen}
        onClose={() => setIsFormOpen(false)}
        onSubmit={handleFormSubmit}
        defaultDate={formDate}
      />
    </div>
  );
}

export default App;
