/**
 * @ai-summary Main app component with routing and mobile navigation
 */

import { useState, useEffect, useTransition, useCallback, lazy } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { Routes, Route, Navigate } from 'react-router-dom';
import { useAuth0 } from '@auth0/auth0-react';
import { motion, AnimatePresence } from 'framer-motion';
import { ThemeProvider } from '@mui/material/styles';
import CssBaseline from '@mui/material/CssBaseline';
import HomeRoundedIcon from '@mui/icons-material/HomeRounded';
import DirectionsCarRoundedIcon from '@mui/icons-material/DirectionsCarRounded';
import LocalGasStationRoundedIcon from '@mui/icons-material/LocalGasStationRounded';
import SettingsRoundedIcon from '@mui/icons-material/SettingsRounded';
import { md3Theme } from './shared-minimal/theme/md3Theme';
import { Layout } from './components/Layout';
import { UnitsProvider } from './core/units/UnitsContext';

// Lazy load route components for better initial bundle size
const VehiclesPage = lazy(() => import('./features/vehicles/pages/VehiclesPage').then(m => ({ default: m.VehiclesPage })));
const VehicleDetailPage = lazy(() => import('./features/vehicles/pages/VehicleDetailPage').then(m => ({ default: m.VehicleDetailPage })));
const SettingsPage = lazy(() => import('./pages/SettingsPage').then(m => ({ default: m.SettingsPage })));
const FuelLogsPage = lazy(() => import('./features/fuel-logs/pages/FuelLogsPage').then(m => ({ default: m.FuelLogsPage })));
const VehiclesMobileScreen = lazy(() => import('./features/vehicles/mobile/VehiclesMobileScreen').then(m => ({ default: m.VehiclesMobileScreen })));
const VehicleDetailMobile = lazy(() => import('./features/vehicles/mobile/VehicleDetailMobile').then(m => ({ default: m.VehicleDetailMobile })));
import { BottomNavigation, NavigationItem } from './shared-minimal/components/mobile/BottomNavigation';
import { GlassCard } from './shared-minimal/components/mobile/GlassCard';
import { Button } from './shared-minimal/components/Button';
import { RouteSuspense } from './components/SuspenseWrappers';
import { Vehicle } from './features/vehicles/types/vehicles.types';
import { FuelLogForm } from './features/fuel-logs/components/FuelLogForm';
import { FuelLogsList } from './features/fuel-logs/components/FuelLogsList';
import { FuelLogEditDialog } from './features/fuel-logs/components/FuelLogEditDialog';
import { useFuelLogs } from './features/fuel-logs/hooks/useFuelLogs';
import { FuelLogResponse, UpdateFuelLogRequest } from './features/fuel-logs/types/fuel-logs.types';
import { fuelLogsApi } from './features/fuel-logs/api/fuel-logs.api';
import { VehicleForm } from './features/vehicles/components/VehicleForm';
import { useOptimisticVehicles } from './features/vehicles/hooks/useOptimisticVehicles';
import { CreateVehicleRequest } from './features/vehicles/types/vehicles.types';
import { MobileSettingsScreen } from './features/settings/mobile/MobileSettingsScreen';
import { useNavigationStore, useUserStore } from './core/store';
import { useDataSync } from './core/hooks/useDataSync';
import { MobileDebugPanel } from './core/debug/MobileDebugPanel';
import { MobileErrorBoundary } from './core/error-boundaries/MobileErrorBoundary';

// Hoisted mobile screen components to stabilize identity and prevent remounts
const DashboardScreen: React.FC = () => (
  <div className="space-y-4">
    <GlassCard>
      <div className="text-center py-12">
        <h2 className="text-lg font-semibold text-slate-800 mb-2">Dashboard</h2>
        <p className="text-slate-500">Coming soon - Vehicle insights and analytics</p>
      </div>
    </GlassCard>
  </div>
);

const LogFuelScreen: React.FC = () => {
  const queryClient = useQueryClient();
  const [editingLog, setEditingLog] = useState<FuelLogResponse | null>(null);
  const { goBack, canGoBack, navigateToScreen } = useNavigationStore();
  useEffect(() => {
    console.log('[LogFuelScreen] Mounted');
    return () => console.log('[LogFuelScreen] Unmounted');
  }, []);

  let fuelLogs: FuelLogResponse[] | undefined, isLoading: boolean | undefined, error: any;
  try {
    const hookResult = useFuelLogs();
    fuelLogs = hookResult.fuelLogs;
    isLoading = hookResult.isLoading;
    error = hookResult.error;
  } catch (hookError) {
    console.error('[LogFuelScreen] Hook error:', hookError);
    error = hookError;
  }

  const handleEdit = (log: FuelLogResponse) => {
    if (!log || !log.id) {
      console.error('[LogFuelScreen] Invalid log data for edit:', log);
      return;
    }
    try {
      setEditingLog(log);
    } catch (error) {
      console.error('[LogFuelScreen] Error setting editing log:', error);
    }
  };

  const handleDelete = async (_logId: string) => {
    try {
      queryClient.invalidateQueries({ queryKey: ['fuelLogs'] });
      queryClient.invalidateQueries({ queryKey: ['fuelLogsStats'] });
    } catch (error) {
      console.error('Failed to refresh fuel logs after delete:', error);
    }
  };

  const handleSaveEdit = async (id: string, data: UpdateFuelLogRequest) => {
    try {
      await fuelLogsApi.update(id, data);
      queryClient.invalidateQueries({ queryKey: ['fuelLogs'] });
      queryClient.invalidateQueries({ queryKey: ['fuelLogsStats'] });
      setEditingLog(null);
    } catch (error) {
      console.error('Failed to update fuel log:', error);
      throw error;
    }
  };

  const handleCloseEdit = () => setEditingLog(null);

  if (error) {
    return (
      <div className="space-y-4">
        <GlassCard>
          <div className="text-center py-8">
            <p className="text-red-600 mb-4">Failed to load fuel logs</p>
            <button
              onClick={() => window.location.reload()}
              className="px-4 py-2 bg-blue-600 text-white rounded-lg"
            >
              Retry
            </button>
          </div>
        </GlassCard>
      </div>
    );
  }

  if (isLoading === undefined) {
    return (
      <div className="space-y-4">
        <GlassCard>
          <div className="text-center py-8 text-slate-500">
            Initializing fuel logs...
          </div>
        </GlassCard>
      </div>
    );
  }

  return (
    <div className="space-y-4">
      <MobileErrorBoundary screenName="FuelLogForm" key="fuel-form">
        <FuelLogForm onSuccess={() => {
          // Refresh dependent data
          try {
            queryClient.invalidateQueries({ queryKey: ['fuelLogs'] });
            queryClient.invalidateQueries({ queryKey: ['fuelLogsStats'] });
          } catch {}
          // Navigate back if we have history; otherwise go to Vehicles
          if (canGoBack()) {
            goBack();
          } else {
            navigateToScreen('Vehicles', { source: 'fuel-log-added' });
          }
        }} />
      </MobileErrorBoundary>
      <MobileErrorBoundary screenName="FuelLogsSection" key="fuel-section">
        <GlassCard>
          <div className="py-2">
            {isLoading ? (
              <div className="text-center py-8 text-slate-500">
                Loading fuel logs...
              </div>
            ) : (
              <FuelLogsList
                logs={fuelLogs || []}
                onEdit={handleEdit}
                onDelete={handleDelete}
              />
            )}
          </div>
        </GlassCard>
      </MobileErrorBoundary>

      <MobileErrorBoundary screenName="FuelLogEditDialog" key="fuel-edit-dialog">
        <FuelLogEditDialog
          open={!!editingLog}
          log={editingLog}
          onClose={handleCloseEdit}
          onSave={handleSaveEdit}
        />
      </MobileErrorBoundary>
    </div>
  );
};

interface AddVehicleScreenProps {
  onBack: () => void;
  onAdded: () => void;
}

const AddVehicleScreen: React.FC<AddVehicleScreenProps> = ({ onBack, onAdded }) => {
  const { optimisticCreateVehicle } = useOptimisticVehicles([]);

  const handleCreateVehicle = async (data: CreateVehicleRequest) => {
    try {
      await optimisticCreateVehicle(data);
      onAdded();
    } catch (error) {
      console.error('Failed to create vehicle:', error);
    }
  };

  return (
    <div className="space-y-4">
      <GlassCard>
        <div className="p-4">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-lg font-semibold text-slate-800">Add Vehicle</h2>
            <button
              onClick={onBack}
              className="p-2 hover:bg-gray-100 rounded-full transition-colors"
            >
              ✕
            </button>
          </div>
          <VehicleForm
            onSubmit={handleCreateVehicle}
            onCancel={onBack}
          />
        </div>
      </GlassCard>
    </div>
  );
};

function App() {
  const { isLoading, isAuthenticated, loginWithRedirect, user } = useAuth0();
  const [_isPending, startTransition] = useTransition();

  // Initialize data synchronization
  const { prefetchForNavigation } = useDataSync();

  // Enhanced navigation and user state management
  const {
    activeScreen,
    vehicleSubScreen,
    navigateToScreen,
    navigateToVehicleSubScreen,
    goBack,
    canGoBack,
  } = useNavigationStore();

  const { setUserProfile } = useUserStore();

  // Mobile mode detection - detect mobile screen size with responsive updates
  const [mobileMode, setMobileMode] = useState(() => {
    if (typeof window !== 'undefined') {
      return window.innerWidth <= 768;
    }
    return false;
  });

  const [selectedVehicle, setSelectedVehicle] = useState<Vehicle | null>(null);
  const [showAddVehicle, setShowAddVehicle] = useState(false);

  // Update mobile mode on window resize
  useEffect(() => {
    const checkMobileMode = () => {
      const isMobile = window.innerWidth <= 768 ||
                      /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
      console.log('Window width:', window.innerWidth, 'User agent mobile:', /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent), 'Mobile mode:', isMobile);
      setMobileMode(isMobile);
    };

    // Check on mount
    checkMobileMode();

    window.addEventListener('resize', checkMobileMode);
    return () => window.removeEventListener('resize', checkMobileMode);
  }, []);

  // Update user profile when authenticated
  useEffect(() => {
    if (isAuthenticated && user) {
      setUserProfile(user);
    }
  }, [isAuthenticated, user, setUserProfile]);

  // Handle mobile back button and navigation errors
  useEffect(() => {
    const handlePopState = (event: PopStateEvent) => {
      event.preventDefault();
      if (canGoBack() && mobileMode) {
        goBack();
      }
    };

    if (mobileMode) {
      window.addEventListener('popstate', handlePopState);
      return () => window.removeEventListener('popstate', handlePopState);
    }

    return undefined;
  }, [goBack, canGoBack, mobileMode]);

  // Mobile navigation items
  const mobileNavItems: NavigationItem[] = [
    { key: "Dashboard", label: "Dashboard", icon: <HomeRoundedIcon /> },
    { key: "Vehicles", label: "Vehicles", icon: <DirectionsCarRoundedIcon /> },
    { key: "Log Fuel", label: "Log Fuel", icon: <LocalGasStationRoundedIcon /> },
    { key: "Settings", label: "Settings", icon: <SettingsRoundedIcon /> },
  ];

  console.log('MotoVaultPro status:', { isLoading, isAuthenticated, mobileMode, activeScreen, vehicleSubScreen, userAgent: navigator.userAgent });

  // Enhanced navigation handlers for mobile
  const handleVehicleSelect = useCallback((vehicle: Vehicle) => {
    setSelectedVehicle(vehicle);
    navigateToVehicleSubScreen('detail', vehicle.id, { source: 'vehicle-list' });
  }, [navigateToVehicleSubScreen]);

  const handleAddVehicle = useCallback(() => {
    setShowAddVehicle(true);
    navigateToVehicleSubScreen('add', undefined, { source: 'vehicle-list' });
  }, [navigateToVehicleSubScreen]);

  const handleBackToList = useCallback(() => {
    setSelectedVehicle(null);
    setShowAddVehicle(false);
    navigateToVehicleSubScreen('list', undefined, { source: 'back-navigation' });
  }, [navigateToVehicleSubScreen]);

  const handleVehicleAdded = useCallback(() => {
    setShowAddVehicle(false);
    navigateToVehicleSubScreen('list', undefined, { source: 'vehicle-added' });
  }, [navigateToVehicleSubScreen]);

  // Enhanced debug component
  const DebugInfo = () => (
    <MobileDebugPanel visible={import.meta.env.MODE === 'development'} />
  );

  // Mobile settings now uses the dedicated MobileSettingsScreen component
  const SettingsScreen = MobileSettingsScreen;

  if (isLoading) {
    if (mobileMode) {
      return (
        <ThemeProvider theme={md3Theme}>
          <CssBaseline />
          <Layout mobileMode={true}>
            <div className="flex items-center justify-center h-64">
              <div className="text-slate-500">Loading...</div>
            </div>
          </Layout>
        </ThemeProvider>
      );
    }
    return (
      <ThemeProvider theme={md3Theme}>
        <CssBaseline />
        <div className="flex items-center justify-center min-h-screen">
          <div className="text-lg">Loading...</div>
        </div>
      </ThemeProvider>
    );
  }

  if (!isAuthenticated) {
    if (mobileMode) {
      return (
        <ThemeProvider theme={md3Theme}>
          <CssBaseline />
          <Layout mobileMode={true}>
            <div className="space-y-6 flex flex-col items-center justify-center min-h-[400px]">
              <div className="text-center">
                <h1 className="text-2xl font-bold text-slate-800 mb-3">Welcome to MotoVaultPro</h1>
                <p className="text-slate-600 mb-6 text-sm">Your personal vehicle management platform</p>
                <button
                  onClick={() => loginWithRedirect()}
                  className="h-12 px-8 rounded-2xl text-white font-medium shadow-lg active:scale-[0.99] transition bg-gradient-moto"
                >
                  Login to Continue
                </button>
              </div>
            </div>
            <DebugInfo />
          </Layout>
        </ThemeProvider>
      );
    }
    return (
      <ThemeProvider theme={md3Theme}>
        <CssBaseline />
        <div className="flex items-center justify-center min-h-screen bg-gray-50">
          <div className="text-center max-w-md mx-auto px-6">
            <h1 className="text-4xl font-bold text-gray-900 mb-4">MotoVaultPro</h1>
            <p className="text-gray-600 mb-8">Your personal vehicle management platform</p>
            <Button onClick={() => loginWithRedirect()}>
              Login to Continue
            </Button>
          </div>
          <DebugInfo />
        </div>
      </ThemeProvider>
    );
  }

  // Mobile app rendering
  if (mobileMode) {
    return (
      <ThemeProvider theme={md3Theme}>
        <CssBaseline />
        <UnitsProvider>
          <Layout mobileMode={true}>
          <AnimatePresence mode="popLayout" initial={false}>
            {activeScreen === "Dashboard" && (
              <motion.div
                key="dashboard"
                initial={{opacity:0, y:8}}
                animate={{opacity:1, y:0}}
                exit={{opacity:0, y:-8}}
                transition={{ duration: 0.2, ease: "easeOut" }}
              >
                <MobileErrorBoundary screenName="Dashboard">
                  <DashboardScreen />
                </MobileErrorBoundary>
              </motion.div>
            )}
            {activeScreen === "Vehicles" && (
              <motion.div
                key="vehicles"
                initial={{opacity:0, y:8}}
                animate={{opacity:1, y:0}}
                exit={{opacity:0, y:-8}}
                className="space-y-6"
                transition={{ duration: 0.2, ease: "easeOut" }}
              >
                <MobileErrorBoundary screenName="Vehicles">
                  {vehicleSubScreen === 'add' || showAddVehicle ? (
                    <AddVehicleScreen onBack={handleBackToList} onAdded={handleVehicleAdded} />
                  ) : selectedVehicle && (vehicleSubScreen === 'detail') ? (
                    <VehicleDetailMobile
                      vehicle={selectedVehicle}
                      onBack={handleBackToList}
                      onLogFuel={() => navigateToScreen("Log Fuel")}
                    />
                  ) : (
                    <VehiclesMobileScreen
                      onVehicleSelect={handleVehicleSelect}
                      onAddVehicle={handleAddVehicle}
                    />
                  )}
                </MobileErrorBoundary>
              </motion.div>
            )}
            {activeScreen === "Log Fuel" && (
              <motion.div
                key="logfuel"
                initial={{opacity:0, y:8}}
                animate={{opacity:1, y:0}}
                exit={{opacity:0, y:-8}}
                transition={{ duration: 0.2, ease: "easeOut" }}
              >
                <MobileErrorBoundary screenName="Log Fuel">
                  <LogFuelScreen />
                </MobileErrorBoundary>
              </motion.div>
            )}
            {activeScreen === "Settings" && (
              <motion.div
                key="settings"
                initial={{opacity:0, y:8}}
                animate={{opacity:1, y:0}}
                exit={{opacity:0, y:-8}}
                transition={{ duration: 0.2, ease: "easeOut" }}
              >
                <MobileErrorBoundary screenName="Settings">
                  <SettingsScreen />
                </MobileErrorBoundary>
              </motion.div>
            )}
          </AnimatePresence>
          <DebugInfo />
        </Layout>
        
        <BottomNavigation
          items={mobileNavItems}
          activeItem={activeScreen}
          onItemSelect={(screen) => startTransition(() => {
            // Prefetch data for the target screen
            prefetchForNavigation(screen);

            // Reset states first, then navigate to prevent race conditions
            if (screen !== 'Vehicles') {
              setSelectedVehicle(null); // Reset selected vehicle when leaving Vehicles
            }
            if (screen !== 'Vehicles' || vehicleSubScreen !== 'add') {
              setShowAddVehicle(false); // Reset add vehicle form when appropriate
            }

            // Navigate after state cleanup
            navigateToScreen(screen as any, { source: 'bottom-navigation' });
          })}
        />
        </UnitsProvider>
      </ThemeProvider>
    );
  }

  // Desktop app rendering (fallback)
  return (
    <ThemeProvider theme={md3Theme}>
      <CssBaseline />
      <UnitsProvider>
        <Layout mobileMode={false}>
        <RouteSuspense>
          <Routes>
            <Route path="/" element={<Navigate to="/vehicles" replace />} />
            <Route path="/callback" element={<div>Processing login...</div>} />
            <Route path="/vehicles" element={<VehiclesPage />} />
            <Route path="/vehicles/:id" element={<VehicleDetailPage />} />
            <Route path="/fuel-logs" element={<FuelLogsPage />} />
            <Route path="/maintenance" element={<div>Maintenance (TODO)</div>} />
            <Route path="/stations" element={<div>Stations (TODO)</div>} />
            <Route path="/settings" element={<SettingsPage />} />
            <Route path="*" element={<Navigate to="/vehicles" replace />} />
          </Routes>
        </RouteSuspense>
        <DebugInfo />
      </Layout>
      </UnitsProvider>
    </ThemeProvider>
  );
}

export default App;
