import { Colors } from '@/constants/Colors';
import { useColorScheme } from '@/hooks/useColorScheme';
import { Ionicons } from '@expo/vector-icons';
import { GlassView, isLiquidGlassAvailable } from 'expo-glass-effect';
import { useRouter } from 'expo-router';
import React from 'react';
import { Linking, ScrollView, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';

// 参考文献数据
const references = [
    {
    id: 5,
    name: '中国国家卫生健康委员会（国家卫健委）',
    englishName: 'National Health Commission of the People\'s Republic of China',
    url: 'http://www.nhc.gov.cn',
    note: '（用于中文用户环境非常合适）',
  },
  {
    id: 1,
    name: '美国国立卫生研究院（NIH）',
    englishName: 'National Institutes of Health',
    url: 'https://www.nih.gov',
  },
  {
    id: 3,
    name: '世界卫生组织（WHO）',
    englishName: 'World Health Organization',
    url: 'https://www.who.int',
  },

  {
    id: 6,
    name: '中国营养学会（Chinese Nutrition Society）',
    englishName: 'Chinese Nutrition Society',
    url: 'https://www.cnsoc.org',
  },
];

export default function FastingReferencesScreen() {
  const router = useRouter();
  const insets = useSafeAreaInsets();
  const theme = useColorScheme() ?? 'light';
  const colors = Colors[theme];
  const glassAvailable = isLiquidGlassAvailable();

  const handleBack = () => {
    router.back();
  };

  const handleLinkPress = async (url: string) => {
    try {
      const canOpen = await Linking.canOpenURL(url);
      if (canOpen) {
        await Linking.openURL(url);
      } else {
        console.log('无法打开链接:', url);
      }
    } catch (error) {
      console.error('打开链接时发生错误:', error);
    }
  };

  return (
    <View style={[styles.safeArea, { backgroundColor: '#ffffff' }]}>
      {/* 固定悬浮的返回按钮 */}
      <View style={[styles.backButtonContainer, { paddingTop: insets.top + 12 }]}>
        <TouchableOpacity style={styles.backButton} onPress={handleBack} activeOpacity={0.8}>
          {glassAvailable ? (
            <GlassView
              style={styles.backButtonGlass}
              glassEffectStyle="regular"
              tintColor="rgba(255,255,255,0.4)"
              isInteractive={true}
            >
              <Ionicons name="chevron-back" size={24} color="#2E3142" />
            </GlassView>
          ) : (
            <View style={styles.backButtonFallback}>
              <Ionicons name="chevron-back" size={24} color="#2E3142" />
            </View>
          )}
        </TouchableOpacity>
      </View>

      <ScrollView 
        contentContainerStyle={[
          styles.scrollContainer,
          { paddingTop: insets.top + 80 }
        ]}
        showsVerticalScrollIndicator={false}
      >
        <View style={styles.headerSection}>
          <Text style={styles.title}>参考文献与医学来源</Text>
          <Text style={styles.subtitle}>
            本应用的断食相关功能和建议基于以下权威医学机构的科学研究和指导原则
          </Text>
        </View>

        <View style={styles.referencesList}>
          {references.map((reference) => (
            <View key={reference.id} style={styles.referenceCard}>
              <View style={styles.referenceHeader}>
                <View style={styles.referenceIcon}>
                  <Ionicons name="medical-outline" size={24} color="#2E3142" />
                </View>
                <View style={styles.referenceInfo}>
                  <Text style={styles.referenceName}>{reference.name}</Text>
                  <Text style={styles.referenceEnglishName}>{reference.englishName}</Text>
                </View>
              </View>
              
              <TouchableOpacity
                style={styles.referenceLink}
                onPress={() => handleLinkPress(reference.url)}
                activeOpacity={0.8}
              >
                <Text style={styles.referenceUrl}>{reference.url}</Text>
                <Ionicons name="open-outline" size={16} color="#6F7D87" />
              </TouchableOpacity>
              
              {reference.note && (
                <Text style={styles.referenceNote}>{reference.note}</Text>
              )}
            </View>
          ))}
        </View>

        <View style={styles.disclaimerSection}>
          <View style={styles.disclaimerHeader}>
            <Ionicons name="information-circle-outline" size={20} color="#6F7D87" />
            <Text style={styles.disclaimerTitle}>重要声明</Text>
          </View>
          <Text style={styles.disclaimerText}>
            本应用提供的断食相关信息仅供参考，不能替代专业医疗建议。在开始任何断食计划前，
            请咨询医生或专业医疗人员的意见，特别是如果您有基础疾病、正在服药或处于特殊生理时期（如怀孕、哺乳期等）。
          </Text>
        </View>
      </ScrollView>
    </View>
  );
}

const styles = StyleSheet.create({
  safeArea: {
    flex: 1,
  },
  backButtonContainer: {
    position: 'absolute',
    top: 0,
    left: 24,
    zIndex: 10,
  },
  backButton: {
    width: 44,
    height: 44,
    borderRadius: 22,
    alignItems: 'center',
    justifyContent: 'center',
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 4,
    },
    shadowOpacity: 0.15,
    shadowRadius: 8,
    elevation: 8,
  },
  backButtonGlass: {
    width: 44,
    height: 44,
    borderRadius: 22,
    alignItems: 'center',
    justifyContent: 'center',
    borderWidth: 1,
    borderColor: 'rgba(255,255,255,0.3)',
    overflow: 'hidden',
  },
  backButtonFallback: {
    width: 44,
    height: 44,
    borderRadius: 22,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'rgba(255,255,255,0.85)',
    borderWidth: 1,
    borderColor: 'rgba(255,255,255,0.5)',
  },
  scrollContainer: {
    paddingHorizontal: 24,
    paddingBottom: 40,
  },
  headerSection: {
    alignItems: 'center',
    marginBottom: 32,
  },
  title: {
    fontSize: 28,
    fontWeight: '800',
    color: '#2E3142',
    marginBottom: 12,
    textAlign: 'center',
  },
  subtitle: {
    fontSize: 16,
    color: '#6F7D87',
    textAlign: 'center',
    lineHeight: 24,
    paddingHorizontal: 20,
  },
  referencesList: {
    marginBottom: 32,
  },
  referenceCard: {
    backgroundColor: '#FFFFFF',
    borderRadius: 20,
    padding: 20,
    marginBottom: 16,
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 8,
    },
    shadowOpacity: 0.06,
    shadowRadius: 16,
    elevation: 4,
  },
  referenceHeader: {
    flexDirection: 'row',
    alignItems: 'flex-start',
    marginBottom: 12,
  },
  referenceIcon: {
    width: 48,
    height: 48,
    borderRadius: 24,
    backgroundColor: 'rgba(46, 49, 66, 0.08)',
    alignItems: 'center',
    justifyContent: 'center',
    marginRight: 16,
  },
  referenceInfo: {
    flex: 1,
  },
  referenceName: {
    fontSize: 16,
    fontWeight: '700',
    color: '#2E3142',
    marginBottom: 4,
  },
  referenceEnglishName: {
    fontSize: 14,
    color: '#6F7D87',
    lineHeight: 20,
  },
  referenceLink: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    backgroundColor: 'rgba(111, 125, 135, 0.08)',
    paddingHorizontal: 16,
    paddingVertical: 12,
    borderRadius: 12,
    marginBottom: 8,
  },
  referenceUrl: {
    fontSize: 14,
    color: '#2E3142',
    flex: 1,
  },
  referenceNote: {
    fontSize: 13,
    color: '#8A96A3',
    fontStyle: 'italic',
    lineHeight: 18,
  },
  disclaimerSection: {
    backgroundColor: 'rgba(255, 248, 225, 0.6)',
    borderRadius: 20,
    padding: 20,
    borderWidth: 1,
    borderColor: 'rgba(255, 193, 7, 0.2)',
  },
  disclaimerHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 12,
  },
  disclaimerTitle: {
    fontSize: 16,
    fontWeight: '700',
    color: '#2E3142',
    marginLeft: 8,
  },
  disclaimerText: {
    fontSize: 14,
    color: '#5B6572',
    lineHeight: 22,
  },
});