/*
 * 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,
  StatusBar,
  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 types and API
import { patientAPI } from '../services/patientAPI';
import { selectUser } from '../../Auth/redux/authSelectors';
import { API_CONFIG } from '../../../shared/utils';

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

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

interface PatientDetailsScreenProps {
  navigation: any;
  route: {
    params: {
      patientId: string;
      patientName?: string;
    };
  };
}

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');
  
  // Feedback state
  const [showFeedbackModal, setShowFeedbackModal] = useState(false);
  const [selectedSeriesForFeedback, setSelectedSeriesForFeedback] = useState<SeriesSummary | null>(null);
  const [selectedPrediction, setSelectedPrediction] = useState<Prediction | null>(null);
  const [feedbackText, setFeedbackText] = useState('');
  const [isPositive, setIsPositive] = useState<boolean | null>(null);
  const [isSubmittingFeedback, setIsSubmittingFeedback] = useState(false);
  
  // Feedback result modal state
  const [showFeedbackResultModal, setShowFeedbackResultModal] = useState(false);
  const [feedbackResult, setFeedbackResult] = useState<{
    type: 'success' | 'error';
    title: string;
    message: string;
  } | 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);
      
      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]);

  // ============================================================================
  // 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 Image Press
   * 
   * Purpose: Open full-screen image viewer for selected series
   * 
   * @param seriesIndex - Index of the series
   */
  const handleImagePress = useCallback((seriesIndex: number) => {
    setSelectedImageIndex(seriesIndex);
    setShowFullImage(true);
  }, []);

  /**
   * Handle Close Image Viewer
   * 
   * Purpose: Close full-screen image viewer
   */
  const handleCloseImageViewer = useCallback(() => {
    setShowFullImage(false);
  }, []);

  /**
   * 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]);

  // ============================================================================
  // FEEDBACK HANDLERS
  // ============================================================================

  /**
   * Handle Open Feedback Modal
   * 
   * Purpose: Open feedback modal for a specific series and prediction
   * 
   * @param series - Series data for feedback
   * @param prediction - Prediction data for feedback
   */
  const handleOpenFeedback = useCallback((series: SeriesSummary, prediction: Prediction) => {
    setSelectedSeriesForFeedback(series);
    setSelectedPrediction(prediction);
    setFeedbackText('');
    setIsPositive(null);
    setShowFeedbackModal(true);
  }, []);

  /**
   * Handle Submit Feedback
   * 
   * Purpose: Submit feedback to API
   */
  const handleSubmitFeedback = useCallback(async () => {
    if ( !selectedPrediction || !feedbackText.trim() || isPositive === null) {
      setFeedbackResult({
        type: 'error',
        title: 'Validation Error',
        message: 'Please provide all required feedback information'
      });
      setShowFeedbackResultModal(true);
      return;
    }

    try {
      setIsSubmittingFeedback(true);
      
      if (!patientData?.patid) {
        throw new Error('Patient ID not available');
      }

      const feedbackPayload = {
        patid: patientData.patid,
        prediction_id: selectedPrediction.id,
        feedback_text: feedbackText.trim(),
        is_positive: isPositive
      };

      console.log('Submitting feedback payload:', feedbackPayload);
      
      // Call the actual API
      const response = await patientAPI.submitFeedback(feedbackPayload, user?.access_token);
      console.log('update response', response);
      
      if (!response.ok) {
        throw new Error(response.problem || 'Failed to submit feedback');
      }
      
      // Show success message
      setFeedbackResult({
        type: 'success',
        title: 'Feedback Submitted',
        message: 'Your feedback has been recorded successfully.'
      });
      setShowFeedbackResultModal(true);
    } catch (error: any) {
      setFeedbackResult({
        type: 'error',
        title: 'Error',
        message: error.message || 'Failed to submit feedback. Please try again.'
      });
      setShowFeedbackResultModal(true);
    } finally {
      setIsSubmittingFeedback(false);
    }
  }, [selectedSeriesForFeedback, selectedPrediction, feedbackText, isPositive, patientData?.patid]);

  /**
   * Handle Close Feedback Modal
   * 
   * Purpose: Close feedback modal and reset state
   */
  const handleCloseFeedback = useCallback(() => {
    setShowFeedbackModal(false);
    setSelectedSeriesForFeedback(null);
    setSelectedPrediction(null);
    setFeedbackText('');
    setIsPositive(null);
  }, []);

  /**
   * Handle Feedback Result Modal Close
   * 
   * Purpose: Close feedback result modal and reset form if success
   */
  const handleFeedbackResultClose = useCallback(() => {
    setShowFeedbackResultModal(false);
    setFeedbackResult(null);
    
    // If it was a success, also close the feedback modal and reset form
    if (feedbackResult?.type === 'success') {
      setShowFeedbackModal(false);
      setSelectedSeriesForFeedback(null);
      setSelectedPrediction(null);
      setFeedbackText('');
      setIsPositive(null);
    }
  }, [feedbackResult?.type]);

  // ============================================================================
  // 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 key={seriesIndex} 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.feedbackButton}
                     onPress={() => handleOpenFeedback(series, seriesPredictions[0])}
                     activeOpacity={0.7}
                   >
                    <Icon name="message-circle" size={16} color={theme.colors.primary} />
                    <Text style={styles.feedbackButtonText}>Feedback</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 key={prediction.id} 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}>
        <StatusBar barStyle="dark-content" backgroundColor={theme.colors.background} />
        {renderLoadingState()}
      </SafeAreaView>
    );
  }

  if (error) {
    return (
      <SafeAreaView style={styles.container}>
        <StatusBar barStyle="dark-content" backgroundColor={theme.colors.background} />
        {renderErrorState()}
      </SafeAreaView>
    );
  }

  if (!patientData) {
    return (
      <SafeAreaView style={styles.container}>
        <StatusBar barStyle="dark-content" backgroundColor={theme.colors.background} />
        <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}>
      <StatusBar barStyle="dark-content" backgroundColor={theme.colors.background} />
      
      {/* 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>

      {/* Feedback Modal: Allows physicians to provide clinical feedback on AI predictions and DICOM images */}
      {showFeedbackModal && selectedSeriesForFeedback && (
        <View style={styles.modalOverlay}>
          <View style={styles.feedbackModal}>
            <View style={styles.modalHeader}>
              <Text style={styles.modalTitle}>Provide Feedback</Text>
              <TouchableOpacity
                style={styles.closeButton}
                onPress={handleCloseFeedback}
              >
                <Icon name="x" size={24} color={theme.colors.textSecondary} />
              </TouchableOpacity>
            </View>

            <View style={styles.modalContent}>

              {/* <View style={styles.feedbackSeriesInfo}>
                <Text style={styles.feedbackSeriesTitle}>
                  Series {selectedSeriesForFeedback.series_num}: {selectedSeriesForFeedback.series_description}
                </Text>
                <Text style={styles.feedbackSeriesMeta}>
                  {selectedSeriesForFeedback.modality} • {selectedSeriesForFeedback.total_images} images
                </Text>
              </View> */}

              {/* Series and Prediction Info */}
              {selectedPrediction && (
                <View style={styles.feedbackPredictionInfo}>
                  <Text style={styles.feedbackPredictionTitle}>
                    AI Prediction: {selectedPrediction.prediction.label}
                  </Text>
                  <Text style={styles.feedbackPredictionMeta}>
                    Confidence: {(selectedPrediction.prediction.confidence_score * 100).toFixed(1)}% • 
                    Type: {selectedPrediction.prediction.finding_type}
                  </Text>
                </View>
              )}

              {/* Prediction Accuracy Selection */}
              <View style={styles.feedbackSection}>
                <Text style={styles.feedbackSectionTitle}>Is this prediction accurate?</Text>
                <View style={styles.predictionAccuracyContainer}>
                  {[
                    { key: 'true', label: 'Yes (Positive)', color: theme.colors.success, icon: 'check-circle', value: true },
                    { key: 'false', label: 'No (Negative)', color: theme.colors.error, icon: 'x-circle', value: false }
                  ].map((option) => (
                                          <TouchableOpacity
                        key={option.key}
                        onPress={() => setIsPositive(option.value)}
                        style={[
                          styles.predictionAccuracyButton,
                          isPositive === option.value && styles.predictionAccuracyButtonActive,
                          { borderColor: option.color }
                        ]}
                      >
                        <Icon 
                          name={option.icon as any} 
                          size={16} 
                          color={isPositive === option.value ? theme.colors.background : option.color} 
                        />
                        <Text style={[
                          styles.predictionAccuracyButtonText,
                          isPositive === option.value && styles.predictionAccuracyButtonTextActive
                        ]}>
                          {option.label}
                        </Text>
                      </TouchableOpacity>
                  ))}
                </View>
              </View>

              {/* Feedback Text Input */}
              <View style={styles.feedbackSection}>
                <Text style={styles.feedbackSectionTitle}>Your Feedback</Text>
                <TextInput
                  style={styles.feedbackTextInput}
                  placeholder="Provide your clinical insights, suggestions, or corrections..."
                  placeholderTextColor={theme.colors.textMuted}
                  value={feedbackText}
                  onChangeText={setFeedbackText}
                  multiline
                  numberOfLines={4}
                  textAlignVertical="top"
                />
              </View>
            </View>

            <View style={styles.modalFooter}>
              <TouchableOpacity
                style={styles.cancelButton}
                onPress={handleCloseFeedback}
              >
                <Text style={styles.cancelButtonText}>Cancel</Text>
              </TouchableOpacity>
              <TouchableOpacity
                style={[
                  styles.submitButton,
                  (!feedbackText.trim() || isPositive === null || isSubmittingFeedback) && styles.submitButtonDisabled
                ]}
                onPress={handleSubmitFeedback}
                disabled={!feedbackText.trim() || isPositive === null || isSubmittingFeedback}
              >
                <Text style={styles.submitButtonText}>Submit Feedback</Text>
              </TouchableOpacity>
            </View>
          </View>
        </View>
      )}

      {/* Feedback Result Modal: Shows success/error messages for feedback submission */}
      {showFeedbackResultModal && feedbackResult && (
        <View style={styles.modalOverlay}>
          <View style={styles.feedbackResultModal}>
            <View style={styles.modalHeader}>
              <Icon 
                name={feedbackResult.type === 'success' ? 'check-circle' : 'alert-circle'} 
                size={24} 
                color={feedbackResult.type === 'success' ? theme.colors.success : theme.colors.error} 
              />
              <Text style={[
                styles.modalTitle,
                { color: feedbackResult.type === 'success' ? theme.colors.success : theme.colors.error }
              ]}>
                {feedbackResult.title}
              </Text>
            </View>

            <View style={styles.modalContent}>
              <Text style={styles.feedbackResultMessage}>
                {feedbackResult.message}
              </Text>
            </View>

            <View style={styles.modalFooter}>
              <TouchableOpacity
                style={styles.okButton}
                onPress={handleFeedbackResultClose}
              >
                <Text style={styles.okButtonText}>OK</Text>
              </TouchableOpacity>
            </View>
          </View>
        </View>
      )}
    </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,
    fontWeight: 'bold',
    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,
    fontWeight: 'bold',
    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,
    fontWeight: '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,
    fontWeight: '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,
    fontWeight: 'bold',
  },
  
  // Content Styles
  content: {
    flex: 1,
  },
  tabContent: {
    padding: theme.spacing.md,
  },
  
  // Section Styles
  section: {
    marginBottom: theme.spacing.lg,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    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,
    fontWeight: 'bold',
    color: theme.colors.textPrimary,
    fontFamily: theme.typography.fontFamily.bold,
  },
  feedbackButton: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: theme.colors.backgroundAlt,
    paddingHorizontal: 10,
    paddingVertical: 6,
    borderRadius: 16,
    borderWidth: 1,
    borderColor: theme.colors.border,
  },
  feedbackButtonText: {
    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,
    fontWeight: '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,
    fontWeight: 'bold',
    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,
    fontWeight: 'bold',
    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,
    fontWeight: 'bold',
    color: theme.colors.textPrimary,
    fontFamily: theme.typography.fontFamily.bold,
  },
  urgencyBadge: {
    paddingHorizontal: 10,
    paddingVertical: 4,
    borderRadius: 12,
  },
  urgencyText: {
    fontSize: 10,
    fontWeight: '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,
    fontWeight: 'bold',
    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,
    fontWeight: 'bold',
    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,
    fontWeight: 'bold',
    color: theme.colors.textPrimary,
    fontFamily: theme.typography.fontFamily.bold,
    marginBottom: theme.spacing.sm,
  },
  predictionsSection: {
    flex: 1,
  },
  predictionsSectionTitle: {
    fontSize: 14,
    fontWeight: 'bold',
    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,
    fontWeight: 'bold',
    color: theme.colors.textPrimary,
    fontFamily: theme.typography.fontFamily.bold,
    marginTop: theme.spacing.xs,
  },

  // Feedback Modal Styles
  modalOverlay: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    backgroundColor: 'rgba(0, 0, 0, 0.7)',
    justifyContent: 'center',
    alignItems: 'center',
    zIndex: 1000,
  },
  feedbackModal: {
    backgroundColor: theme.colors.background,
    borderRadius: 12,
    width: '90%',
    maxWidth: 450,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 4 },
    shadowOpacity: 0.3,
    shadowRadius: 10,
    elevation: 10,
  },
  modalHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: theme.spacing.md,
    borderBottomWidth: 1,
    borderBottomColor: theme.colors.border,
  },
  modalTitle: {
    fontSize: 20,
    fontWeight: 'bold',
    color: theme.colors.textPrimary,
    fontFamily: theme.typography.fontFamily.bold,
  },
  closeButton: {
    padding: theme.spacing.sm,
  },
  modalContent: {
    padding: theme.spacing.md,
  },
  feedbackSeriesInfo: {
    marginBottom: theme.spacing.md,
  },
  feedbackSeriesTitle: {
    fontSize: 16,
    fontWeight: 'bold',
    color: theme.colors.textPrimary,
    fontFamily: theme.typography.fontFamily.bold,
    marginBottom: theme.spacing.xs,
  },
  feedbackSeriesMeta: {
    fontSize: 12,
    color: theme.colors.textSecondary,
    fontFamily: theme.typography.fontFamily.regular,
  },
  feedbackSection: {
    marginBottom: theme.spacing.md,
  },
  feedbackSectionTitle: {
    fontSize: 14,
    fontWeight: 'bold',
    color: theme.colors.textPrimary,
    fontFamily: theme.typography.fontFamily.bold,
    marginBottom: theme.spacing.sm,
  },
  feedbackTypeContainer: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    marginBottom: theme.spacing.sm,
  },
  feedbackTypeButton: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: theme.spacing.sm,
    paddingHorizontal: theme.spacing.md,
    borderRadius: 12,
    borderWidth: 1,
    borderColor: theme.colors.border,
  },
  feedbackTypeButtonActive: {
    borderColor: theme.colors.primary,
    backgroundColor: theme.colors.primary,
  },
  feedbackTypeButtonText: {
    fontSize: 14,
    color: theme.colors.textSecondary,
    fontFamily: theme.typography.fontFamily.medium,
    marginLeft: theme.spacing.sm,
  },
  feedbackTypeButtonTextActive: {
    color: theme.colors.background,
    fontFamily: theme.typography.fontFamily.bold,
  },
  priorityContainer: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    marginBottom: theme.spacing.sm,
  },
  priorityButton: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: theme.spacing.sm,
    paddingHorizontal: theme.spacing.md,
    borderRadius: 12,
    borderWidth: 1,
    borderColor: theme.colors.border,
  },
  priorityButtonActive: {
    borderColor: theme.colors.primary,
    backgroundColor: theme.colors.primary,
  },
  priorityIndicator: {
    width: 10,
    height: 10,
    borderRadius: 5,
    marginRight: theme.spacing.sm,
  },
  priorityButtonText: {
    fontSize: 14,
    color: theme.colors.textSecondary,
    fontFamily: theme.typography.fontFamily.medium,
  },
  priorityButtonTextActive: {
    color: theme.colors.background,
    fontFamily: theme.typography.fontFamily.bold,
  },
  feedbackTextInput: {
    borderWidth: 1,
    borderColor: theme.colors.border,
    borderRadius: 8,
    padding: theme.spacing.md,
    fontSize: 14,
    color: theme.colors.textPrimary,
    fontFamily: theme.typography.fontFamily.regular,
    minHeight: 100,
    textAlignVertical: 'top',
  },
     modalFooter: {
     flexDirection: 'row',
     justifyContent: 'space-around',
     padding: theme.spacing.md,
     borderTopWidth: 1,
     borderTopColor: theme.colors.border,
   },
   
   // Feedback Prediction Info Styles
   feedbackPredictionInfo: {
    //  marginTop: theme.spacing.sm,
     paddingTop: theme.spacing.md,
     marginBottom: theme.spacing.sm,
    //  borderTopWidth: 1,
    //  borderTopColor: theme.colors.border,
   },
   feedbackPredictionTitle: {
     fontSize: 14,
     fontWeight: 'bold',
     color: theme.colors.textPrimary,
     fontFamily: theme.typography.fontFamily.bold,
     marginBottom: theme.spacing.xs,
   },
   feedbackPredictionMeta: {
     fontSize: 12,
     color: theme.colors.textSecondary,
     fontFamily: theme.typography.fontFamily.regular,
   },
   
   // Prediction Accuracy Selection Styles
   predictionAccuracyContainer: {
     flexDirection: 'row',
     justifyContent: 'space-around',
     marginBottom: theme.spacing.sm,
   },
   predictionAccuracyButton: {
     flexDirection: 'row',
     alignItems: 'center',
     paddingVertical: theme.spacing.sm,
     paddingHorizontal: theme.spacing.md,
     borderRadius: 12,
     borderWidth: 1,
     borderColor: theme.colors.border,
     minWidth: 120,
     justifyContent: 'center',
   },
   predictionAccuracyButtonActive: {
     borderColor: theme.colors.primary,
     backgroundColor: theme.colors.primary,
   },
   predictionAccuracyButtonText: {
     fontSize: 14,
     color: theme.colors.textSecondary,
     fontFamily: theme.typography.fontFamily.medium,
     marginLeft: theme.spacing.sm,
   },
   predictionAccuracyButtonTextActive: {
     color: theme.colors.background,
     fontFamily: theme.typography.fontFamily.bold,
   },
  cancelButton: {
    paddingVertical: theme.spacing.md,
    paddingHorizontal: theme.spacing.lg,
    borderRadius: 8,
    borderWidth: 1,
    borderColor: theme.colors.border,
  },
  cancelButtonText: {
    fontSize: 16,
    color: theme.colors.textSecondary,
    fontFamily: theme.typography.fontFamily.medium,
  },
  submitButton: {
    paddingVertical: theme.spacing.md,
    paddingHorizontal: theme.spacing.lg,
    borderRadius: 8,
    backgroundColor: theme.colors.primary,
    shadowColor: theme.colors.primary,
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.3,
    shadowRadius: 4,
    elevation: 4,
  },
  submitButtonDisabled: {
    backgroundColor: theme.colors.textMuted,
    opacity: 0.7,
  },
  submitButtonText: {
    color: theme.colors.background,
    fontSize: 16,
    fontWeight: 'bold',
    fontFamily: theme.typography.fontFamily.bold,
  },

  // Feedback Result Modal Styles
  feedbackResultModal: {
    backgroundColor: theme.colors.background,
    borderRadius: 16,
    padding: 0,
    width: '90%',
    maxWidth: 400,
    shadowColor: '#000000',
    shadowOffset: { width: 0, height: 4 },
    shadowOpacity: 0.15,
    shadowRadius: 8,
    elevation: 8,
  },
  feedbackResultMessage: {
    fontSize: 16,
    color: theme.colors.textPrimary,
    fontFamily: theme.typography.fontFamily.regular,
    textAlign: 'center',
    lineHeight: 24,
    paddingHorizontal: theme.spacing.md,
  },
  okButton: {
    paddingVertical: theme.spacing.md,
    paddingHorizontal: theme.spacing.xl,
    borderRadius: 8,
    backgroundColor: theme.colors.primary,
    shadowColor: theme.colors.primary,
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.3,
    shadowRadius: 4,
    elevation: 4,
    minWidth: 100,
    alignItems: 'center',
  },
  okButtonText: {
    color: theme.colors.background,
    fontSize: 16,
    fontWeight: 'bold',
    fontFamily: theme.typography.fontFamily.bold,
  },
});

export default PatientDetailsScreen;
