import { useState, useEffect } from 'react';
import { LandingPage } from './pages/LandingPage';
import { ExploreMap } from './pages/ExploreMap';
import { TourDetailPage } from './pages/TourDetailPage';
import SignupPage from './pages/SignupPage';
import { MyPhotosPage } from './pages/MyPhotosPage';
import { MyNotePage } from './pages/MyNotePage';
import { JoinTourPage } from './pages/JoinTourPage';
import { AdminDashboard } from './pages/AdminDashboard';
import { ShareJourneyPage } from './pages/ShareJourneyPage';
import { TourNavigationPage } from './pages/TourNavigationPage';
import { ConfirmProvider } from './hooks/useConfirm';
import { NotificationProvider, useNotification } from './hooks/useNotification';
import { io } from 'socket.io-client';
import { Capacitor } from '@capacitor/core';

interface GlobalNotificationListenerProps {
  user: any;
  currentPage: string;
  currentTourId: string | null;
}

const GlobalNotificationListener: React.FC<GlobalNotificationListenerProps> = ({ user, currentPage, currentTourId }) => {
  const notify = useNotification();

  // Request browser Notification permission once on mount
  useEffect(() => {
    if ('Notification' in window && Notification.permission === 'default') {
      Notification.requestPermission();
    }
  }, []);

  useEffect(() => {
    if (!user?.id) return;

    const socketInstance = Capacitor.isNativePlatform()
      ? io(import.meta.env.VITE_BACKEND_URL || 'https://yotrip.labz.io.vn')
      : io();

    socketInstance.on('connect', () => {
      console.log('[WS] Global notification socket connected:', socketInstance.id);
      socketInstance.emit('joinUser', user.id);
    });

    socketInstance.on('tourMessageNotification', (data: any) => {
      // Dispatch custom window event
      window.dispatchEvent(new CustomEvent('app:tourMessageNotification', { detail: data }));

      // Check if user is actively viewing this specific tour chat
      const isViewingThisTourChat = currentPage === 'tourDetail' && currentTourId === data.tourId && (window as any).activeTourChatTab;

      if (!isViewingThisTourChat) {
        notify({
          title: `Tin nhắn mới trong tour "${data.tourTitle}"`,
          message: `${data.senderName}: "${data.content.substring(0, 30)}${data.content.length > 30 ? '...' : ''}"`,
          type: 'success'
        });

        // Show push notification on desktop browser
        if ('Notification' in window && Notification.permission === 'granted') {
          try {
            new Notification(`Tin nhắn mới trong tour "${data.tourTitle}"`, {
              body: `${data.senderName}: ${data.content}`,
              icon: '/favicon.ico'
            });
          } catch (e) {
            console.error('System Notification error:', e);
          }
        }
      }
    });

    socketInstance.on('messageReceived', (message: any) => {
      // Dispatch custom window event
      window.dispatchEvent(new CustomEvent('app:messageReceived', { detail: message }));

      // Check if user is actively chatting with the sender
      const isChattingWithSender = currentPage === 'dashboard' && (window as any).activeChatUserId === message.senderId;

      if (!isChattingWithSender) {
        notify({
          title: 'Tin nhắn mới',
          message: `${message.sender?.name || 'Ai đó'} gửi: "${message.content.substring(0, 30)}${message.content.length > 30 ? '...' : ''}"`,
          type: 'success'
        });

        // Show push notification on desktop browser
        if ('Notification' in window && Notification.permission === 'granted') {
          try {
            new Notification(`Tin nhắn mới từ ${message.sender?.name || 'Thành viên'}`, {
              body: message.content,
              icon: '/favicon.ico'
            });
          } catch (e) {
            console.error('System Notification error:', e);
          }
        }
      }
    });

    socketInstance.on('connectionAccepted', (data: any) => {
      window.dispatchEvent(new CustomEvent('app:connectionAccepted', { detail: data }));
      notify({
        title: 'Kết nối mới',
        message: `${data.acceptedByName} đã chấp nhận yêu cầu kết nối của bạn.`,
        type: 'success'
      });
    });

    socketInstance.on('joinRequestAccepted', (data: any) => {
      window.dispatchEvent(new CustomEvent('app:joinRequestAccepted', { detail: data }));
      notify({
        title: 'Yêu cầu tham gia được duyệt',
        message: `Yêu cầu tham gia hành trình "${data.tourTitle}" của bạn đã được chấp nhận!`,
        type: 'success'
      });
    });

    return () => {
      socketInstance.disconnect();
    };
  }, [user?.id, currentPage, currentTourId]);

  return null;
};

function App() {
  const params = new URLSearchParams(window.location.search);
  const viewTourId = params.get('viewTour');
  const pathParts = window.location.pathname.split('/');
  const isJourneyShare = pathParts[1] === 'journey' && pathParts[2];
  const journeyTokenVal = isJourneyShare ? pathParts[2] : null;

  const [user, setUser] = useState<any>(null);
  const [shareJourneyToken, setShareJourneyToken] = useState<string | null>(journeyTokenVal);
  const [currentPage, setCurrentPage] = useState<'landing' | 'dashboard' | 'admin' | 'explore' | 'tourDetail' | 'signup' | 'myPhotos' | 'notes' | 'joinTour' | 'shareJourney' | 'tourNavigation'>(
    journeyTokenVal ? 'shareJourney' : (viewTourId ? 'tourDetail' : (window.location.pathname === '/join-tour' || params.has('token') ? 'joinTour' : 'landing'))
  );
  const [currentTourId, setCurrentTourId] = useState<string | null>(viewTourId);
  const [isPublicTourView, setIsPublicTourView] = useState(!!viewTourId);
  const [previousPage, setPreviousPage] = useState<'explore' | 'landing'>('explore');
  const [navigationPayload, setNavigationPayload] = useState<{ tourId: string; origin: { lat: number; lng: number }; destination: { lat: number; lng: number; name: string }; tourTitle: string } | null>(null);

  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    const viewTourId = params.get('viewTour');
    const isJoinTour = window.location.pathname === '/join-tour' || params.has('token');
    const pathParts = window.location.pathname.split('/');
    const journeyToken = pathParts[1] === 'journey' && pathParts[2] ? pathParts[2] : null;

    // Check if user just finished uploading from a public tour
    const fromPublicUpload = localStorage.getItem('fromPublicUpload');
    if (fromPublicUpload) {
      localStorage.removeItem('fromPublicUpload');
      setCurrentPage('landing');
      return;
    }

    // Khôi phục thông tin đăng nhập nếu có
    const token = localStorage.getItem('token');
    const guestToken = localStorage.getItem('guest_token');
    const storedUser = localStorage.getItem('user');
    
    let loggedInUser = null;
    if (token && storedUser) {
      try {
        loggedInUser = JSON.parse(storedUser);
        setUser(loggedInUser);
      } catch (e) {
        localStorage.removeItem('token');
        localStorage.removeItem('user');
      }
    }

    if (journeyToken) {
      setShareJourneyToken(journeyToken);
      setCurrentPage('shareJourney');
    } else if (isJoinTour) {
      setCurrentPage('joinTour');
    } else if (viewTourId) {
      setCurrentPage('tourDetail');
    } else {
      // CRITICAL: Check for guest token FIRST - guests should NEVER access dashboard
      // regardless of whether they also have other tokens
      if (guestToken) {
        setCurrentPage('landing');
      } else if (loggedInUser) {
        // Real authenticated user (no guest token)
        if (loggedInUser.isAdmin) {
          setCurrentPage('admin');
        } else {
          setCurrentPage('landing');
        }
      } else {
        setCurrentPage('landing');
      }
    }
  }, []);

  const handleLoginSuccess = (loggedInUser: any) => {
    setUser(loggedInUser);
    
    // Nếu có pending token, ta vẫn giữ ở trang joinTour để nó tự động thực hiện join
    const pendingInviteToken = localStorage.getItem('pendingInviteToken');
    if (pendingInviteToken) {
      setCurrentPage('joinTour');
    } else if (loggedInUser.isAdmin) {
      // Nếu là admin, chuyển đến admin dashboard
      setCurrentPage('admin');
    } else {
      // Keep on current page after successful login, modal will close
    }
  };

  const handleLogout = () => {
    localStorage.removeItem('token');
    localStorage.removeItem('user');
    setUser(null);
    setCurrentPage('landing');
  };


  const handleViewTour = (tourId: string, fromPage?: 'explore') => {
    setCurrentTourId(tourId);
    setIsPublicTourView(false); // Không phải chế độ công khai nếu đến từ bản đồ khám phá
    setPreviousPage(fromPage || 'explore');
    setCurrentPage('tourDetail');
  };

  const handleBackFromTourDetail = () => {
    const wasPublicView = isPublicTourView;
    
    setCurrentTourId(null);
    setIsPublicTourView(false);
    
    if (wasPublicView) {
      setCurrentPage('landing');
    } else if (user) {
      setCurrentPage(previousPage);
    } else {
      setCurrentPage('landing');
    }
  };

  const handleOpenNavigationPage = (payload: { tourId: string; origin: { lat: number; lng: number }; destination: { lat: number; lng: number; name: string }; tourTitle: string }) => {
    setNavigationPayload(payload);
    setCurrentPage('tourNavigation');
  };

  const handleBackFromNavigation = () => {
    setNavigationPayload(null);
    setCurrentPage('tourDetail');
  };

  const handleBackFromSignup = () => {
    const pendingInviteToken = localStorage.getItem('pendingInviteToken');
    if (pendingInviteToken) {
      setCurrentPage('joinTour');
    } else {
      setCurrentPage('landing');
    }
  };

  const handleSignupSuccess = () => {
    // Sau khi đăng ký, ta có thể tự động đăng nhập hoặc quay lại landing/joinTour
    const pendingInviteToken = localStorage.getItem('pendingInviteToken');
    const token = localStorage.getItem('token');
    const storedUser = localStorage.getItem('user');

    if (token && storedUser) {
      try {
        const loggedInUser = JSON.parse(storedUser);
        setUser(loggedInUser);
        if (pendingInviteToken) {
          setCurrentPage('joinTour');
        } else {
          setCurrentPage('dashboard');
        }
        return;
      } catch (e) {}
    }

    if (pendingInviteToken) {
      setCurrentPage('joinTour');
    } else {
      setCurrentPage('landing');
    }
  };

  const handleBackFromExplore = () => {
    setCurrentPage('landing');
  };

  const handleGoToDashboard = (_tab?: 'tours' | 'connections' | 'photos' | 'chats') => {
    // Deprecated dashboard redirect: keeping empty function to satisfy interface prop requirements
  };

  const handleGoToHome = () => {
    window.history.pushState({}, '', '/');
    setShareJourneyToken(null);
    const token = localStorage.getItem('token');
    const guestToken = localStorage.getItem('guest_token');
    // Only real authenticated users can access dashboard, not guests
    const isRealUser = token && !guestToken;
    setCurrentPage(isRealUser ? 'dashboard' : 'landing');
  };

  return (
    <ConfirmProvider>
      <NotificationProvider>
        {user && (
          <GlobalNotificationListener
            user={user}
            currentPage={currentPage}
            currentTourId={currentTourId}
          />
        )}
        {(() => {
        if (currentPage === 'admin') {
          return (
            <AdminDashboard
              user={user}
              onNavigate={(page) => setCurrentPage(page as any)}
            />
          );
        }

        if (currentPage === 'tourDetail') {
          return (
            <TourDetailPage
              tourId={currentTourId!} 
              onBack={handleBackFromTourDetail}
              isPublicView={isPublicTourView}
              onOpenNotes={() => setCurrentPage('notes')}
              onOpenNavigationPage={(routeData) => handleOpenNavigationPage({
                tourId: currentTourId!,
                ...routeData
              })}
            />
          );
        }

        if (currentPage === 'notes') {
          return <MyNotePage tourId={currentTourId!} onBack={() => setCurrentPage('tourDetail')} />;
        }

        if (currentPage === 'tourNavigation' && navigationPayload) {
          return (
            <TourNavigationPage
              tourId={navigationPayload.tourId}
              routeData={{
                origin: navigationPayload.origin,
                destination: navigationPayload.destination
              }}
              onBack={handleBackFromNavigation}
            />
          );
        }

        if (currentPage === 'explore') {
          return (
            <ExploreMap 
              onBack={handleBackFromExplore} 
              onLogout={handleLogout} 
              user={user} 
              onViewTour={handleViewTour} 
              onLoginSuccess={handleLoginSuccess}
              onGoToDashboard={handleGoToDashboard}
              onOpenNavigation={handleOpenNavigationPage}
            />
          );
        }

        if (currentPage === 'myPhotos') {
          return (
            <MyPhotosPage onBack={() => setCurrentPage('explore')} />
          );
        }

        if (currentPage === 'signup') {
          return <SignupPage onBack={handleBackFromSignup} onSuccess={handleSignupSuccess} />;
        }

        if (currentPage === 'joinTour') {
          return (
            <JoinTourPage
              onLoginSuccess={handleLoginSuccess}
              onGoToSignup={() => setCurrentPage('signup')}
              onViewTour={(tourId) => {
                setCurrentTourId(tourId);
                setIsPublicTourView(false);
                setCurrentPage('tourDetail');
              }}
              onGoToHome={() => {
                const loggedIn = !!localStorage.getItem('token');
                setCurrentPage(loggedIn ? 'explore' : 'landing');
              }}
            />
          );
        }

        if (currentPage === 'shareJourney') {
          return (
            <ShareJourneyPage
              token={shareJourneyToken!}
              onGoToHome={handleGoToHome}
            />
          );
        }

        return (
          <LandingPage 
            onContinue={() => setCurrentPage('explore')} 
            onGoToSignup={() => setCurrentPage('signup')} 
            onGoToMap={() => setCurrentPage('explore')} 
            onLoginSuccess={handleLoginSuccess} 
            user={user}
            onLogout={handleLogout}
            onGoToDashboard={handleGoToDashboard}
            onOpenNavigation={handleOpenNavigationPage}
          />
        );
      })()}
      </NotificationProvider>
    </ConfirmProvider>
  );
}

export default App;