import { useState, useEffect } 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 [isSubmitting, setIsSubmitting] = useState(false);

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

  // Refresh counts when form closes
  useEffect(() => {
    if (!isFormOpen) {
      fetchDeliveryCounts();
    }
  }, [isFormOpen, fetchDeliveryCounts]);

  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 = async (data: Parameters<typeof addDelivery>[0]) => {
    setIsSubmitting(true);
    try {
      await addDelivery(data);
      setIsFormOpen(false);

      // If created for different date, navigate to that date
      const today = new Date().toLocaleDateString('ru-RU').split('.').join('-');
      if (data.date !== today) {
        setSelectedDate(data.date);
        setView('delivery-list');
      }
    } catch {
      // Error is handled by store
    } finally {
      setIsSubmitting(false);
    }
  };

  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}
        isSubmitting={isSubmitting}
      />
    </div>
  );
}

export default App;
