/**
 * 资料详情页：展示资料详细信息
 */
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 {
  spacing,
  fontSizes,
  borderRadius,
  shadows,
  useAppColors,
  useResolvedColorScheme,
  type AppColors,
} from '../../theme';
import { Text, ResponsiveContainer, Loading } from '../../components/common';
import { useResponsive, useResponsiveSpacing, useBreakpointGTE } from '../../hooks/useResponsive';
import type { MaterialFile } from '../../types/material';
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) => {
    const date = new Date(dateStr);
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'long',
      day: 'numeric',
    });
  }, []);

  const cardStyle = useMemo(
    () => ({
      backgroundColor: colors.background.paper,
      borderRadius: 16,
      overflow: 'hidden' as const,
      shadowColor: '#000',
      shadowOffset: { width: 0, height: 2 },
      shadowOpacity: 0.06,
      shadowRadius: 8,
      elevation: 2,
    }),
    [colors]
  );

  const renderContent = () => {
    if (isLoading) {
      return (
        <View style={styles.centerContainer}>
          <Loading size="large" />
        </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 }]}>
            <MaterialCommunityIcons name={iconName as any} size={48} color="#FFFFFF" />
            <Text variant="body" style={styles.fileTypeName}>
              {fileTypeName}
            </Text>
          </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.metaItem}>
                <MaterialCommunityIcons name="file-outline" size={16} color={colors.text.hint} />
                <Text variant="caption" color={colors.text.hint}>
                  {formatFileSize(material.file_size)}
                </Text>
              </View>
              <View style={styles.metaItem}>
                <MaterialCommunityIcons name="download" size={16} color={colors.text.hint} />
                <Text variant="caption" color={colors.text.hint}>
                  {material.download_count} 次下载
                </Text>
              </View>
            </View>
          </View>
        </View>

        {/* 详细信息 */}
        <View style={[styles.detailCard, cardStyle]}>
          <Text variant="body" style={styles.sectionTitle}>
            详细信息
          </Text>
          <View style={styles.detailRow}>
            <Text variant="caption" color={colors.text.hint} style={styles.detailLabel}>
              文件名
            </Text>
            <Text variant="body" color={colors.text.primary} style={styles.detailValue}>
              {material.file_name}
            </Text>
          </View>
          <View style={styles.detailRow}>
            <Text variant="caption" color={colors.text.hint} style={styles.detailLabel}>
              上传时间
            </Text>
            <Text variant="body" color={colors.text.primary} style={styles.detailValue}>
              {formatDate(material.created_at)}
            </Text>
          </View>
          {material.author_name && (
            <View style={styles.detailRow}>
              <Text variant="caption" color={colors.text.hint} style={styles.detailLabel}>
                上传者
              </Text>
              <Text variant="body" color={colors.text.primary} style={styles.detailValue}>
                {material.author_name}
              </Text>
            </View>
          )}
          {material.tags && material.tags.length > 0 && (
            <View style={styles.tagContainer}>
              <Text variant="caption" color={colors.text.hint} style={styles.detailLabel}>
                标签
              </Text>
              <View style={styles.tags}>
                {material.tags.map((tag, index) => (
                  <View key={index} style={styles.tag}>
                    <Text variant="caption" color={colors.primary.main}>
                      {tag}
                    </Text>
                  </View>
                ))}
              </View>
            </View>
          )}
        </View>

        {/* 操作按钮 */}
        <View style={styles.actionButtons}>
          <TouchableOpacity
            style={[styles.previewButton, { backgroundColor: colors.background.paper }]}
            onPress={handlePreview}
            activeOpacity={0.8}
          >
            <MaterialCommunityIcons name="eye-outline" size={20} color={colors.text.primary} />
            <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}
          >
            <MaterialCommunityIcons name="download" size={20} color={colors.primary.contrast} />
            <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}>
          <TouchableOpacity onPress={() => router.back()} style={styles.backButton}>
            <MaterialCommunityIcons name="arrow-left" size={24} color={colors.text.primary} />
          </TouchableOpacity>
        </View>
        <View style={styles.headerCenter}>
          <Text style={[styles.headerTitle, isWideScreen && styles.headerTitleWide]}>
            资料详情
          </Text>
        </View>
        <View style={styles.headerRight}>
          <TouchableOpacity style={styles.shareButton}>
            <MaterialCommunityIcons name="share-variant" size={22} color={colors.text.primary} />
          </TouchableOpacity>
        </View>
      </View>

      {/* Content */}
      {isWideScreen ? (
        <ResponsiveContainer maxWidth={800}>
          <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: {
      flexDirection: 'row',
      alignItems: 'center',
      justifyContent: 'space-between',
      paddingHorizontal: spacing.md,
      paddingVertical: spacing.md,
      backgroundColor: headerBg,
      ...shadows.sm,
    },
    headerWide: {
      paddingHorizontal: spacing.lg,
      paddingVertical: spacing.lg,
    },
    headerLeft: {
      width: 44,
      alignItems: 'flex-start',
    },
    backButton: {
      padding: spacing.xs,
    },
    headerCenter: {
      flexDirection: 'row',
      alignItems: 'center',
    },
    headerTitle: {
      fontSize: 19,
      fontWeight: '700',
      color: colors.text.primary,
    },
    headerTitleWide: {
      fontSize: 22,
    },
    headerRight: {
      width: 44,
      alignItems: 'flex-end',
    },
    shareButton: {
      padding: spacing.xs,
    },
    scroll: {
      flex: 1,
      backgroundColor: headerBg,
    },
    scrollContent: {
      paddingTop: spacing.md,
      flexGrow: 1,
      backgroundColor: headerBg,
    },
    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,
    },
    fileCard: {
      marginBottom: spacing.md,
    },
    fileTypeBanner: {
      height: 100,
      alignItems: 'center',
      justifyContent: 'center',
    },
    fileTypeName: {
      color: '#FFFFFF',
      fontWeight: '700',
      fontSize: fontSizes.lg,
      marginTop: spacing.sm,
    },
    fileInfo: {
      padding: spacing.lg,
    },
    fileName: {
      color: colors.text.primary,
      fontWeight: '700',
      fontSize: fontSizes.lg,
    },
    fileDescription: {
      marginTop: spacing.sm,
      lineHeight: fontSizes.md * 1.5,
    },
    fileMetaRow: {
      flexDirection: 'row',
      marginTop: spacing.md,
      gap: spacing.md,
    },
    metaItem: {
      flexDirection: 'row',
      alignItems: 'center',
      gap: spacing.xs,
    },
    detailCard: {
      padding: spacing.lg,
      marginBottom: spacing.md,
    },
    sectionTitle: {
      fontWeight: '700',
      fontSize: fontSizes.md,
      color: colors.text.primary,
      marginBottom: spacing.md,
    },
    detailRow: {
      flexDirection: 'row',
      justifyContent: 'space-between',
      alignItems: 'center',
      paddingVertical: spacing.sm,
      borderBottomWidth: 1,
      borderBottomColor: colors.divider,
    },
    detailLabel: {
      width: 80,
    },
    detailValue: {
      flex: 1,
      textAlign: 'right',
    },
    tagContainer: {
      flexDirection: 'row',
      alignItems: 'center',
      marginTop: spacing.sm,
    },
    tags: {
      flexDirection: 'row',
      flexWrap: 'wrap',
      gap: spacing.xs,
      flex: 1,
    },
    tag: {
      paddingVertical: spacing.xs,
      paddingHorizontal: spacing.sm,
      backgroundColor: colors.background.paper,
      borderRadius: borderRadius.sm,
      borderWidth: 1,
      borderColor: colors.primary.main,
    },
    actionButtons: {
      flexDirection: 'row',
      gap: spacing.md,
      marginTop: spacing.lg,
    },
    previewButton: {
      flex: 1,
      flexDirection: 'row',
      alignItems: 'center',
      justifyContent: 'center',
      paddingVertical: spacing.md,
      borderRadius: borderRadius.lg,
      gap: spacing.xs,
    },
    downloadButton: {
      flex: 1,
      flexDirection: 'row',
      alignItems: 'center',
      justifyContent: 'center',
      paddingVertical: spacing.md,
      borderRadius: borderRadius.lg,
      gap: spacing.xs,
    },
    actionButtonText: {
      fontWeight: '600',
    },
  });
}