/*
 * File: App.tsx
 * Description: Main application component with navigation setup
 * Design & Developed by Tech4Biz Solutions
 * Copyright (c) Spurrin Innovations. All rights reserved.
 */

import React, { useRef } from 'react';
import { StatusBar } from 'react-native';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import { NavigationContainer, NavigationContainerRef } from '@react-navigation/native';
import { theme } from './theme/theme';
import { RootStackNavigator, setNavigationRef } from './navigation';
import { StoreProvider } from './store/Provider';
import Toast from 'react-native-toast-message';
import { useAppSelector } from './store/hooks';
import { selectIsAuthenticated } from './modules/Auth/redux/authSelectors';

// ============================================================================
// MOCK DATA SECTION - For demonstration and development purposes
// ============================================================================

// Mock dashboard data representing the current state of the ER
const mockDashboard = {
  totalPatients: 24,           // Total number of patients in ER
  criticalPatients: 3,         // Number of patients requiring immediate attention
  pendingScans: 8,            // Number of scans waiting for review
  recentReports: 12,          // Number of reports generated recently
  bedOccupancy: 85,           // Percentage of beds currently occupied
  departmentStats: {
    emergency: 8,             // Patients in emergency department
    trauma: 4,                // Patients in trauma department
    cardiac: 3,               // Patients in cardiac department
    neurology: 2,             // Patients in neurology department
    pediatrics: 5,            // Patients in pediatrics department
    icu: 2,                   // Patients in ICU
  },
  shiftInfo: {
    currentShift: 'DAY' as const,           // Current shift (DAY/NIGHT)
    startTime: new Date(),                  // Shift start time
    endTime: new Date(),                    // Shift end time
    attendingPhysician: 'Dr. Smith',        // Lead physician on duty
    residents: ['Dr. Johnson', 'Dr. Williams'], // Resident physicians
    nurses: ['Nurse Brown', 'Nurse Davis'],     // Nursing staff
  },
  lastUpdated: new Date(),    // Last time dashboard was updated
};

// Mock patient data representing real patients in the ER
const mockPatients = [
  {
    id: '1',                  // Unique patient identifier
    mrn: 'MRN001',           // Medical Record Number
    firstName: 'John',
    lastName: 'Doe',
    dateOfBirth: new Date('1985-03-15'),
    gender: 'MALE' as const,
    age: 38,
    bedNumber: 'A1',         // Assigned bed number
    roomNumber: '101',       // Room number
    admissionDate: new Date('2024-01-15'),
    status: 'ACTIVE' as const,    // Current patient status
    priority: 'CRITICAL' as const, // Priority level for treatment
    department: 'Emergency',
    attendingPhysician: 'Dr. Smith',
    allergies: [
      { 
        id: '1', 
        name: 'Penicillin', 
        severity: 'SEVERE' as const, 
        reaction: 'Anaphylaxis' 
      },
    ],
    medications: [
      {
        id: '1',
        name: 'Morphine',
        dosage: '2mg',
        frequency: 'Every 4 hours',
        route: 'IV',              // Administration route
        startDate: new Date(),
        status: 'ACTIVE' as const,
        prescribedBy: 'Dr. Smith',
      },
    ],
    vitalSigns: {
      bloodPressure: { systolic: 140, diastolic: 90, timestamp: new Date() },
      heartRate: { value: 95, timestamp: new Date() },
      temperature: { value: 37.2, timestamp: new Date() },
      respiratoryRate: { value: 18, timestamp: new Date() },
      oxygenSaturation: { value: 98, timestamp: new Date() },
    },
    medicalHistory: [],
    currentDiagnosis: 'Chest pain, rule out MI',  // Current medical diagnosis
    lastUpdated: new Date(),
  },
  {
    id: '2',
    mrn: 'MRN002',
    firstName: 'Jane',
    lastName: 'Smith',
    dateOfBirth: new Date('1990-07-22'),
    gender: 'FEMALE' as const,
    age: 33,
    bedNumber: 'B2',
    roomNumber: '102',
    admissionDate: new Date('2024-01-15'),
    status: 'ACTIVE' as const,
    priority: 'HIGH' as const,
    department: 'Trauma',
    attendingPhysician: 'Dr. Johnson',
    allergies: [],
    medications: [],
    vitalSigns: {
      bloodPressure: { systolic: 120, diastolic: 80, timestamp: new Date() },
      heartRate: { value: 88, timestamp: new Date() },
      temperature: { value: 36.8, timestamp: new Date() },
      respiratoryRate: { value: 16, timestamp: new Date() },
      oxygenSaturation: { value: 99, timestamp: new Date() },
    },
    medicalHistory: [],
    currentDiagnosis: 'Multiple trauma from MVA',  // MVA = Motor Vehicle Accident
    lastUpdated: new Date(),
  },
];

// Mock alerts representing critical notifications that require immediate attention
const mockAlerts = [
  {
    id: '1',
    type: 'CRITICAL_FINDING' as const,      // Type of alert
    priority: 'CRITICAL' as const,          // Priority level
    title: 'Critical Finding Detected',
    message: 'AI has detected a potential brain bleed in CT scan. Immediate review required.',
    patientId: '1',                         // Associated patient
    patientName: 'John Doe',
    bedNumber: 'A1',
    timestamp: new Date(),                  // When alert was generated
    isRead: false,                          // Whether alert has been read
    isAcknowledged: false,                  // Whether alert has been acknowledged
    actionRequired: true,                   // Whether action is required
  },
];

/**
 * AppContent Component (Inner Component)
 * 
 * Purpose: Inner component that uses Redux hooks for authentication state
 * 
 * Features:
 * 1. Connect to Redux store for authentication state
 * 2. Set up navigation container with global reference
 * 3. Configure status bar appearance
 * 4. Render the main app navigator based on authentication state
 * 
 * Navigation Flow:
 * 1. App starts → Check Redux authentication status
 * 2. If not authenticated → Show LoginScreen
 * 3. If authenticated → Show MainTabNavigator (dashboard)
 */
function AppContent() {
  // ============================================================================
  // REDUX STATE
  // ============================================================================
  
  // Get authentication state from Redux
  const isAuthenticated = useAppSelector(selectIsAuthenticated);

  // Navigation reference for programmatic navigation
  const navigationRef = useRef<NavigationContainerRef<any> | null>(null);

  // ============================================================================
  // EFFECTS
  // ============================================================================

  // Set up navigation reference for global access
  React.useEffect(() => {
    setNavigationRef(navigationRef);
  }, []);

  // ============================================================================
  // RENDER SECTION
  // ============================================================================

  return (
    <SafeAreaProvider>
      <NavigationContainer ref={navigationRef}>
        <StatusBar
          barStyle="dark-content"                    // Dark text on light background
          backgroundColor={theme.colors.background}  // Status bar background color
        />
        <RootStackNavigator isAuthenticated={isAuthenticated} />
        <Toast     
          position='bottom'
          bottomOffset={20} 
        />
      </NavigationContainer>
    </SafeAreaProvider>
  );
}

/**
 * App Component (Root Component)
 * 
 * Purpose: Root component that wraps the entire application with Redux Provider
 * 
 * Features:
 * 1. Provide Redux store context
 * 2. Wrap the main app content
 * 3. Enable Redux state management throughout the app
 */
export default function App() {
  return (
    <StoreProvider>
      <AppContent />
    </StoreProvider>
  );
}

/*
 * End of File: App.tsx
 * Design & Developed by Tech4Biz Solutions
 * Copyright (c) Spurrin Innovations. All rights reserved.
 */ 