import { HealthProgressRing } from '@/components/health/HealthProgressRing';
import { BasicInfoTab } from '@/components/health/tabs/BasicInfoTab';
import { CheckupRecordsTab } from '@/components/health/tabs/CheckupRecordsTab';
import { HealthHistoryTab } from '@/components/health/tabs/HealthHistoryTab';
import { MedicalRecordsTab } from '@/components/health/tabs/MedicalRecordsTab';
import { HeaderBar } from '@/components/ui/HeaderBar';
import { Colors } from '@/constants/Colors';
import { ROUTES } from '@/constants/Routes';
import { useAppSelector } from '@/hooks/redux';
import { useColorScheme } from '@/hooks/useColorScheme';
import { useI18n } from '@/hooks/useI18n';
import { selectHealthHistoryProgress } from '@/store/healthSlice';
import { DEFAULT_MEMBER_NAME } from '@/store/userSlice';
import { Ionicons } from '@expo/vector-icons';
import { Image } from 'expo-image';
import { LinearGradient } from 'expo-linear-gradient';
import { Stack, useRouter } from 'expo-router';
import React, { useMemo, useState } from 'react';
import { ScrollView, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';

export default function HealthProfileScreen() {
  const router = useRouter();
  const insets = useSafeAreaInsets();
  const theme = (useColorScheme() ?? 'light') as 'light' | 'dark';
  const colorTokens = Colors[theme];
  const { t } = useI18n();
  
  const [activeTab, setActiveTab] = useState(0);
  
  // Mock user data - in a real app this would come from Redux/Context
  const userProfile = useAppSelector((state) => state.user.profile);
  const displayName = userProfile.name?.trim() ? userProfile.name : DEFAULT_MEMBER_NAME;
  const avatarUrl = userProfile.avatar || 'https://plates-1251306435.cos.ap-guangzhou.myqcloud.com/images/seal-avatar/2.jpeg';
  
  // 从 Redux 获取健康史进度
  const healthHistoryProgress = useAppSelector(selectHealthHistoryProgress);
  
  // Mock health data
  const healthData = {
    bmi: userProfile.weight && userProfile.height ? (parseFloat(userProfile.weight) / Math.pow(parseFloat(userProfile.height) / 100, 2)).toFixed(1) : '--',
    height: userProfile.height ? `${parseFloat(userProfile.height).toFixed(1)}` : '--',
    weight: userProfile.weight ? `${parseFloat(userProfile.weight).toFixed(1)}` : '--',
    waist: userProfile.waistCircumference ? `${parseFloat(userProfile.waistCircumference.toString()).toFixed(1)}` : '--',
    status: '健康状况良好',
    statusDesc: '请继续保持良好的生活习惯',
    statusMessage: '您的健康状况不错哦~'
  };

  // Calculate Basic Info completion percentage
  const basicInfoProgress = useMemo(() => {
    let filledCount = 0;
    const totalFields = 3; // height, weight, waist
    
    if (userProfile.height && parseFloat(userProfile.height) > 0) filledCount++;
    if (userProfile.weight && parseFloat(userProfile.weight) > 0) filledCount++;
    if (userProfile.waistCircumference && parseFloat(userProfile.waistCircumference.toString()) > 0) filledCount++;
    
    return Math.round((filledCount / totalFields) * 100);
  }, [userProfile.height, userProfile.weight, userProfile.waistCircumference]);

  const gradientColors: [string, string] =
    theme === 'dark'
      ? ['#1f2230', '#10131e']
      : [colorTokens.backgroundGradientStart, colorTokens.backgroundGradientEnd];

  const tabs = [
    t('health.tabs.healthProfile.basicInfo'),
    t('health.tabs.healthProfile.healthHistory'),
    // t('health.tabs.healthProfile.medicalRecords'),
    t('health.tabs.healthProfile.checkupRecords'),
    t('health.tabs.healthProfile.medicineBox')
  ];
  const tabIcons = ["person", "time", "folder", "clipboard", "medkit"];

  const handleTabPress = (index: number) => {
    if (index === 4) {
      // Handle Medicine Box tab specially
      router.push('/medications/manage-medications');
      return;
    }
    setActiveTab(index);
  };

  const renderActiveTab = () => {
    switch (activeTab) {
      case 0:
        return <BasicInfoTab healthData={healthData} />;
      case 1:
        return <HealthHistoryTab />;
      case 2:
        return <MedicalRecordsTab />;
      case 3:
        return <CheckupRecordsTab />;
      default:
        return <BasicInfoTab healthData={healthData} />;
    }
  };

  return (
    <View style={[styles.container, { backgroundColor: colorTokens.pageBackgroundEmphasis }]}>
      <Stack.Screen options={{ headerShown: false }} />
      <LinearGradient colors={gradientColors} style={StyleSheet.absoluteFillObject} />
      
      <HeaderBar 
        title={t('health.tabs.healthProfile.title')} 
        transparent
        right={
          <View style={{ flexDirection: 'row', alignItems: 'center' }}>
            <TouchableOpacity style={{ marginRight: 12 }}>
              <Ionicons name="settings-outline" size={22} color="#1F2937" />
            </TouchableOpacity>
          </View>
        }
      />

      <ScrollView 
        contentContainerStyle={[styles.scrollContent, { paddingTop: insets.top + 60 }]}
        showsVerticalScrollIndicator={false}
      >
        {/* Top Section with Avatar and Status */}
        <View style={styles.topSection}>
          <View style={styles.avatarRow}>
             <View style={styles.miniAvatarContainer}>
               <Image source={{ uri: avatarUrl }} style={styles.miniAvatar} />
               <Text style={styles.miniAvatarName}>{displayName}</Text>
             </View>
             <TouchableOpacity style={styles.addButton}>
               <Ionicons name="add" size={16} color="#6B7280" />
             </TouchableOpacity>
          </View>

          {/* Action Buttons - Replaced with HealthProgressRing */}
          <View style={styles.actionButtonsRow}>
            <HealthProgressRing 
              title={t('health.tabs.healthProfile.basicInfo')} 
              progress={basicInfoProgress} 
              gradientColors={['#9B8AFB', '#5B4CFF']} 
            />
            <HealthProgressRing 
              title={t('health.tabs.healthProfile.healthHistory')} 
              progress={healthHistoryProgress} 
              gradientColors={['#E0E7FF', '#C7D2FE']} 
              label={healthHistoryProgress.toString()}
              suffix="%"
            />
            <HealthProgressRing 
              title={t('health.tabs.healthProfile.medicalRecords')} 
              progress={0} 
              gradientColors={['#E0E7FF', '#C7D2FE']} 
              label="0"
              suffix="份"
            />
          </View>
        </View>

        {/* Family Invite Banner */}
        <TouchableOpacity 
          style={styles.inviteBanner}
          activeOpacity={0.9}
          onPress={() => router.push(ROUTES.HEALTH_FAMILY_INVITE)}
        >
           <View style={styles.inviteContent}>
             <View style={styles.inviteIconContainer}>
               <Ionicons name="home" size={18} color="#5B4CFF" />
             </View>
             <Text style={styles.inviteText}>{t('health.tabs.healthProfile.subtitle')}</Text>
             <Ionicons name="chevron-forward" size={18} color="#6B7280" />
           </View>
        </TouchableOpacity>

        {/* Tab/Segment Control */}
        <View style={styles.segmentControl}>
           {tabs.map((tab, index) => (
             <TouchableOpacity 
               key={index} 
               style={styles.segmentItem}
               onPress={() => handleTabPress(index)}
               activeOpacity={0.7}
             >
               <View style={[styles.segmentIconPlaceholder, index === activeTab && styles.segmentIconActive]}>
                 <Ionicons 
                   name={tabIcons[index] as any} 
                   size={20} 
                   color={index === activeTab ? "#5B4CFF" : "#6B7280"} 
                 />
               </View>
               <Text style={[styles.segmentText, index === activeTab && styles.segmentTextActive]}>{tab}</Text>
             </TouchableOpacity>
           ))}
        </View>

        {/* Active Tab Content */}
        {renderActiveTab()}

        {/* Privacy Notice Footer */}
        <View style={styles.privacyNoticeContainer}>
          <View style={styles.privacyIconWrapper}>
            <Ionicons name="shield-checkmark" size={16} color="#9CA3AF" />
          </View>
          <Text style={styles.privacyNoticeText}>
            {t('health.tabs.healthProfile.privacyNotice')}
          </Text>
        </View>

      </ScrollView>
      
      {/* Privacy Warning Footer - Removed as requested */}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  scrollContent: {
    paddingHorizontal: 16,
    paddingBottom: 100,
  },
  topSection: {
    marginBottom: 20,
  },
  avatarRow: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 10,
  },
  miniAvatarContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#5B4CFF',
    paddingVertical: 4,
    paddingHorizontal: 4,
    paddingRight: 12,
    borderRadius: 20,
  },
  miniAvatar: {
    width: 24,
    height: 24,
    borderRadius: 12,
    marginRight: 6,
    borderWidth: 1,
    borderColor: '#FFF',
  },
  miniAvatarName: {
    color: '#FFF',
    fontSize: 12,
    fontWeight: 'bold',
  },
  addButton: {
    width: 28,
    height: 28,
    borderRadius: 14,
    backgroundColor: '#FFFFFF',
    alignItems: 'center',
    justifyContent: 'center',
    marginLeft: 8,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 1 },
    shadowOpacity: 0.1,
    shadowRadius: 2,
    elevation: 2,
  },
  actionButtonsRow: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    marginTop: 24,
    marginBottom: 12,
  },
  inviteBanner: {
    backgroundColor: '#FFFFFF',
    borderRadius: 20,
    padding: 16,
    marginBottom: 20,
    shadowColor: '#5B4CFF',
    shadowOffset: { width: 0, height: 4 },
    shadowOpacity: 0.05,
    shadowRadius: 8,
    elevation: 2,
  },
  inviteContent: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  inviteIconContainer: {
    marginRight: 8,
  },
  inviteText: {
    flex: 1,
    fontSize: 13,
    color: '#1F2138',
    fontWeight: '600',
  },
  segmentControl: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginBottom: 16,
    paddingHorizontal: 18,
  },
  segmentItem: {
    alignItems: 'center',
  },
  segmentIconPlaceholder: {
    width: 48,
    height: 48,
    borderRadius: 12,
    backgroundColor: '#F3F4F6',
    alignItems: 'center',
    justifyContent: 'center',
    marginBottom: 4,
  },
  segmentIconActive: {
    backgroundColor: '#E0E7FF',
  },
  segmentText: {
    fontSize: 14,
    color: '#6B7280',
  },
  segmentTextActive: {
    color: '#5B4CFF',
    fontWeight: 'bold',
  },
  privacyNoticeContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: 20,
    paddingHorizontal: 16,
    marginTop: 32,
    marginBottom: 16,
  },
  privacyIconWrapper: {
    marginRight: 6,
  },
  privacyNoticeText: {
    fontSize: 12,
    color: '#9CA3AF',
    textAlign: 'center',
    lineHeight: 18,
  },

});
