import React, { useState, useEffect, useCallback } from 'react';
import { ToastProvider, useToast } from './context/ToastContext';
import { AuthProvider, useAuth } from './context/AuthContext';
import { CartProvider } from './context/CartContext';
import { Header } from './components/Header';
import { HeroSection } from './components/HeroSection';
import { WireguardSection } from './components/WireguardSection';
import { ProductCard } from './components/ProductCard';
import { FeaturesSection } from './components/FeaturesSection';
import { FaqSection } from './components/FaqSection';
import { TutorialsSection } from './components/TutorialsSection';
import { Footer } from './components/Footer';
import { ShopView } from './components/ShopView';
import { UserProfile } from './components/UserProfile';
import { AdminPanel } from './components/AdminPanel';
import { ProductDetailsModal } from './components/ProductDetailsModal';
import { CartDrawer } from './components/CartDrawer';
import { CheckoutModal } from './components/CheckoutModal';
import { AuthModal } from './components/AuthModal';
import { api } from './services/api';
import type { Product, Category, Order } from './types';

function MainApp() {
  // Navigation View State
  const [currentView, setCurrentView] = useState<'home' | 'shop' | 'tutorials' | 'profile' | 'track-order' | 'admin'>('home');
  const [selectedCategoryId, setSelectedCategoryId] = useState<string>('');
  const [initialSearchTerm, setInitialSearchTerm] = useState<string>('');
  const [initialTrackingNumber, setInitialTrackingNumber] = useState<string>('');

  // Data states
  const [products, setProducts] = useState<Product[]>([]);
  const [categories, setCategories] = useState<Category[]>([]);
  const [loading, setLoading] = useState(true);

  // Modals state
  const [activeProductModal, setActiveProductModal] = useState<Product | null>(null);
  const [isCheckoutOpen, setIsCheckoutOpen] = useState(false);

  const { error } = useToast();

  // Load products and categories from backend
  const loadData = useCallback(async () => {
    try {
      setLoading(true);
      const [prodsData, catsData] = await Promise.all([
        api.getProducts(),
        api.getCategories(),
      ]);
      setProducts(prodsData);
      setCategories(catsData);
    } catch (err: any) {
      console.error('Error fetching data:', err);
      error(err.message || 'خطا در برقراری ارتباط با سرور');
    } finally {
      setLoading(false);
    }
  }, [error]);

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

  // Navigation Handler
  const handleNavigate = (view: string, data?: any) => {
    window.scrollTo({ top: 0, behavior: 'smooth' });

    if (view === 'shop') {
      if (data?.categoryId !== undefined) {
        setSelectedCategoryId(data.categoryId);
      }
      if (data?.search) {
        setInitialSearchTerm(data.search);
      }
      setCurrentView('shop');
    } else if (view === 'tutorials') {
      setCurrentView('tutorials');
    } else if (view === 'track-order' || view === 'profile') {
      if (data?.orderNumber) {
        setInitialTrackingNumber(data.orderNumber);
      }
      setCurrentView('profile');
    } else if (view === 'admin') {
      setCurrentView('admin');
    } else {
      setCurrentView('home');
    }
  };

  const handleSelectCategory = (categoryId: string) => {
    setSelectedCategoryId(categoryId);
    setCurrentView('shop');
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  // WireGuard Dedicated Product
  const wireguardProducts = products.filter(p => p.categoryId === 'cat_gaming_service');
  const wireguardProduct = wireguardProducts[0];

  // Featured and Best-selling subsets
  const featuredProducts = products.filter(p => p.isFeatured || p.badge);
  const bestSellers = products.filter(p => p.isBestSeller);

  // Related products for modal
  const relatedProducts = activeProductModal
    ? products.filter(p => p.categoryId === activeProductModal.categoryId && p.id !== activeProductModal.id)
    : [];

  return (
    <div className="min-h-screen bg-[#050505] text-zinc-100 flex flex-col selection:bg-purple-600 selection:text-white font-sans antialiased overflow-x-hidden">
      
      {/* Top Main Navigation Header */}
      <Header
        onNavigate={handleNavigate}
        categories={categories}
        currentView={currentView}
      />

      {/* Main Content Area */}
      <main className="flex-1">
        {currentView === 'home' && (
          <>
            {/* Hero Banner with ZaccShop Bento Structure */}
            <HeroSection
              onShopClick={() => handleNavigate('shop')}
              onWireguardClick={() => {
                if (wireguardProduct) {
                  setActiveProductModal(wireguardProduct);
                } else {
                  handleSelectCategory('cat_gaming_service');
                }
              }}
            />

            {/* Dedicated WireGuard Showcase */}
            <WireguardSection
              products={wireguardProducts}
              onViewProduct={(prod) => setActiveProductModal(prod)}
            />

            {/* Products available in the shop */}
            {products.length > 0 && (
              <section className="py-10 relative">
                <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                  <div className="flex items-end justify-between mb-6 text-right">
                    <div>
                      <div className="text-xs font-bold text-purple-300 mb-1">فقط WireGuard</div>
                      <h2 className="text-2xl sm:text-3xl font-black text-white">پلن‌های فعال</h2>
                    </div>
                    <button onClick={() => handleNavigate('shop')} className="text-xs sm:text-sm text-purple-400 hover:text-purple-300 font-bold">مشاهده فروشگاه</button>
                  </div>
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 max-w-4xl mr-auto">
                    {products.map((product) => (
                      <ProductCard key={product.id} product={product} onViewDetails={(prod) => setActiveProductModal(prod)} />
                    ))}
                  </div>
                </div>
              </section>
            )}

            {/* Why ZaccShop Features */}
            <FeaturesSection />

            {/* FAQ Section */}
            <FaqSection />
          </>
        )}

        {currentView === 'tutorials' && (
          <TutorialsSection />
        )}

        {currentView === 'shop' && (
          <ShopView
            products={products}
            categories={categories}
            selectedCategoryId={selectedCategoryId}
            initialSearch={initialSearchTerm}
            onSelectCategory={(catId) => setSelectedCategoryId(catId)}
            onViewProductDetails={(prod) => setActiveProductModal(prod)}
          />
        )}

        {(currentView === 'profile' || currentView === 'track-order') && (
          <UserProfile
            initialSearchOrderNumber={initialTrackingNumber}
            onNavigateHome={() => handleNavigate('home')}
          />
        )}

        {currentView === 'admin' && (
          <AdminPanel
            onBackToStore={() => handleNavigate('home')}
            onRefreshData={loadData}
          />
        )}
      </main>

      {/* Footer */}
      <Footer
        onNavigate={handleNavigate}
        categories={categories}
      />

      {/* Global Modals & Drawers */}
      <CartDrawer
        onProceedToCheckout={() => setIsCheckoutOpen(true)}
      />

      <CheckoutModal
        isOpen={isCheckoutOpen}
        onClose={() => setIsCheckoutOpen(false)}
        onOrderSuccess={(order: Order) => {
          handleNavigate('profile', { orderNumber: order.orderNumber });
        }}
      />

      <ProductDetailsModal
        product={activeProductModal}
        onClose={() => setActiveProductModal(null)}
        onSelectRelatedProduct={(prod) => setActiveProductModal(prod)}
        relatedProducts={relatedProducts}
      />

      <AuthModal />

    </div>
  );
}

export default function App() {
  return (
    <ToastProvider>
      <AuthProvider>
        <CartProvider>
          <MainApp />
        </CartProvider>
      </AuthProvider>
    </ToastProvider>
  );
}
