
import React, { useState, useEffect, Suspense, lazy, useMemo } from 'react';
import { Routes, Route, useLocation, useNavigate, Navigate } from 'react-router-dom';
import { Toaster } from '@/components/ui/toaster';
import { toast } from '@/components/ui/use-toast';
import { supabase } from '@/lib/supabaseClient';

import Header from '@/components/layout/Header';
import Footer from '@/components/layout/Footer';
import CouponCodeDialog from '@/components/dialogs/CouponCodeDialog';

import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";

import HomePage from '@/pages/HomePage';
import CouponDetailPage from '@/pages/CouponDetailPage';
import AdminLoginPage from '@/pages/AdminLoginPage';

import Meta from '@/components/Meta'; 

import useCoupons from '@/hooks/useCoupons';
import useAdminPanel from '@/hooks/useAdminPanel';
import useCouponDisplay from '@/hooks/useCouponDisplay';
import useMobileMenu from '@/hooks/useMobileMenu';
import { slugify } from '@/utils/slugify';


const AdminPanel = lazy(() => import('@/components/AdminPanel'));
const HowWeMakeMoneyDialog = lazy(() => import('@/components/dialogs/HowWeMakeMoneyDialog'));
const TermsOfUseDialog = lazy(() => import('@/components/dialogs/TermsOfUseDialog'));
const PrivacyPolicyDialog = lazy(() => import('@/components/dialogs/PrivacyPolicyDialog'));


const ITEMS_PER_PAGE = 15;

const LoadingFallback = () => (
  <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-[9999]">
    <div className="animate-spin rounded-full h-16 w-16 border-t-4 border-b-4 border-orange-500"></div>
  </div>
);


const App = () => {
  const [currentPage, setCurrentPage] = useState(1);
  const {
    adminCoupons,
    setAdminCoupons,
    loading: couponsLoading,
    fetchCoupons,
    handleAddCoupon,
    handleEditCoupon,
    handleDeleteCouponInternal,
    handleToggleCouponVisibility,
  } = useCoupons(toast, currentPage, ITEMS_PER_PAGE);

  const {
    showAdmin: showAdminViaHook, 
    setShowAdmin: setShowAdminViaHook,
    editingCoupon,
    setEditingCoupon,
  } = useAdminPanel(); 

  const [session, setSession] = useState(null);
  const [authLoading, setAuthLoading] = useState(true);
  const [adminSortOrder, setAdminSortOrder] = useState('desc');


  const publicCoupons = useMemo(() => adminCoupons.filter(c => !c.is_hidden && c.title && c.brand), [adminCoupons]);

  const {
    sortOption,
    setSortOption,
    filterStatus,
    setFilterStatus,
    searchTerm,
    setSearchTerm,
    selectedBrand,
    setSelectedBrand,
    selectedCoupon,
    showCouponDialog,
    setShowCouponDialog,
    filteredAndSortedCoupons: getFilteredAndSortedPublicCoupons,
    handleCouponClick: baseHandleCouponClick, 
    handleCopyCode,
  } = useCouponDisplay(publicCoupons, toast);
  
  const {
    filteredAndSortedCoupons: getFilteredAndSortedAdminCoupons,
  } = useCouponDisplay(adminCoupons, toast, true, adminSortOrder);


  const { isMobileMenuOpen, setIsMobileMenuOpen, toggleMobileMenu: toggleMobileMenuHook } = useMobileMenu();
  const [showHowWeMakeMoneyDialog, setShowHowWeMakeMoneyDialog] = useState(false);
  const [showTermsOfUseDialog, setShowTermsOfUseDialog] = useState(false);
  const [showPrivacyPolicyDialog, setShowPrivacyPolicyDialog] = useState(false);
  const [showDeleteConfirmDialog, setShowDeleteConfirmDialog] = useState(false);
  const [couponToDelete, setCouponToDelete] = useState(null);

  const navigate = useNavigate();
  const location = useLocation();

  useEffect(() => {
    const getSession = async () => {
      const { data: { session: currentSession } } = await supabase.auth.getSession();
      setSession(currentSession);
      if (currentSession && location.pathname === '/admin-dashboard') {
        setShowAdminViaHook(true);
      }
      setAuthLoading(false);
    };

    getSession();

    const authSubscription = supabase.auth.onAuthStateChange((_event, newSession) => {
      setSession(newSession);
      if (_event === 'SIGNED_OUT') {
        setShowAdminViaHook(false); 
        navigate('/');
      }
      if (_event === 'SIGNED_IN') {
        setShowAdminViaHook(true); 
        if (location.pathname === '/secure-admin-login' || location.pathname === '/') {
            navigate('/admin-dashboard'); 
        }
      }
    });

    return () => {
      authSubscription.data.subscription.unsubscribe();
    };
  }, [navigate, location.pathname, setShowAdminViaHook]);
  
  useEffect(() => {
    fetchCoupons(currentPage, ITEMS_PER_PAGE);
  }, [currentPage, fetchCoupons]);

  const handleRegularLogoClick = () => {
    if (location.pathname !== "/") {
      navigate("/");
    } else {
      window.location.href = "https://alogapedia.com";
    }
  };

  const handleAdminLogout = async () => {
    const { error } = await supabase.auth.signOut();
    if (error) {
      toast({ title: 'Logout Error', description: error.message, variant: 'destructive' });
    } else {
      toast({ title: 'Logged Out', description: 'You have been successfully logged out.' });
      setSession(null);
      setShowAdminViaHook(false); 
      navigate('/');
    }
  };

  const triggerAdminPanelAction = () => {
    if (session) { 
      const newShowAdminState = !showAdminViaHook;
      setShowAdminViaHook(newShowAdminState);
      if (newShowAdminState) {
          if (location.pathname !== '/admin-dashboard') {
            navigate('/admin-dashboard');
          }
      } else {
          if (location.pathname.startsWith('/admin-dashboard')) {
            navigate('/');
          }
      }
    } else {
      navigate('/secure-admin-login');
    }
  };
  
  const navLinks = [
    { href: "https://alogapedia.com", text: "Home" },
    { href: "/", text: "Deals", active: location.pathname === '/' || location.pathname.startsWith('/deal/') },
    { href: "https://alogapedia.com/product-reviews/", text: "Reviews" },
    { href: "https://alogapedia.com/recommendations/", text: "Recommendations" },
    { href: "https://alogapedia.com/about/", text: "About" }
  ];
  
  const displayedPublicCoupons = getFilteredAndSortedPublicCoupons();
  const totalPublicCoupons = displayedPublicCoupons.length;
  const totalPages = Math.ceil(totalPublicCoupons / ITEMS_PER_PAGE);
  const paginatedPublicCoupons = displayedPublicCoupons.slice((currentPage - 1) * ITEMS_PER_PAGE, currentPage * ITEMS_PER_PAGE);

  const uniqueBrands = useMemo(() => {
    const brands = new Set(publicCoupons.map(coupon => coupon.brand).filter(Boolean));
    return Array.from(brands).sort();
  }, [publicCoupons]);

  useEffect(() => {
    setCurrentPage(1); 
  }, [selectedBrand, sortOption, filterStatus, searchTerm]);


  const handlePageChange = (page) => {
    setCurrentPage(page);
    window.scrollTo(0, 0);
  };

  const handleDeleteRequest = (couponId) => {
    setCouponToDelete(couponId);
    setShowDeleteConfirmDialog(true);
  };

  const confirmDeleteCoupon = async () => {
    if (couponToDelete) {
      await handleDeleteCouponInternal(couponToDelete);
      setCouponToDelete(null);
      setShowDeleteConfirmDialog(false);
      fetchCoupons(currentPage, ITEMS_PER_PAGE); 
    }
  };

  const handleCouponCardClick = (coupon) => {
    if (coupon && coupon.brand && coupon.title) {
      const couponSlug = `${slugify(coupon.brand)}-${slugify(coupon.title).substring(0,50)}`;
      navigate(`/deal/${couponSlug}/`);
    } else {
      baseHandleCouponClick(coupon); 
    }
  };

  if (authLoading) {
    return <LoadingFallback />;
  }

  return (
    <div className="min-h-screen bg-[#ffc071] flex flex-col">
      <Meta />
      <Toaster />
      
      <CouponCodeDialog
        showCouponDialog={showCouponDialog}
        setShowCouponDialog={setShowCouponDialog}
        selectedCoupon={selectedCoupon}
        handleCopyCode={handleCopyCode}
      />
      <Suspense fallback={<LoadingFallback />}>
        {showHowWeMakeMoneyDialog && <HowWeMakeMoneyDialog
          showDialog={showHowWeMakeMoneyDialog}
          setShowDialog={setShowHowWeMakeMoneyDialog}
        />}

        {showTermsOfUseDialog && <TermsOfUseDialog
          showDialog={showTermsOfUseDialog}
          setShowDialog={setShowTermsOfUseDialog}
        />}

        {showPrivacyPolicyDialog && <PrivacyPolicyDialog
          showDialog={showPrivacyPolicyDialog}
          setShowDialog={setShowPrivacyPolicyDialog}
        />}
      </Suspense>


      <AlertDialog open={showDeleteConfirmDialog} onOpenChange={setShowDeleteConfirmDialog}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Are you sure?</AlertDialogTitle>
            <AlertDialogDescription>
              This action cannot be undone. This will permanently delete the coupon.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel onClick={() => setShowDeleteConfirmDialog(false)}>Cancel</AlertDialogCancel>
            <AlertDialogAction onClick={confirmDeleteCoupon} className="bg-red-600 hover:bg-red-700">Delete</AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
      
      <Header 
        navLinks={navLinks} 
        handleLogoClick={handleRegularLogoClick}
        isMobileMenuOpen={isMobileMenuOpen}
        toggleMobileMenu={toggleMobileMenuHook}
        setIsMobileMenuOpen={setIsMobileMenuOpen}
        toggleAdminPanel={triggerAdminPanelAction}
        isLoggedIn={!!session}
      />
      
      <Routes>
        <Route 
          path="/" 
          element={
            <HomePage 
              coupons={paginatedPublicCoupons} 
              handleCouponClick={handleCouponCardClick} 
              loading={couponsLoading}
              currentPage={currentPage}
              totalPages={totalPages}
              onPageChange={handlePageChange}
              brands={uniqueBrands}
              selectedBrand={selectedBrand}
              onSelectBrand={setSelectedBrand}
              sortOption={sortOption}
              onSortChange={setSortOption}
            />
          } 
        />
        <Route 
          path="/deal/:slug/" 
          element={
            <CouponDetailPage />
          } 
        />
        <Route 
          path="/secure-admin-login" 
          element={!session ? <AdminLoginPage /> : <Navigate to="/admin-dashboard" replace />} 
        />
        <Route
          path="/admin-dashboard"
          element={
            session && showAdminViaHook ? (
              <Suspense fallback={<LoadingFallback />}>
                <AdminPanel
                  setShowAdmin={setShowAdminViaHook} 
                  onLogout={handleAdminLogout}
                  handleAddCoupon={handleAddCoupon}
                  handleEditCoupon={handleEditCoupon}
                  handleDeleteCoupon={handleDeleteRequest}
                  handleToggleCouponVisibility={handleToggleCouponVisibility}
                  adminCoupons={adminCoupons}
                  setAdminCoupons={setAdminCoupons}
                  searchTerm={searchTerm}
                  setSearchTerm={setSearchTerm}
                  filterStatus={filterStatus}
                  setFilterStatus={setFilterStatus}
                  sortOrder={adminSortOrder} 
                  setSortOrder={setAdminSortOrder}
                  filteredAndSortedCoupons={getFilteredAndSortedAdminCoupons}
                  editingCoupon={editingCoupon}
                  setEditingCoupon={setEditingCoupon}
                  toast={toast}
                  fetchCoupons={() => fetchCoupons(currentPage, ITEMS_PER_PAGE)} 
                  isPublicInterface={false}
                />
              </Suspense>
            ) : session && !showAdminViaHook && location.pathname === '/admin-dashboard' ? (
              <Navigate to="/" replace />
            ) : !session ? (
              <Navigate to="/secure-admin-login" replace />
            ) : null 
          }
        />
        
      </Routes>
      
      {(location.pathname === '/admin-dashboard' && session && showAdminViaHook) ? null : (
        <Footer 
          openHowWeMakeMoneyDialog={() => setShowHowWeMakeMoneyDialog(true)} 
          openTermsOfUseDialog={() => setShowTermsOfUseDialog(true)}
          openPrivacyPolicyDialog={() => setShowPrivacyPolicyDialog(true)}
        />
      )}
    </div>
  );
};

export default App;
