/**
 * 资料详情页：展示资料详细信息
 * 现代化扁平化设计，风格统一
 */
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import {
  View,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  StatusBar,
  Alert,
} from 'react-native';
import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context';
import { useRouter, useLocalSearchParams } from 'expo-router';
import { MaterialCommunityIcons } from '@expo/vector-icons';

import { AppBackButton } from '../../components/common';
import {
  spacing,
  fontSizes,
  borderRadius,
  shadows,
  useAppColors,
  useResolvedColorScheme,
  type AppColors,
} from '../../theme';
import { Text, ResponsiveContainer, Loading } from '../../components/common';
import { useResponsive, useResponsiveSpacing, useBreakpointGTE } from '../../hooks';
import type { MaterialFile } from '../../types/material';
import { formatDate as formatDateUtil } from '../../utils/formatTime';
import { materialRepository } from '../../data/repositories/MaterialRepository';
import {
  MATERIAL_FILE_TYPE_ICONS,
  MATERIAL_FILE_TYPE_COLORS,
  MATERIAL_FILE_TYPE_NAMES,
  formatFileSize,
} from '../../types/material';

export const MaterialDetailScreen: React.FC = () => {
  const colors = useAppColors();
  const resolvedScheme = useResolvedColorScheme();
  const statusBarStyle = resolvedScheme === 'dark' ? 'light-content' : 'dark-content';
  const styles = useMemo(() => createMaterialDetailStyles(colors), [colors]);
  const router = useRouter();
  const params = useLocalSearchParams<{ materialId: string }>();
  const insets = useSafeAreaInsets();
  const { isMobile } = useResponsive();
  const isWideScreen = useBreakpointGTE('lg');
  const responsivePadding = useResponsiveSpacing({ xs: 8, sm: 12, md: 16, lg: 24, xl: 32 });

  const [material, setMaterial] = useState<MaterialFile | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const scrollBottomInset = isMobile ? 88 + insets.bottom + spacing.md : spacing['3xl'];

  const loadMaterial = useCallback(async () => {
    if (!params.materialId) {
      setError('缺少资料ID');
      setIsLoading(false);
      return;
    }

    try {
      setError(null);
      const data = await materialRepository.getMaterialById(params.materialId);
      setMaterial(data);
    } catch (err) {
      setError('加载资料详情失败');
      console.error('Failed to load material:', err);
    } finally {
      setIsLoading(false);
    }
  }, [params.materialId]);

  useEffect(() => {
    loadMaterial();
  }, [loadMaterial]);

  const handleDownload = useCallback(() => {
    if (!material) return;

    Alert.alert(
      '下载资料',
      `确定要下载「${material.title}」吗？`,
      [
        { text: '取消', style: 'cancel' },
        {
          text: '下载',
          onPress: () => {
            // Mock下载逻辑
            Alert.alert('提示', '下载功能开发中，请稍后再试');
          },
        },
      ]
    );
  }, [material]);

  const handlePreview = useCallback(() => {
    if (!material?.file_url) return;

    Alert.alert(
      '在线预览',
      '在线预览功能开发中，请稍后再试',
      [{ text: '确定', style: 'default' }]
    );
  }, [material]);

  const formatDate = useCallback((dateStr: string) => formatDateUtil(dateStr), []);

  // 扁平化卡片样式：更柔和的阴影，更大的圆角
  const cardStyle = useMemo(
    () => ({
      backgroundColor: colors.background.paper,
      borderRadius: borderRadius.xl,
      overflow: 'hidden' as const,
      shadowColor: colors.chat.shadow,
      shadowOffset: { width: 0, height: 2 },
      shadowOpacity: 0.06,
      shadowRadius: 8,
      elevation: 2,
    }),
    [colors]
  );

  const renderContent = () => {
    if (isLoading) {
      return (
        <View style={styles.centerContainer}>
          <Loading size="lg" />
        </View>
      );
    }

    if (error || !material) {
      return (
        <View style={styles.centerContainer}>
          <MaterialCommunityIcons name="alert-circle-outline" size={48} color={colors.text.hint} />
          <Text variant="body" color={colors.text.secondary} style={styles.errorText}>
            {error || '资料不存在'}
          </Text>
          <TouchableOpacity onPress={() => router.back()} style={styles.retryButton}>
            <Text variant="body" color={colors.primary.main}>
              返回
            </Text>
          </TouchableOpacity>
        </View>
      );
    }

    const fileColor = MATERIAL_FILE_TYPE_COLORS[material.file_type];
    const iconName = MATERIAL_FILE_TYPE_ICONS[material.file_type];
    const fileTypeName = MATERIAL_FILE_TYPE_NAMES[material.file_type];

    return (
      <>
        {/* 文件信息卡片 - 现代化设计 */}
        <View style={[styles.fileCard, cardStyle]}>
          {/* 顶部文件类型标识区 - 扁平化渐变 */}
          <View style={[styles.fileTypeBanner, { backgroundColor: fileColor }]}>
            <View style={styles.fileIconWrapper}>
              <MaterialCommunityIcons name={iconName as any} size={40} color="#FFFFFF" />
            </View>
            <View style={styles.fileTypeBadge}>
              <Text variant="caption" style={styles.fileTypeName}>
                {fileTypeName}
              </Text>
            </View>
          </View>

          <View style={styles.fileInfo}>
            <Text variant="h3" style={styles.fileName}>
              {material.title}
            </Text>
            {material.description && (
              <Text variant="body" color={colors.text.secondary} style={styles.fileDescription}>
                {material.description}
              </Text>
            )}

            {/* 元数据 - 现代化标签式布局 */}
            <View style={styles.fileMetaRow}>
              <View style={[styles.metaBadge, { backgroundColor: `${colors.neutral.main}12` }]}>
                <MaterialCommunityIcons name="file-outline" size={14} color={colors.neutral.main} />
                <Text variant="caption" color={colors.neutral.dark} style={styles.metaBadgeText}>
                  {formatFileSize(material.file_size)}
                </Text>
              </View>
              <View style={[styles.metaBadge, { backgroundColor: `${colors.primary.main}12` }]}>
                <MaterialCommunityIcons name="download" size={14} color={colors.primary.main} />
                <Text variant="caption" color={colors.primary.dark} style={styles.metaBadgeText}>
                  {material.download_count} 次下载
                </Text>
              </View>
            </View>
          </View>
        </View>

        {/* 详细信息卡片 - 扁平化列表 */}
        <View style={[styles.detailCard, cardStyle]}>
          <View style={styles.sectionHeader}>
            <View style={[styles.sectionIcon, { backgroundColor: `${colors.info.main}12` }]}>
              <MaterialCommunityIcons name="information-outline" size={18} color={colors.info.main} />
            </View>
            <Text variant="body" style={styles.sectionTitle}>
              详细信息
            </Text>
          </View>

          <View style={styles.detailList}>
            <View style={styles.detailRow}>
              <View style={styles.detailLabelWrapper}>
                <MaterialCommunityIcons name="file-document-outline" size={16} color={colors.text.hint} />
                <Text variant="caption" color={colors.text.hint} style={styles.detailLabel}>
                  文件名
                </Text>
              </View>
              <Text variant="body" color={colors.text.primary} style={styles.detailValue}>
                {material.file_name}
              </Text>
            </View>

            <View style={styles.detailRow}>
              <View style={styles.detailLabelWrapper}>
                <MaterialCommunityIcons name="calendar-outline" size={16} color={colors.text.hint} />
                <Text variant="caption" color={colors.text.hint} style={styles.detailLabel}>
                  上传时间
                </Text>
              </View>
              <Text variant="body" color={colors.text.primary} style={styles.detailValue}>
                {formatDate(material.created_at)}
              </Text>
            </View>

            {material.author_name && (
              <View style={styles.detailRow}>
                <View style={styles.detailLabelWrapper}>
                  <MaterialCommunityIcons name="account-outline" size={16} color={colors.text.hint} />
                  <Text variant="caption" color={colors.text.hint} style={styles.detailLabel}>
                    上传者
                  </Text>
                </View>
                <Text variant="body" color={colors.text.primary} style={styles.detailValue}>
                  {material.author_name}
                </Text>
              </View>
            )}
          </View>

          {material.tags && material.tags.length > 0 && (
            <View style={styles.tagSection}>
              <View style={styles.tagSectionHeader}>
                <MaterialCommunityIcons name="tag-outline" size={16} color={colors.text.hint} />
                <Text variant="caption" color={colors.text.hint} style={styles.tagSectionTitle}>
                  标签
                </Text>
              </View>
              <View style={styles.tags}>
                {material.tags.map((tag, index) => (
                  <View key={index} style={[styles.tag, { backgroundColor: `${colors.primary.main}10` }]}>
                    <Text variant="caption" color={colors.primary.main} style={styles.tagText}>
                      {tag}
                    </Text>
                  </View>
                ))}
              </View>
            </View>
          )}
        </View>

        {/* 操作按钮 - 现代化扁平按钮 */}
        <View style={styles.actionButtons}>
          <TouchableOpacity
            style={[styles.previewButton, { backgroundColor: colors.background.paper }]}
            onPress={handlePreview}
            activeOpacity={0.7}
          >
            <View style={[styles.actionIconWrapper, { backgroundColor: `${colors.neutral.main}12` }]}>
              <MaterialCommunityIcons name="eye-outline" size={18} color={colors.neutral.dark} />
            </View>
            <Text variant="body" color={colors.text.primary} style={styles.actionButtonText}>
              在线预览
            </Text>
          </TouchableOpacity>

          <TouchableOpacity
            style={[styles.downloadButton, { backgroundColor: colors.primary.main }]}
            onPress={handleDownload}
            activeOpacity={0.8}
          >
            <View style={[styles.actionIconWrapper, { backgroundColor: 'rgba(255,255,255,0.2)' }]}>
              <MaterialCommunityIcons name="download" size={18} color="#FFFFFF" />
            </View>
            <Text variant="body" color={colors.primary.contrast} style={styles.actionButtonText}>
              下载资料
            </Text>
          </TouchableOpacity>
        </View>
      </>
    );
  };

  return (
    <SafeAreaView style={styles.container} edges={['top', 'bottom']}>
      <StatusBar barStyle={statusBarStyle} backgroundColor={colors.background.default} />

      {/* Header - 扁平化设计 */}
      <View style={[styles.header, isWideScreen && styles.headerWide]}>
        <View style={styles.headerLeft}>
          <AppBackButton onPress={() => router.back()} />
        </View>
        <View style={styles.headerCenter}>
          <Text style={isWideScreen ? [styles.headerTitle, styles.headerTitleWide] : styles.headerTitle}>
            资料详情
          </Text>
        </View>
        <View style={styles.headerRight}>
          <TouchableOpacity style={styles.shareButton} activeOpacity={0.7}>
            <MaterialCommunityIcons name="share-variant" size={20} color={colors.text.secondary} />
          </TouchableOpacity>
        </View>
      </View>

      {/* Content */}
      {isWideScreen ? (
        <ResponsiveContainer maxWidth={720}>
          <ScrollView
            style={styles.scroll}
            contentContainerStyle={[styles.scrollContent, { paddingBottom: scrollBottomInset }]}
            showsVerticalScrollIndicator={false}
          >
            {renderContent()}
          </ScrollView>
        </ResponsiveContainer>
      ) : (
        <ScrollView
          style={styles.scroll}
          contentContainerStyle={[
            styles.scrollContent,
            { paddingBottom: scrollBottomInset, paddingHorizontal: responsivePadding },
          ]}
          showsVerticalScrollIndicator={false}
        >
          {renderContent()}
        </ScrollView>
      )}
    </SafeAreaView>
  );
};

export default MaterialDetailScreen;

function createMaterialDetailStyles(colors: AppColors) {
  const headerBg = colors.background.default;
  return StyleSheet.create({
    container: {
      flex: 1,
      backgroundColor: colors.background.default,
    },
    // Header
    header: {
      flexDirection: 'row',
      alignItems: 'center',
      justifyContent: 'space-between',
      paddingHorizontal: spacing.md,
      paddingVertical: spacing.md,
      backgroundColor: headerBg,
      borderBottomWidth: 1,
      borderBottomColor: colors.chat.borderHairline,
    },
    headerWide: {
      paddingHorizontal: spacing.lg,
      paddingVertical: spacing.lg,
    },
    headerLeft: {
      width: 40,
      alignItems: 'flex-start',
    },
    headerCenter: {
      flexDirection: 'row',
      alignItems: 'center',
    },
    headerTitle: {
      fontSize: fontSizes.lg,
      fontWeight: '600',
      color: colors.text.primary,
      letterSpacing: 0.3,
    },
    headerTitleWide: {
      fontSize: fontSizes.xl,
    },
    headerRight: {
      width: 44,
      alignItems: 'flex-end',
    },
    shareButton: {
      padding: spacing.xs,
      borderRadius: borderRadius.md,
    },
    // Scroll
    scroll: {
      flex: 1,
      backgroundColor: headerBg,
    },
    scrollContent: {
      paddingTop: spacing.lg,
      flexGrow: 1,
      backgroundColor: headerBg,
    },
    // Center states
    centerContainer: {
      flex: 1,
      justifyContent: 'center',
      alignItems: 'center',
      paddingVertical: spacing['3xl'],
    },
    errorText: {
      marginTop: spacing.md,
      textAlign: 'center',
    },
    retryButton: {
      marginTop: spacing.md,
      paddingVertical: spacing.sm,
      paddingHorizontal: spacing.lg,
    },
    // File card
    fileCard: {
      marginBottom: spacing.lg,
    },
    fileTypeBanner: {
      height: 120,
      alignItems: 'center',
      justifyContent: 'center',
      position: 'relative',
    },
    fileIconWrapper: {
      width: 72,
      height: 72,
      borderRadius: borderRadius['2xl'],
      backgroundColor: 'rgba(255,255,255,0.2)',
      alignItems: 'center',
      justifyContent: 'center',
      marginBottom: spacing.sm,
    },
    fileTypeBadge: {
      paddingVertical: spacing.xs,
      paddingHorizontal: spacing.md,
      borderRadius: borderRadius.full,
      backgroundColor: 'rgba(255,255,255,0.25)',
    },
    fileTypeName: {
      color: '#FFFFFF',
      fontWeight: '700',
      fontSize: fontSizes.sm,
      letterSpacing: 0.5,
    },
    fileInfo: {
      padding: spacing.lg,
    },
    fileName: {
      color: colors.text.primary,
      fontWeight: '700',
      fontSize: fontSizes.xl,
      lineHeight: fontSizes.xl * 1.4,
    },
    fileDescription: {
      marginTop: spacing.sm,
      lineHeight: fontSizes.md * 1.6,
      color: colors.text.secondary,
    },
    fileMetaRow: {
      flexDirection: 'row',
      marginTop: spacing.lg,
      gap: spacing.sm,
      flexWrap: 'wrap',
    },
    metaBadge: {
      flexDirection: 'row',
      alignItems: 'center',
      gap: spacing.xs,
      paddingVertical: spacing.xs + 2,
      paddingHorizontal: spacing.md,
      borderRadius: borderRadius.full,
    },
    metaBadgeText: {
      fontWeight: '500',
      fontSize: fontSizes.sm,
    },
    // Detail card
    detailCard: {
      padding: spacing.lg,
      marginBottom: spacing.lg,
    },
    sectionHeader: {
      flexDirection: 'row',
      alignItems: 'center',
      marginBottom: spacing.md,
      gap: spacing.sm,
    },
    sectionIcon: {
      width: 32,
      height: 32,
      borderRadius: borderRadius.md,
      alignItems: 'center',
      justifyContent: 'center',
    },
    sectionTitle: {
      fontWeight: '700',
      fontSize: fontSizes.md,
      color: colors.text.primary,
      letterSpacing: 0.2,
    },
    detailList: {
      gap: 0,
    },
    detailRow: {
      flexDirection: 'row',
      justifyContent: 'space-between',
      alignItems: 'center',
      paddingVertical: spacing.md,
      borderBottomWidth: 1,
      borderBottomColor: colors.chat.borderHairline,
    },
    detailLabelWrapper: {
      flexDirection: 'row',
      alignItems: 'center',
      gap: spacing.sm,
      flex: 1,
    },
    detailLabel: {
      fontWeight: '500',
    },
    detailValue: {
      flex: 1.5,
      textAlign: 'right',
      fontWeight: '500',
    },
    // Tags
    tagSection: {
      marginTop: spacing.md,
    },
    tagSectionHeader: {
      flexDirection: 'row',
      alignItems: 'center',
      gap: spacing.sm,
      marginBottom: spacing.sm,
    },
    tagSectionTitle: {
      fontWeight: '500',
    },
    tags: {
      flexDirection: 'row',
      flexWrap: 'wrap',
      gap: spacing.sm,
    },
    tag: {
      paddingVertical: spacing.xs + 2,
      paddingHorizontal: spacing.md,
      borderRadius: borderRadius.full,
    },
    tagText: {
      fontWeight: '600',
      fontSize: fontSizes.sm,
    },
    // Action buttons
    actionButtons: {
      flexDirection: 'row',
      gap: spacing.md,
      marginTop: spacing.sm,
      marginBottom: spacing.lg,
    },
    previewButton: {
      flex: 1,
      flexDirection: 'row',
      alignItems: 'center',
      justifyContent: 'center',
      paddingVertical: spacing.md,
      borderRadius: borderRadius.xl,
      gap: spacing.sm,
      borderWidth: 1,
      borderColor: colors.chat.border,
      shadowColor: colors.chat.shadow,
      shadowOffset: { width: 0, height: 1 },
      shadowOpacity: 0.04,
      shadowRadius: 4,
      elevation: 1,
    },
    downloadButton: {
      flex: 1,
      flexDirection: 'row',
      alignItems: 'center',
      justifyContent: 'center',
      paddingVertical: spacing.md,
      borderRadius: borderRadius.xl,
      gap: spacing.sm,
      shadowColor: colors.primary.main,
      shadowOffset: { width: 0, height: 4 },
      shadowOpacity: 0.25,
      shadowRadius: 8,
      elevation: 4,
    },
    actionIconWrapper: {
      width: 32,
      height: 32,
      borderRadius: borderRadius.md,
      alignItems: 'center',
      justifyContent: 'center',
    },
    actionButtonText: {
      fontWeight: '700',
      fontSize: fontSizes.md,
      letterSpacing: 0.3,
    },
  });
}
