/*
 * File: PatientDetailsScreen.tsx
 * Description: Comprehensive patient details screen with DICOM image viewer and AI analysis
 * Design & Developed by Tech4Biz Solutions
 * Copyright (c) Spurrin Innovations. All rights reserved.
 * 
 * Features:
 * - Patient demographics and medical information
 * - Merged AI Analysis tab showing DICOM images alongside AI predictions
 * - Processing history and timeline
 * - Responsive design for different screen sizes
 * - Emergency actions for critical cases
 * - Clinical feedback system for AI predictions and DICOM images
 */

import React, { useEffect, useState, useCallback, useMemo } from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  Alert,
  Dimensions,
  Image,
  FlatList,
  RefreshControl,
  TextInput,
} from 'react-native';
import { theme } from '../../../theme/theme';
import { useAppDispatch, useAppSelector } from '../../../store/hooks';
import Icon from 'react-native-vector-icons/Feather';
import { SafeAreaView } from 'react-native-safe-area-context';
import { DicomViewerModal } from '../../../shared/components';

// Import types and API
import { patientAPI } from '../services/patientAPI';
import { selectUser } from '../../Auth/redux/authSelectors';
import { logoutUser } from '../../Auth/redux/authActions';
import { API_CONFIG } from '../../../shared/utils';
import { PatientDetailsScreenProps } from '../navigation/navigationTypes';

// Get screen dimensions
const { width: screenWidth, height: screenHeight } = Dimensions.get('window');

// ============================================================================
// INTERFACES
// ============================================================================



interface PatientInfo {
  name: string;
  age: string;
  sex: string;
  date: string;
  institution: string;
  modality: string;
  status: string;
  report_status: string;
  file_name: string;
  file_type: string;
  frame_count: number;
}

interface SeriesSummary {
  series_num: string;
  series_description: string;
  total_images: number;
  png_preview: string;
  modality: string;
}

interface Prediction {
  id: number;
  file_path: string;
  prediction: {
    label: string;
    finding_type: string;
    clinical_urgency: string;
    confidence_score: number;
    detailed_results: any;
    finding_category: string;
    primary_severity: string;
    anatomical_location: string;
  };
  processed_at: string;
  preview: string;
}

interface PatientData {
  patid: string;
  hospital_id: string;
  patient_info: PatientInfo;
  series_summary: SeriesSummary[];
  processing_metadata: any;
  total_predictions: number;
  first_processed_at: string;
  last_processed_at: string;
  predictions_by_series: { [key: string]: Prediction[] };
}

// ============================================================================
// PATIENT DETAILS SCREEN COMPONENT
// ============================================================================

/**
 * PatientDetailsScreen Component
 * 
 * Purpose: Comprehensive patient details display with DICOM image viewer
 * 
 * Features:
 * - Full patient demographic information
 * - Medical case details and status
 * - DICOM series information
 * - AI predictions and findings
 * - Image gallery with thumbnail previews
 * - Real-time data updates from API
 * - Emergency actions for critical cases
 * - Medical history and notes
 * - Modern healthcare-focused UI design
 * - Responsive layout for different screen sizes
 */
const PatientDetailsScreen: React.FC<PatientDetailsScreenProps> = ({ navigation, route }) => {
  // ============================================================================
  // STATE MANAGEMENT
  // ============================================================================
  
  const dispatch = useAppDispatch();
  
  // Route parameters
  const { patientId, patientName } = route.params;
  
  // Redux state
  const user = useAppSelector(selectUser);
  
  // Local state
  const [patientData, setPatientData] = useState<PatientData | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [selectedImageIndex, setSelectedImageIndex] = useState(0);
  const [showFullImage, setShowFullImage] = useState(false);
  const [activeTab, setActiveTab] = useState<'overview' | 'aiAnalysis' | 'history'>('overview');
  
  // DICOM Modal state
  const [dicomModalVisible, setDicomModalVisible] = useState(false);
  const [selectedDicomData, setSelectedDicomData] = useState<{
    dicomUrl: string;
    seriesData: SeriesSummary;
    prediction?: Prediction;
  } | null>(null);
  
  // Navigation state
  const [selectedSeriesForDetail, setSelectedSeriesForDetail] = useState<SeriesSummary | null>(null);

  // ============================================================================
  // DATA FETCHING
  // ============================================================================

  /**
   * Fetch Patient Data
   * 
   * Purpose: Fetch patient details from API
   */
  const fetchPatientData = useCallback(async () => {
    if (!user?.access_token) {
      setError('Authentication token not available');
      setIsLoading(false);
      return;
    }

    try {
      setIsLoading(true);
      setError(null);
      
      const response: any = await patientAPI.getPatientDetailsById(patientId, user.access_token);
      
      // Check for 401 Unauthorized response
      if (response.status === 401) {
        // Dispatch logout action to clear authentication state
        dispatch(logoutUser());
        setError('Session expired. Please login again.');
        return;
      }
      
      if (response.ok && response.data && response.data.data ) {
        setPatientData(response.data.data as PatientData);
      } else {
        setError(response.problem || 'Failed to fetch patient data');
      }
    } catch (err: any) {
      setError(err.message || 'An error occurred while fetching patient data');
    } finally {
      setIsLoading(false);
    }
  }, [patientId, user?.access_token, dispatch]);

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

  /**
   * Component Mount Effect
   * 
   * Purpose: Initialize screen and fetch patient data
   */
  useEffect(() => {
    fetchPatientData();
  }, [fetchPatientData]);

  /**
   * Navigation Title Effect
   * 
   * Purpose: Set navigation title when patient data is loaded
   */
  useEffect(() => {
    if (patientData) {
      navigation.setOptions({
        title: patientData.patient_info.name || 'Patient Details',
        headerShown: false,
      });
    }
  }, [navigation, patientData]);

  // ============================================================================
  // EVENT HANDLERS
  // ============================================================================

  /**
   * Handle Refresh
   * 
   * Purpose: Pull-to-refresh functionality
   */
  const handleRefresh = useCallback(async () => {
    setIsRefreshing(true);
    await fetchPatientData();
    setIsRefreshing(false);
  }, [fetchPatientData]);

  /**
   * Handle DICOM Image Press
   * 
   * Purpose: Open DICOM viewer modal for selected series
   * 
   * @param seriesIndex - Index of the series
   */
  const handleImagePress = useCallback((seriesIndex: number) => {
    if (!patientData || !patientData.series_summary[seriesIndex]) return;
    
    const series = patientData.series_summary[seriesIndex];
    const seriesPredictions = patientData.predictions_by_series[series.series_num] || [];
    const firstPrediction = seriesPredictions[0];
    
    if (firstPrediction?.preview) {
      const dicomUrl = API_CONFIG.BASE_URL +'/api/dicom'+ firstPrediction.file_path;
      setSelectedDicomData({
        dicomUrl,
        seriesData: series,
        prediction: firstPrediction,
      });
      setDicomModalVisible(true);
    } else {
      Alert.alert(
        'No DICOM Available',
        'No DICOM image is available for this series.',
        [{ text: 'OK' }]
      );
    }
  }, [patientData]);

  /**
   * Handle Open DICOM Modal
   * 
   * Purpose: Open DICOM modal with specific series and prediction data
   * 
   * @param series - Series data
   * @param prediction - Optional prediction data
   */
  const handleOpenDicomModal = useCallback((series: SeriesSummary, prediction?: Prediction) => {
    if (!patientData) return;
    
    const seriesPredictions = patientData.predictions_by_series[series.series_num] || [];
    const targetPrediction = prediction || seriesPredictions[0];
    
    if (targetPrediction?.preview) {
      const dicomUrl = API_CONFIG.DICOM_BASE_URL + targetPrediction.preview;
      
      setSelectedDicomData({
        dicomUrl,
        seriesData: series,
        prediction: targetPrediction,
      });
      setDicomModalVisible(true);
    } else {
      Alert.alert(
        'No DICOM Available',
        'No DICOM image is available for this series.',
        [{ text: 'OK' }]
      );
    }
  }, [patientData]);

  /**
   * Handle Close DICOM Modal
   * 
   * Purpose: Close DICOM viewer modal and reset state
   */
  const handleCloseDicomModal = useCallback(() => {
    setDicomModalVisible(false);
    setSelectedDicomData(null);
  }, []);

  /**
   * Get All Images from Series
   * 
   * Purpose: Extract image paths from DICOM series
   */
  const getAllImages = useCallback(() => {
    if (!patientData) return [];
    
    const images: string[] = [];
    patientData.series_summary.forEach(series => {
      if (series.png_preview) {
        images.push(series.png_preview);
      }
    });
    return images;
  }, [patientData]);

  /**
   * Get Series Info for Image Index
   * 
   * Purpose: Get series information for a given image index
   */
  const getSeriesInfoForImage = useCallback((imageIndex: number) => {
    if (!patientData || imageIndex < 0 || imageIndex >= patientData.series_summary.length) {
      return {
        seriesNum: '1',
        seriesDesc: 'Unknown Series',
        imageInSeries: 1,
        totalInSeries: 1
      };
    }
    
    const series = patientData.series_summary[imageIndex];
    return {
      seriesNum: series.series_num,
      seriesDesc: series.series_description,
      imageInSeries: 1,
      totalInSeries: series.total_images
    };
  }, [patientData]);

  /**
   * Handle Emergency Action
   * 
   * Purpose: Handle emergency actions for critical patients
   */
  const handleEmergencyAction = useCallback(() => {
    if (!patientData) return;
    
    Alert.alert(
      'Emergency Action Required',
      `Patient ${patientData.patient_info.name} requires immediate attention`,
      [
        {
          text: 'Call Code Blue',
          style: 'destructive',
          onPress: () => {
            // TODO: Implement emergency code calling
            Alert.alert('Emergency', 'Code Blue activated');
          },
        },
        {
          text: 'Alert Team',
          onPress: () => {
            // TODO: Implement team alerting
            Alert.alert('Alert', 'Team notified');
          },
        },
        {
          text: 'Cancel',
          style: 'cancel',
        },
      ]
    );
  }, [patientData]);

  /**
   * Handle Back Navigation
   * 
   * Purpose: Navigate back to previous screen
   */
  const handleBackPress = useCallback(() => {
    navigation.goBack();
  }, [navigation]);

  // ============================================================================
  // NAVIGATION HANDLERS
  // ============================================================================

  /**
   * Handle Navigate to Series Detail
   * 
   * Purpose: Navigate to detailed series view
   * 
   * @param series - Series data to view in detail
   */
  const handleNavigateToSeriesDetail = useCallback((series: SeriesSummary) => {
    if (!patientData) return;
    
    navigation.navigate('SeriesDetail', {
      patientId: patientData.patid,
      patientName: patientData.patient_info.name,
      seriesNumber: series.series_num,
      seriesData: series,
      patientData: patientData,
      // Pass the refresh function as callback so parent screen can update when feedback is submitted
      onFeedbackSubmitted: fetchPatientData
    });
  }, [navigation, patientData, fetchPatientData]);

  // ============================================================================
  // UTILITY FUNCTIONS
  // ============================================================================

  /**
   * Get Status Color
   * 
   * Purpose: Get appropriate color for patient status
   * 
   * @param status - Patient status
   */
  const getStatusColor = (status: string) => {
    switch (status.toLowerCase()) {
      case 'processed':
        return theme.colors.success;
      case 'pending':
        return theme.colors.warning;
      case 'error':
        return theme.colors.error;
      default:
        return theme.colors.info;
    }
  };

  /**
   * Get Clinical Urgency Color
   * 
   * Purpose: Get appropriate color for clinical urgency
   * 
   * @param urgency - Clinical urgency level
   */
  const getUrgencyColor = (urgency: string) => {
    switch (urgency.toLowerCase()) {
      case 'urgent':
        return theme.colors.error;
      case 'semi-urgent':
        return theme.colors.warning;
      case 'non-urgent':
        return theme.colors.success;
      default:
        return theme.colors.info;
    }
  };

  // ============================================================================
  // RENDER HELPERS
  // ============================================================================

  /**
   * Render Loading State
   * 
   * Purpose: Render loading state while fetching data
   */
  const renderLoadingState = () => (
    <View style={styles.loadingContainer}>
      <Icon name="loader" size={48} color={theme.colors.primary} />
      <Text style={styles.loadingText}>Loading patient data...</Text>
    </View>
  );

  /**
   * Render Error State
   * 
   * Purpose: Render error state when API fails
   */
  const renderErrorState = () => (
    <View style={styles.errorContainer}>
      <Icon name="alert-circle" size={48} color={theme.colors.error} />
      <Text style={styles.errorTitle}>Error Loading Patient Data</Text>
      <Text style={styles.errorMessage}>{error}</Text>
      <TouchableOpacity
        style={styles.retryButton}
        onPress={fetchPatientData}
        activeOpacity={0.7}
      >
        <Text style={styles.retryButtonText}>Retry</Text>
      </TouchableOpacity>
    </View>
  );

  /**
   * Render Patient Header
   * 
   * Purpose: Render patient identification and status section
   */
  const renderPatientHeader = () => {
    if (!patientData) return null;
    
    const isCritical = patientData.patient_info.status === 'Error' || 
                      patientData.patient_info.report_status === 'Critical';
    
    return (
      <View style={styles.patientHeader}>
        <View style={styles.patientInfo}>
          <View style={styles.patientAvatar}>
            <Icon name="user" size={32} color={theme.colors.primary} />
          </View>
          <View style={styles.patientDetails}>
            <Text style={styles.patientName}>
              {patientData.patient_info.name || 'Unknown Patient'}
            </Text>
            <Text style={styles.patientId}>
              ID: {patientData.patid}
            </Text>
            <View style={styles.patientMeta}>
              <Text style={styles.patientMetaText}>
                {patientData.patient_info.age || 'N/A'} • {patientData.patient_info.sex || 'N/A'}
              </Text>
              <View style={[
                styles.statusBadge,
                { backgroundColor: getStatusColor(patientData.patient_info.status) }
              ]}>
                <Text style={styles.statusText}>{patientData.patient_info.status}</Text>
              </View>
            </View>
          </View>
        </View>
        
        {isCritical && (
          <TouchableOpacity
            style={styles.emergencyButton}
            onPress={handleEmergencyAction}
          >
            <Icon name="alert-triangle" size={20} color={theme.colors.background} />
            <Text style={styles.emergencyButtonText}>EMERGENCY</Text>
          </TouchableOpacity>
        )}
      </View>
    );
  };

  /**
   * Render Tab Navigation
   * 
   * Purpose: Render tab navigation for different sections
   * 
   * Tab Structure:
   * - Overview: Patient demographics and medical information
   * - AI Analysis: Merged view of DICOM images and AI predictions (formerly separate Images and Predictions tabs)
   * - History: Processing history and notes
   */
  const renderTabNavigation = () => {
    if (!patientData) return null;
    
    return (
      <View style={styles.tabContainer}>
        {[
          { key: 'overview', label: 'Overview', icon: 'info' },
          { key: 'aiAnalysis', label: 'AI Analysis', icon: 'activity', count: patientData.series_summary.length },
          { key: 'history', label: 'History', icon: 'clock' },
        ].map((tab) => (
          <TouchableOpacity
            key={tab.key}
            style={[
              styles.tabButton,
              activeTab === tab.key && styles.activeTabButton
            ]}
            onPress={() => setActiveTab(tab.key as any)}
          >
            <Icon 
              name={tab.icon as any} 
              size={18} 
              color={activeTab === tab.key ? theme.colors.primary : theme.colors.textSecondary} 
            />
            <Text style={[
              styles.tabLabel,
              activeTab === tab.key && styles.activeTabLabel
            ]}>
              {tab.label}
            </Text>
            {tab.count !== undefined && (
              <View style={styles.tabCount}>
                <Text style={styles.tabCountText}>{tab.count}</Text>
              </View>
            )}
          </TouchableOpacity>
        ))}
      </View>
    );
  };

  /**
   * Render Overview Tab
   * 
   * Purpose: Render patient overview information
   */
  const renderOverviewTab = () => {
    if (!patientData) return null;
    
    return (
      <View style={styles.tabContent}>
        {/* Patient Information */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>Patient Information</Text>
          <View style={styles.infoGrid}>
            <View style={styles.infoItem}>
              <Text style={styles.infoLabel}>Patient ID</Text>
              <Text style={styles.infoValue}>{patientData.patid}</Text>
            </View>
            <View style={styles.infoItem}>
              <Text style={styles.infoLabel}>Hospital ID</Text>
              <Text style={styles.infoValue}>{patientData.hospital_id.substring(0, 8)}...</Text>
            </View>
            <View style={styles.infoItem}>
              <Text style={styles.infoLabel}>Name</Text>
              <Text style={styles.infoValue}>{patientData.patient_info.name}</Text>
            </View>
            <View style={styles.infoItem}>
              <Text style={styles.infoLabel}>Age</Text>
              <Text style={styles.infoValue}>{patientData.patient_info.age}</Text>
            </View>
            <View style={styles.infoItem}>
              <Text style={styles.infoLabel}>Sex</Text>
              <Text style={styles.infoValue}>{patientData.patient_info.sex}</Text>
            </View>
            <View style={styles.infoItem}>
              <Text style={styles.infoLabel}>Date</Text>
              <Text style={styles.infoValue}>{patientData.patient_info.date}</Text>
            </View>
          </View>
        </View>

        {/* Medical Information */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>Medical Information</Text>
          <View style={styles.infoGrid}>
            <View style={styles.infoItem}>
              <Text style={styles.infoLabel}>Institution</Text>
              <Text style={styles.infoValue}>{patientData.patient_info.institution}</Text>
            </View>
            <View style={styles.infoItem}>
              <Text style={styles.infoLabel}>Modality</Text>
              <Text style={styles.infoValue}>{patientData.patient_info.modality}</Text>
            </View>
            <View style={styles.infoItem}>
              <Text style={styles.infoLabel}>Status</Text>
              <Text style={styles.infoValue}>{patientData.patient_info.status}</Text>
            </View>
            <View style={styles.infoItem}>
              <Text style={styles.infoLabel}>Report Status</Text>
              <Text style={styles.infoValue}>{patientData.patient_info.report_status}</Text>
            </View>
            <View style={styles.infoItem}>
              <Text style={styles.infoLabel}>File Name</Text>
              <Text style={styles.infoValue} numberOfLines={2}>{patientData.patient_info.file_name}</Text>
            </View>
            <View style={styles.infoItem}>
              <Text style={styles.infoLabel}>Frame Count</Text>
              <Text style={styles.infoValue}>{patientData.patient_info.frame_count}</Text>
            </View>
          </View>
        </View>

        {/* Processing Information */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>Processing Information</Text>
          <View style={styles.infoGrid}>
            <View style={styles.infoItem}>
              <Text style={styles.infoLabel}>First Processed</Text>
              <Text style={styles.infoValue}>
                {new Date(patientData.first_processed_at).toLocaleDateString()}
              </Text>
            </View>
            <View style={styles.infoItem}>
              <Text style={styles.infoLabel}>Last Processed</Text>
              <Text style={styles.infoValue}>
                {new Date(patientData.last_processed_at).toLocaleDateString()}
              </Text>
            </View>
            <View style={styles.infoItem}>
              <Text style={styles.infoLabel}>Total Predictions</Text>
              <Text style={styles.infoValue}>{patientData.total_predictions}</Text>
            </View>
            <View style={styles.infoItem}>
              <Text style={styles.infoLabel}>Series Count</Text>
              <Text style={styles.infoValue}>{patientData.series_summary.length}</Text>
            </View>
          </View>
        </View>
      </View>
    );
  };

  /**
   * Render AI Analysis Tab
   * 
   * Purpose: Render AI predictions and findings alongside their related images
   * 
   * Features:
   * - Merged view of DICOM images and AI predictions
   * - Side-by-side display on larger screens, stacked on mobile
   * - Summary statistics at the top
   * - Series-based organization with integrated image and prediction data
   * - Responsive design for different screen sizes
   * - Feedback system for each series allowing physicians to provide clinical insights
   */
  const renderAIAnalysisTab = () => {
    if (!patientData) return null;
    
    if (patientData.series_summary.length === 0) {
      return (
        <View style={styles.tabContent}>
          <View style={styles.emptyState}>
            <Icon name="layers" size={48} color={theme.colors.textMuted} />
            <Text style={styles.emptyStateTitle}>No Images Available</Text>
            <Text style={styles.emptyStateSubtitle}>
              No DICOM images are currently available for this patient
            </Text>
          </View>
        </View>
      );
    }

    return (
      <View style={styles.tabContent}>
        <Text style={styles.sectionTitle}>
          AI Analysis & DICOM Images
        </Text>
        
        {/* Summary Statistics */}
        <View style={styles.analysisSummary}>
          <View style={styles.summaryItem}>
            <Icon name="layers" size={20} color={theme.colors.primary} />
            <Text style={styles.summaryLabel}>Total Series</Text>
            <Text style={styles.summaryValue}>{patientData.series_summary.length}</Text>
          </View>
          <View style={styles.summaryItem}>
            <Icon name="zap" size={20} color={theme.colors.success} />
            <Text style={styles.summaryLabel}>AI Predictions</Text>
            <Text style={styles.summaryValue}>{patientData.total_predictions}</Text>
          </View>
          <View style={styles.summaryItem}>
            <Icon name="check-circle" size={20} color={theme.colors.warning} />
            <Text style={styles.summaryLabel}>Processing Status</Text>
            <Text style={styles.summaryValue}>{patientData.patient_info.status}</Text>
          </View>
        </View>
        
        {patientData.series_summary.map((series, seriesIndex) => {
          // Get predictions for this series
          const seriesPredictions = patientData.predictions_by_series[series.series_num] || [];
          const hasPredictions = seriesPredictions.length > 0;
          
          return (
            <View style={styles.seriesContainer}>
              {/* Series Header */}
              <View style={styles.seriesHeader}>
                <View style={styles.seriesHeaderTop}>
                  <Text style={styles.seriesTitle}>
                    Series {series.series_num}: {series.series_description}
                  </Text>
                                     <TouchableOpacity
                     style={styles.seriesDetailButton}
                     onPress={() => handleNavigateToSeriesDetail(series)}
                     activeOpacity={0.7}
                   >
                    <Icon name="external-link" size={16} color={theme.colors.primary} />
                    <Text style={styles.seriesDetailButtonText}>Series Details</Text>
                  </TouchableOpacity>
                </View>
                <Text style={styles.seriesMeta}>
                  {series.total_images} images • {series.modality} modality
                  {hasPredictions && ` • ${seriesPredictions.length} AI predictions`}
                </Text>
              </View>
              
              {/* Series Details */}
              <View style={styles.seriesDetails}>
                <View style={styles.seriesDetailItem}>
                  <Text style={styles.seriesDetailLabel}>Series Number:</Text>
                  <Text style={styles.seriesDetailValue}>{series.series_num}</Text>
                </View>
                <View style={styles.seriesDetailItem}>
                  <Text style={styles.seriesDetailLabel}>Description:</Text>
                  <Text style={styles.seriesDetailValue} numberOfLines={2}>
                    {series.series_description}
                  </Text>
                </View>
                <View style={styles.seriesDetailItem}>
                  <Text style={styles.seriesDetailLabel}>Total Images:</Text>
                  <Text style={styles.seriesDetailValue}>{series.total_images}</Text>
                </View>
                <View style={styles.seriesDetailItem}>
                  <Text style={styles.seriesDetailLabel}>Modality:</Text>
                  <Text style={styles.seriesDetailValue}>{series.modality}</Text>
                </View>
                <View style={styles.seriesDetailItem}>
                  <Text style={styles.seriesDetailLabel}>AI Predictions:</Text>
                  <Text style={styles.seriesDetailValue}>
                    {hasPredictions ? `${seriesPredictions.length} found` : 'None'}
                  </Text>
                </View>
              </View>
              
              {/* Image and Predictions Row */}
              <View style={styles.imagePredictionsRow}>
                {/* DICOM Image */}
                <View style={styles.imageSection}>
                   <Text style={styles.imageSectionTitle}>
                     DICOM Preview
                   </Text>
                   {seriesPredictions[0]?.preview ? (
                    <TouchableOpacity
                      style={styles.imageThumbnail}
                      onPress={() => handleImagePress(seriesIndex)}
                    >
                      <Image
                        source={{ uri: API_CONFIG.DICOM_BASE_URL + seriesPredictions[0]?.preview }}
                        style={styles.thumbnailImage}
                        resizeMode="cover"
                      />
                      <View style={styles.imageOverlay}>
                        <Text style={styles.imageNumber}>Series {series.series_num}</Text>
                      </View>
                    </TouchableOpacity>
                  ) : (
                    
                    <View style={styles.noImagePlaceholder}>
                      <Icon name="image" size={48} color={theme.colors.textMuted} />
                      <Text style={styles.noImageText}>No Preview Available</Text>
                    </View>
                  )}
                </View>
                
                {/* AI Predictions */}
                <View style={styles.predictionsSection}>
                  <Text style={styles.predictionsSectionTitle}>
                    AI Analysis Results
                  </Text>
                  
                  {hasPredictions ? (
                    seriesPredictions.map((prediction) => (
                      <View style={styles.predictionCard}>
                        <View style={styles.predictionHeader}>
                          <Text style={styles.predictionLabel}>{prediction.prediction.label}</Text>
                          <View style={[
                            styles.urgencyBadge,
                            { backgroundColor: getUrgencyColor(prediction.prediction.clinical_urgency) }
                          ]}>
                            <Text style={styles.urgencyText}>
                              {prediction.prediction.clinical_urgency}
                            </Text>
                          </View>
                        </View>
                        
                        <View style={styles.predictionDetails}>
                          <View style={styles.predictionDetailItem}>
                            <Text style={styles.predictionDetailLabel}>Finding Type:</Text>
                            <Text style={styles.predictionDetailValue}>
                              {prediction.prediction.finding_type}
                            </Text>
                          </View>
                          <View style={styles.predictionDetailItem}>
                            <Text style={styles.predictionDetailLabel}>Confidence:</Text>
                            <Text style={styles.predictionDetailValue}>
                              {(prediction.prediction.confidence_score * 100).toFixed(1)}%
                            </Text>
                          </View>
                          <View style={styles.predictionDetailItem}>
                            <Text style={styles.predictionDetailLabel}>Category:</Text>
                            <Text style={styles.predictionDetailValue}>
                              {prediction.prediction.finding_category}
                            </Text>
                          </View>
                          <View style={styles.predictionDetailItem}>
                            <Text style={styles.predictionDetailLabel}>Severity:</Text>
                            <Text style={styles.predictionDetailValue}>
                              {prediction.prediction.primary_severity}
                            </Text>
                          </View>
                          <View style={styles.predictionDetailItem}>
                            <Text style={styles.predictionDetailLabel}>Location:</Text>
                            <Text style={styles.predictionDetailValue}>
                              {prediction.prediction.anatomical_location}
                            </Text>
                          </View>
                        </View>
                        
                        <Text style={styles.predictionTimestamp}>
                          Processed: {new Date(prediction.processed_at).toLocaleDateString()}
                        </Text>
                      </View>
                    ))
                  ) : (
                    <View style={styles.noPredictionsPlaceholder}>
                      <Icon name="brain" size={32} color={theme.colors.textMuted} />
                      <Text style={styles.noPredictionsText}>No AI predictions for this series</Text>
                    </View>
                  )}
                </View>
              </View>
            </View>
          );
        })}
      </View>
    );
  };

  /**
   * Render History Tab
   * 
   * Purpose: Render patient medical history
   */
  const renderHistoryTab = () => {
    if (!patientData) return null;
    
    return (
      <View style={styles.tabContent}>
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>Processing History</Text>
          <View style={styles.historyItem}>
            <Icon name="calendar" size={16} color={theme.colors.textSecondary} />
            <Text style={styles.historyText}>
              First processed on {new Date(patientData.first_processed_at).toLocaleDateString()}
            </Text>
          </View>
          <View style={styles.historyItem}>
            <Icon name="clock" size={16} color={theme.colors.textSecondary} />
            <Text style={styles.historyText}>
              Last updated on {new Date(patientData.last_processed_at).toLocaleDateString()}
            </Text>
          </View>
          <View style={styles.historyItem}>
            <Icon name="activity" size={16} color={theme.colors.textSecondary} />
            <Text style={styles.historyText}>
              Status: {patientData.patient_info.status} case
            </Text>
          </View>
          <View style={styles.historyItem}>
            <Icon name="brain" size={16} color={theme.colors.textSecondary} />
            <Text style={styles.historyText}>
              Total AI predictions: {patientData.total_predictions}
            </Text>
          </View>
        </View>

        <View style={styles.section}>
          <Text style={styles.sectionTitle}>Notes</Text>
          <Text style={styles.notesText}>
            Patient case processed with {patientData.series_summary.length} DICOM series.
            AI analysis completed with {patientData.total_predictions} predictions.
          </Text>
        </View>
      </View>
    );
  };

  // ============================================================================
  // MAIN RENDER
  // ============================================================================

  if (isLoading) {
    return (
      <SafeAreaView style={styles.container}>
        {renderLoadingState()}
      </SafeAreaView>
    );
  }

  if (error) {
    return (
      <SafeAreaView style={styles.container}>
        {renderErrorState()}
      </SafeAreaView>
    );
  }

  if (!patientData) {
    return (
      <SafeAreaView style={styles.container}>
        <View style={styles.errorContainer}>
          <Icon name="user-x" size={48} color={theme.colors.textMuted} />
          <Text style={styles.errorTitle}>Patient Not Found</Text>
          <Text style={styles.errorMessage}>The requested patient data could not be found.</Text>
        </View>
      </SafeAreaView>
    );
  }

  return (
    <SafeAreaView style={styles.container}>
      
      {/* Header */}
      <View style={styles.header}>
        <TouchableOpacity
          style={styles.backButton}
          onPress={handleBackPress}
        >
          <Icon name="arrow-left" size={24} color={theme.colors.textPrimary} />
        </TouchableOpacity>
        <View style={styles.headerTitle}>
          <Text style={styles.headerTitleText}>Patient Details</Text>
          <Text style={styles.headerSubtitleText}>Emergency Department</Text>
        </View>
        <TouchableOpacity
          style={styles.refreshButton}
          onPress={handleRefresh}
          disabled={isRefreshing}
        >
          <Icon 
            name="refresh-cw" 
            size={20} 
            color={isRefreshing ? theme.colors.textMuted : theme.colors.primary} 
          />
        </TouchableOpacity>
      </View>

      {/* Patient Header */}
      {renderPatientHeader()}

      {/* Tab Navigation */}
      {renderTabNavigation()}

      {/* Tab Content */}
      <ScrollView
        style={styles.content}
        showsVerticalScrollIndicator={false}
        refreshControl={
          <RefreshControl
            refreshing={isRefreshing}
            onRefresh={handleRefresh}
            colors={[theme.colors.primary]}
            tintColor={theme.colors.primary}
          />
        }
      >
        {/* Overview Tab: Patient demographics and medical information */}
        {activeTab === 'overview' && renderOverviewTab()}
        
        {/* AI Analysis Tab: Merged view of DICOM images and AI predictions */}
        {activeTab === 'aiAnalysis' && renderAIAnalysisTab()}
        
        {/* History Tab: Processing history and notes */}
        {activeTab === 'history' && renderHistoryTab()}
      </ScrollView>

      {/* DICOM Viewer Modal */}
      {selectedDicomData && (
        <DicomViewerModal
          visible={dicomModalVisible}
          dicomUrl={selectedDicomData.dicomUrl}
          onClose={handleCloseDicomModal}
          title={`${selectedDicomData.seriesData.series_description}`}
          patientName={patientData?.patient_info.name}
          studyDescription={`Series ${selectedDicomData.seriesData.series_num} - ${selectedDicomData.seriesData.modality}`}
        />
      )}

    </SafeAreaView>
  );
};

// ============================================================================
// STYLES
// ============================================================================

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: theme.colors.background,
  },
  
  // Header Styles
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: theme.spacing.md,
    paddingVertical: theme.spacing.sm,
    backgroundColor: theme.colors.background,
    borderBottomWidth: 1,
    borderBottomColor: theme.colors.border,
  },
  backButton: {
    padding: theme.spacing.sm,
    marginRight: theme.spacing.sm,
  },
  headerTitle: {
    flex: 1,
    alignItems: 'center',
  },
  headerTitleText: {
    fontSize: 18,
    color: theme.colors.textPrimary,
    fontFamily: theme.typography.fontFamily.bold,
  },
  headerSubtitleText: {
    fontSize: 12,
    color: theme.colors.textSecondary,
    fontFamily: theme.typography.fontFamily.regular,
  },
  refreshButton: {
    padding: theme.spacing.sm,
    marginLeft: theme.spacing.sm,
  },
  
  // Patient Header Styles
  patientHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: theme.spacing.md,
    paddingVertical: theme.spacing.lg,
    backgroundColor: theme.colors.background,
    borderBottomWidth: 1,
    borderBottomColor: theme.colors.border,
  },
  patientInfo: {
    flexDirection: 'row',
    alignItems: 'center',
    flex: 1,
  },
  patientAvatar: {
    width: 60,
    height: 60,
    borderRadius: 30,
    backgroundColor: theme.colors.backgroundAlt,
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: theme.spacing.md,
  },
  patientDetails: {
    flex: 1,
  },
  patientName: {
    fontSize: 20,
    color: theme.colors.textPrimary,
    fontFamily: theme.typography.fontFamily.bold,
    marginBottom: 4,
  },
  patientId: {
    fontSize: 14,
    color: theme.colors.textSecondary,
    fontFamily: theme.typography.fontFamily.medium,
    marginBottom: 8,
  },
  patientMeta: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  patientMetaText: {
    fontSize: 14,
    color: theme.colors.textSecondary,
    fontFamily: theme.typography.fontFamily.regular,
  },
  statusBadge: {
    paddingHorizontal: 12,
    paddingVertical: 6,
    borderRadius: 16,
  },
  statusText: {
    fontSize: 12,
    fontFamily: theme.typography.fontFamily.bold,
    color: theme.colors.background,
    textTransform: 'uppercase',
  },
  emergencyButton: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: theme.colors.error,
    paddingHorizontal: 16,
    paddingVertical: 12,
    borderRadius: 8,
    shadowColor: theme.colors.error,
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.3,
    shadowRadius: 4,
    elevation: 4,
  },
  emergencyButtonText: {
    color: theme.colors.background,
    fontSize: 12,
    fontFamily: theme.typography.fontFamily.bold,
    marginLeft: 8,
    textTransform: 'uppercase',
  },
  
  // Tab Navigation Styles
  tabContainer: {
    flexDirection: 'row',
    backgroundColor: theme.colors.background,
    borderBottomWidth: 1,
    borderBottomColor: theme.colors.border,
  },
  tabButton: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: theme.spacing.md,
    paddingHorizontal: theme.spacing.sm,
    position: 'relative',
  },
  activeTabButton: {
    borderBottomWidth: 2,
    borderBottomColor: theme.colors.primary,
  },
  tabLabel: {
    fontSize: 14,
    color: theme.colors.textSecondary,
    fontFamily: theme.typography.fontFamily.medium,
    marginLeft: 8,
  },
  activeTabLabel: {
    color: theme.colors.primary,
    fontFamily: theme.typography.fontFamily.bold,
  },
  tabCount: {
    backgroundColor: theme.colors.primary,
    borderRadius: 10,
    paddingHorizontal: 6,
    paddingVertical: 2,
    marginLeft: 8,
  },
  tabCountText: {
    color: theme.colors.background,
    fontSize: 10,
    fontFamily: theme.typography.fontFamily.bold,
  },
  
  // Content Styles
  content: {
    flex: 1,
  },
  tabContent: {
    padding: theme.spacing.md,
  },
  
  // Section Styles
  section: {
    marginBottom: theme.spacing.lg,
  },
  sectionTitle: {
    fontSize: 18,
    color: theme.colors.textPrimary,
    fontFamily: theme.typography.fontFamily.bold,
    marginBottom: theme.spacing.md,
  },
  
  // Info Grid Styles
  infoGrid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'space-between',
  },
  infoItem: {
    width: '48%',
    marginBottom: theme.spacing.md,
  },
  infoLabel: {
    fontSize: 12,
    color: theme.colors.textSecondary,
    fontFamily: theme.typography.fontFamily.medium,
    marginBottom: 4,
    textTransform: 'uppercase',
  },
  infoValue: {
    fontSize: 14,
    color: theme.colors.textPrimary,
    fontFamily: theme.typography.fontFamily.regular,
  },
  
  // Series Info Styles
  seriesInfo: {
    backgroundColor: theme.colors.backgroundAlt,
    padding: theme.spacing.md,
    borderRadius: 8,
  },
  seriesText: {
    fontSize: 14,
    color: theme.colors.textSecondary,
    fontFamily: theme.typography.fontFamily.regular,
    marginBottom: 4,
  },
  
  // Images Styles
  imagesContainer: {
    marginTop: theme.spacing.sm,
  },
  seriesContainer: {
    marginBottom: theme.spacing.lg,
  },
  seriesHeader: {
    marginBottom: theme.spacing.md,
  },
  seriesHeaderTop: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 4,
  },
  seriesTitle: {
    fontSize: 16,
    color: theme.colors.textPrimary,
    fontFamily: theme.typography.fontFamily.bold,
  },
  seriesDetailButton: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: theme.colors.backgroundAlt,
    paddingHorizontal: 10,
    paddingVertical: 6,
    borderRadius: 16,
    borderWidth: 1,
    borderColor: theme.colors.border,
  },
  seriesDetailButtonText: {
    fontSize: 12,
    color: theme.colors.primary,
    fontFamily: theme.typography.fontFamily.medium,
    marginLeft: 4,
  },
  seriesMeta: {
    fontSize: 14,
    color: theme.colors.textSecondary,
    fontFamily: theme.typography.fontFamily.regular,
  },
  imageList: {
    paddingRight: theme.spacing.md,
  },
  imageThumbnail: {
    width: 120,
    height: 120,
    borderRadius: 8,
    marginRight: theme.spacing.sm,
    position: 'relative',
    shadowColor: '#000000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 2,
  },
  thumbnailImage: {
    width: '100%',
    height: '100%',
    borderRadius: 8,
  },
  imageOverlay: {
    position: 'absolute',
    bottom: 0,
    left: 0,
    right: 0,
    backgroundColor: 'rgba(0, 0, 0, 0.7)',
    paddingVertical: 4,
    paddingHorizontal: 8,
    borderBottomLeftRadius: 8,
    borderBottomRightRadius: 8,
  },
  imageNumber: {
    color: theme.colors.background,
    fontSize: 10,
    fontFamily: theme.typography.fontFamily.bold,
    textAlign: 'center',
  },
  
  // History Styles
  historyItem: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: theme.spacing.sm,
  },
  historyText: {
    fontSize: 14,
    color: theme.colors.textSecondary,
    fontFamily: theme.typography.fontFamily.regular,
    marginLeft: theme.spacing.sm,
  },
  notesText: {
    fontSize: 14,
    color: theme.colors.textSecondary,
    fontFamily: theme.typography.fontFamily.regular,
    lineHeight: 20,
  },
  
  // Empty State Styles
  emptyState: {
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: theme.spacing.xl,
  },
  emptyStateTitle: {
    fontSize: 18,
    color: theme.colors.textPrimary,
    fontFamily: theme.typography.fontFamily.bold,
    marginTop: theme.spacing.md,
    marginBottom: theme.spacing.sm,
  },
  emptyStateSubtitle: {
    fontSize: 14,
    color: theme.colors.textSecondary,
    fontFamily: theme.typography.fontFamily.regular,
    textAlign: 'center',
    lineHeight: 20,
  },
  
  // No Image Placeholder Styles
  noImagePlaceholder: {
    width: 120,
    height: 120,
    borderRadius: 8,
    marginRight: theme.spacing.sm,
    backgroundColor: theme.colors.backgroundAlt,
    justifyContent: 'center',
    alignItems: 'center',
    borderWidth: 1,
    borderColor: theme.colors.border,
    borderStyle: 'dashed',
  },
  noImageText: {
    fontSize: 10,
    color: theme.colors.textMuted,
    fontFamily: theme.typography.fontFamily.regular,
    textAlign: 'center',
    marginTop: 4,
  },
  
  // Series Details Styles
  seriesDetails: {
    backgroundColor: theme.colors.backgroundAlt,
    padding: theme.spacing.sm,
    borderRadius: 8,
    marginBottom: theme.spacing.md,
  },
  seriesDetailItem: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'flex-start',
    marginBottom: theme.spacing.xs,
  },
  seriesDetailLabel: {
    fontSize: 12,
    color: theme.colors.textSecondary,
    fontFamily: theme.typography.fontFamily.medium,
    flex: 1,
  },
  seriesDetailValue: {
    fontSize: 12,
    color: theme.colors.textPrimary,
    fontFamily: theme.typography.fontFamily.regular,
    flex: 2,
    textAlign: 'right',
  },

  // Prediction Styles
  predictionSeries: {
    marginBottom: theme.spacing.lg,
  },
  predictionSeriesTitle: {
    fontSize: 16,
    color: theme.colors.textPrimary,
    fontFamily: theme.typography.fontFamily.bold,
    marginBottom: theme.spacing.sm,
  },
  predictionCard: {
    backgroundColor: theme.colors.backgroundAlt,
    borderRadius: 8,
    padding: theme.spacing.md,
    marginBottom: theme.spacing.sm,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 2,
  },
  predictionHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: theme.spacing.sm,
  },
  predictionLabel: {
    fontSize: 14,
    color: theme.colors.textPrimary,
    fontFamily: theme.typography.fontFamily.bold,
  },
  urgencyBadge: {
    paddingHorizontal: 10,
    paddingVertical: 4,
    borderRadius: 12,
  },
  urgencyText: {
    fontSize: 10,
    fontFamily: theme.typography.fontFamily.bold,
    color: theme.colors.background,
    textTransform: 'uppercase',
  },
  predictionDetails: {
    marginBottom: theme.spacing.sm,
  },
  predictionDetailItem: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'flex-start',
    marginBottom: theme.spacing.xs,
  },
  predictionDetailLabel: {
    fontSize: 12,
    color: theme.colors.textSecondary,
    fontFamily: theme.typography.fontFamily.medium,
    flex: 1,
  },
  predictionDetailValue: {
    fontSize: 12,
    color: theme.colors.textPrimary,
    fontFamily: theme.typography.fontFamily.regular,
    flex: 2,
    textAlign: 'right',
  },
  predictionTimestamp: {
    fontSize: 12,
    color: theme.colors.textSecondary,
    fontFamily: theme.typography.fontFamily.regular,
    textAlign: 'right',
  },

  // Loading and Error States
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: theme.spacing.lg,
  },
  loadingText: {
    marginTop: theme.spacing.sm,
    fontSize: 16,
    color: theme.colors.textSecondary,
    fontFamily: theme.typography.fontFamily.regular,
  },
  errorContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: theme.spacing.lg,
  },
  errorTitle: {
    fontSize: 18,
    color: theme.colors.textPrimary,
    fontFamily: theme.typography.fontFamily.bold,
    marginTop: theme.spacing.md,
    marginBottom: theme.spacing.sm,
  },
  errorMessage: {
    fontSize: 14,
    color: theme.colors.textSecondary,
    fontFamily: theme.typography.fontFamily.regular,
    textAlign: 'center',
    marginBottom: theme.spacing.md,
  },
  retryButton: {
    backgroundColor: theme.colors.primary,
    paddingVertical: theme.spacing.md,
    paddingHorizontal: theme.spacing.lg,
    borderRadius: 8,
    shadowColor: theme.colors.primary,
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.3,
    shadowRadius: 4,
    elevation: 4,
  },
  retryButtonText: {
    color: theme.colors.background,
    fontSize: 16,
    fontFamily: theme.typography.fontFamily.bold,
  },

  // New styles for AI Analysis Tab
  imagePredictionsRow: {
    flexDirection: screenWidth > 600 ? 'row' : 'column',
    justifyContent: 'space-between',
    marginTop: theme.spacing.md,
  },
  imageSection: {
    flex: 1,
    marginRight: screenWidth > 600 ? theme.spacing.md : 0,
    marginBottom: screenWidth > 600 ? 0 : theme.spacing.md,
  },
  imageSectionTitle: {
    fontSize: 14,
    color: theme.colors.textPrimary,
    fontFamily: theme.typography.fontFamily.bold,
    marginBottom: theme.spacing.sm,
  },
  predictionsSection: {
    flex: 1,
  },
  predictionsSectionTitle: {
    fontSize: 14,
    color: theme.colors.textPrimary,
    fontFamily: theme.typography.fontFamily.bold,
    marginBottom: theme.spacing.sm,
  },
  noPredictionsPlaceholder: {
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: theme.spacing.md,
  },
  noPredictionsText: {
    fontSize: 14,
    color: theme.colors.textSecondary,
    fontFamily: theme.typography.fontFamily.regular,
    marginTop: theme.spacing.sm,
    textAlign: 'center',
  },

  // New styles for AI Analysis Tab
  analysisSummary: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    backgroundColor: theme.colors.backgroundAlt,
    borderRadius: 8,
    paddingVertical: theme.spacing.md,
    paddingHorizontal: theme.spacing.sm,
    marginBottom: theme.spacing.md,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 2,
  },
  summaryItem: {
    alignItems: 'center',
  },
  summaryLabel: {
    fontSize: 12,
    color: theme.colors.textSecondary,
    fontFamily: theme.typography.fontFamily.medium,
    marginTop: theme.spacing.xs,
  },
  summaryValue: {
    fontSize: 18,
    color: theme.colors.textPrimary,
    fontFamily: theme.typography.fontFamily.bold,
    marginTop: theme.spacing.xs,
  },


});

export default PatientDetailsScreen;
