/**
 * UserProfileHeader 用户资料头部组件 - 美化版（响应式适配）
 * 显示用户封面、头像、昵称、简介、关注/粉丝数
 * 采用现代卡片式设计，渐变封面，悬浮头像
 * 支持互关状态显示
 * 在宽屏下显示更大的头像和封面
 */

import React, { useMemo } from 'react';
import {
  View,
  Image,
  TouchableOpacity,
  StyleSheet,
} from 'react-native';
import { MaterialCommunityIcons } from '@expo/vector-icons';
import { LinearGradient } from 'expo-linear-gradient';
import { spacing, fontSizes, borderRadius, shadows, useAppColors, type AppColors } from '../../theme';
import { User } from '../../types';
import Text from '../common/Text';
import Button from '../common/Button';
import Avatar from '../common/Avatar';
import { useResponsive } from '../../hooks';

interface UserProfileHeaderProps {
  user: User;
  isCurrentUser?: boolean;
  onFollow: () => void;
  onSettings?: () => void;
  onEditProfile?: () => void;
  onMessage?: () => void;
  onMore?: () => void;             // 点击更多按钮
  onPostsPress?: () => void;       // 点击帖子数（可选）
  onFollowingPress?: () => void;   // 点击关注数
  onFollowersPress?: () => void;   // 点击粉丝数
  onAvatarPress?: () => void;      // 点击头像编辑按钮
}

const UserProfileHeader: React.FC<UserProfileHeaderProps> = ({
  user,
  isCurrentUser = false,
  onFollow,
  onSettings,
  onEditProfile,
  onMessage,
  onMore,
  onPostsPress,
  onFollowingPress,
  onFollowersPress,
  onAvatarPress,
}) => {
  const colors = useAppColors();
  const styles = useMemo(() => createUserProfileHeaderStyles(colors), [colors]);
  const { isWideScreen, isDesktop, width } = useResponsive();

  // 格式化数字
  const formatCount = (count: number | undefined): string => {
    if (count === undefined || count === null) {
      return '0';
    }
    if (count >= 10000) {
      return `${(count / 10000).toFixed(1)}w`;
    }
    if (count >= 1000) {
      return `${(count / 1000).toFixed(1)}k`;
    }
    return count.toString();
  };

  // 获取帖子数量
  const getPostsCount = (): number => {
    return user.posts_count ?? 0;
  };

  // 获取粉丝数量
  const getFollowersCount = (): number => {
    return user.followers_count ?? 0;
  };

  // 获取关注数量
  const getFollowingCount = (): number => {
    return user.following_count ?? 0;
  };

  // 检查是否关注
  const getIsFollowing = (): boolean => {
    return user.is_following ?? false;
  };

  // 检查对方是否关注了我
  const getIsFollowingMe = (): boolean => {
    return user.is_following_me ?? false;
  };

  // 获取按钮配置（类似B站的互关逻辑）
  const getButtonConfig = (): { title: string; variant: 'primary' | 'outline'; icon?: string } => {
    const isFollowing = getIsFollowing();
    const isFollowingMe = getIsFollowingMe();

    if (isFollowing && isFollowingMe) {
      // 已互关
      return { title: '互相关注', variant: 'outline', icon: 'account-check' };
    } else if (isFollowing) {
      // 已关注但对方未回关
      return { title: '已关注', variant: 'outline', icon: 'check' };
    } else if (isFollowingMe) {
      // 对方关注了我，但我没关注对方 - 显示回关
      return { title: '回关', variant: 'primary', icon: 'plus' };
    } else {
      // 互不关注
      return { title: '关注', variant: 'primary', icon: 'plus' };
    }
  };

  // 根据屏幕尺寸计算封面高度
  const coverHeight = isDesktop ? 240 : isWideScreen ? 200 : (width * 9) / 16;
  
  // 根据屏幕尺寸计算头像大小
  const avatarSize = isDesktop ? 120 : isWideScreen ? 100 : 90;

  const renderStatItem = ({
    value,
    label,
    onPress,
  }: {
    value: string;
    label: string;
    onPress?: () => void;
  }) => {
    const content = (
      <View style={styles.statContent}>
        <Text variant="h3" style={styles.statNumber}>{value}</Text>
        <Text variant="caption" color={colors.text.secondary} style={styles.statLabel}>
          {label}
        </Text>
      </View>
    );

    if (onPress) {
      return (
        <TouchableOpacity
          style={[styles.statItem, styles.statItemTouchable]}
          onPress={onPress}
          activeOpacity={0.75}
        >
          {content}
        </TouchableOpacity>
      );
    }

    return <View style={styles.statItem}>{content}</View>;
  };

  return (
    <View style={styles.container}>
      {/* 渐变封面背景 */}
      <View style={[styles.coverContainer, { height: coverHeight }]}>
        <View style={styles.coverTouchable}>
          {user.cover_url ? (
            <Image
              source={{ uri: user.cover_url }}
              style={styles.coverImage}
              resizeMode="cover"
            />
          ) : (
            <LinearGradient
              colors={['#FF8F66', '#FF6B35', '#E5521D']}
              start={{ x: 0, y: 0 }}
              end={{ x: 1, y: 1 }}
              style={styles.gradient}
            />
          )}
        </View>
        
        {/* 设置按钮 */}
        {isCurrentUser && onSettings && (
          <TouchableOpacity style={styles.settingsButton} onPress={onSettings}>
            <MaterialCommunityIcons name="cog-outline" size={22} color={colors.text.inverse} />
          </TouchableOpacity>
        )}

        {/* 装饰性波浪 */}
        <View style={styles.waveDecoration}>
          <View style={styles.wave} />
        </View>
      </View>

      {/* 用户信息卡片 */}
      <View style={[
        styles.profileCard,
        isWideScreen && styles.profileCardWide,
      ]}>
        {/* 悬浮头像 */}
        <View style={[
          styles.avatarWrapper,
          isWideScreen && styles.avatarWrapperWide,
        ]}>
          <View style={styles.avatarContainer}>
            <Avatar
              source={user.avatar}
              size={avatarSize}
              name={user.nickname}
            />
            {isCurrentUser && onAvatarPress && (
              <TouchableOpacity style={styles.editAvatarButton} onPress={onAvatarPress}>
                <MaterialCommunityIcons name="camera" size={14} color={colors.text.inverse} />
              </TouchableOpacity>
            )}
          </View>
        </View>

        {/* 用户名和简介 */}
        <View style={styles.userInfo}>
          <Text variant="h2" style={[
            styles.nickname,
            isWideScreen ? styles.nicknameWide : {},
          ]}>
            {user.nickname}
          </Text>
          <Text variant="caption" color={colors.text.secondary} style={styles.username}>
            @{user.username}
          </Text>
          
          {user.bio ? (
            <Text variant="body" color={colors.text.secondary} style={[
              styles.bio,
              isWideScreen ? styles.bioWide : {},
            ]}>
              {user.bio}
            </Text>
          ) : (
            <Text variant="body" color={colors.text.hint} style={styles.bioPlaceholder}>
              这个人很懒，还没有写简介~
            </Text>
          )}
        </View>

        {/* 个人信息标签 */}
        <View style={styles.metaInfo}>
          {user.location?.trim() ? (
            <View style={styles.metaTag}>
              <MaterialCommunityIcons name="map-marker-outline" size={12} color={colors.primary.main} />
              <Text variant="caption" color={colors.primary.main} style={styles.metaTagText}>
                {user.location}
              </Text>
            </View>
          ) : null}
          {user.website?.trim() ? (
            <View style={styles.metaTag}>
              <MaterialCommunityIcons name="link-variant" size={12} color={colors.info.main} />
              <Text variant="caption" color={colors.info.main} style={styles.metaTagText}>
                {user.website.replace(/^https?:\/\//, '')}
              </Text>
            </View>
          ) : null}
          <View style={styles.metaTag}>
            <MaterialCommunityIcons name="calendar-outline" size={12} color={colors.text.secondary} />
            <Text variant="caption" color={colors.text.secondary} style={styles.metaTagText}>
              加入于 {new Date(user.created_at || Date.now()).getFullYear()}年
            </Text>
          </View>
        </View>

        {/* 统计数据 - 卡片式 */}
        <View style={[
          styles.statsCard,
          isWideScreen && styles.statsCardWide,
        ]}>
          {renderStatItem({
            value: formatCount(getPostsCount()),
            label: '帖子',
            onPress: onPostsPress,
          })}
          <View style={styles.statDivider} />
          {renderStatItem({
            value: formatCount(getFollowingCount()),
            label: '关注',
            onPress: onFollowingPress,
          })}
          <View style={styles.statDivider} />
          {renderStatItem({
            value: formatCount(getFollowersCount()),
            label: '粉丝',
            onPress: onFollowersPress,
          })}
        </View>

        {/* 操作按钮 */}
        <View style={styles.actionButtons}>
          {isCurrentUser ? (
            <View style={styles.buttonRow} />
          ) : (
            <View style={StyleSheet.flatten([
              styles.buttonRow,
              isWideScreen && styles.buttonRowWide,
            ])}>
              <Button
                title={getButtonConfig().title}
                onPress={onFollow}
                variant={getButtonConfig().variant}
                style={StyleSheet.flatten([
                  styles.followButton,
                  isWideScreen && styles.followButtonWide,
                ])}
                icon={getButtonConfig().icon}
              />
              <TouchableOpacity style={styles.messageButton} onPress={onMessage}>
                <MaterialCommunityIcons name="message-text-outline" size={20} color={colors.primary.main} />
              </TouchableOpacity>
              <TouchableOpacity style={styles.moreButton} onPress={onMore}>
                <MaterialCommunityIcons name="dots-horizontal" size={24} color={colors.text.secondary} />
              </TouchableOpacity>
            </View>
          )}
        </View>
      </View>
    </View>
  );
};

function createUserProfileHeaderStyles(colors: AppColors) {
  return StyleSheet.create({
  container: {
    backgroundColor: colors.background.default,
  },
  coverContainer: {
    position: 'relative',
    overflow: 'hidden',
  },
  coverTouchable: {
    width: '100%',
    height: '100%',
  },
  coverImage: {
    width: '100%',
    height: '100%',
  },
  gradient: {
    width: '100%',
    height: '100%',
  },
  settingsButton: {
    position: 'absolute',
    top: spacing.lg,
    right: spacing.lg,
    width: 40,
    height: 40,
    borderRadius: 20,
    backgroundColor: 'rgba(0, 0, 0, 0.3)',
    justifyContent: 'center',
    alignItems: 'center',
  },
  waveDecoration: {
    position: 'absolute',
    bottom: 0,
    left: 0,
    right: 0,
    height: 40,
  },
  wave: {
    width: '100%',
    height: '100%',
    backgroundColor: colors.background.default,
    borderTopLeftRadius: 30,
    borderTopRightRadius: 30,
  },
  profileCard: {
    backgroundColor: colors.background.paper,
    marginHorizontal: spacing.md,
    marginTop: -50,
    borderRadius: borderRadius.xl,
    padding: spacing.lg,
    ...shadows.md,
  },
  profileCardWide: {
    marginHorizontal: spacing.lg,
    marginTop: -60,
    padding: spacing.xl,
  },
  avatarWrapper: {
    alignItems: 'center',
    marginTop: -60,
    marginBottom: spacing.md,
  },
  avatarWrapperWide: {
    marginTop: -80,
    marginBottom: spacing.lg,
  },
  avatarContainer: {
    position: 'relative',
    padding: 4,
    backgroundColor: colors.background.paper,
    borderRadius: 50,
  },
  editAvatarButton: {
    position: 'absolute',
    bottom: 0,
    right: 0,
    width: 28,
    height: 28,
    borderRadius: 14,
    backgroundColor: colors.primary.main,
    justifyContent: 'center',
    alignItems: 'center',
    borderWidth: 2,
    borderColor: colors.background.paper,
  },
  userInfo: {
    alignItems: 'center',
    marginBottom: spacing.md,
  },
  nickname: {
    marginBottom: spacing.xs,
    fontWeight: '700',
  },
  nicknameWide: {
    fontSize: fontSizes['3xl'],
  },
  username: {
    marginBottom: spacing.sm,
  },
  bio: {
    textAlign: 'center',
    marginTop: spacing.sm,
    lineHeight: 20,
  },
  bioWide: {
    fontSize: fontSizes.md,
    lineHeight: 24,
    maxWidth: 600,
  },
  bioPlaceholder: {
    textAlign: 'center',
    marginTop: spacing.sm,
    fontStyle: 'italic',
  },
  metaInfo: {
    flexDirection: 'row',
    justifyContent: 'center',
    flexWrap: 'wrap',
    marginBottom: spacing.md,
    gap: spacing.sm,
  },
  metaTag: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: colors.background.default,
    paddingHorizontal: spacing.sm,
    paddingVertical: spacing.xs,
    borderRadius: borderRadius.md,
  },
  metaTagText: {
    marginLeft: spacing.xs,
    fontSize: fontSizes.xs,
  },
  statsCard: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    alignItems: 'center',
    backgroundColor: 'transparent',
    paddingHorizontal: spacing.xs,
    paddingVertical: spacing.xs,
    marginBottom: spacing.md,
  },
  statsCardWide: {
    paddingHorizontal: spacing.sm,
    paddingVertical: spacing.sm,
    marginBottom: spacing.lg,
  },
  statItem: {
    flex: 1,
    minHeight: 58,
    justifyContent: 'center',
  },
  statItemTouchable: {
    borderRadius: borderRadius.md,
  },
  statContent: {
    alignItems: 'center',
    paddingVertical: spacing.sm,
    paddingHorizontal: spacing.xs,
  },
  statNumber: {
    fontWeight: '600',
    marginBottom: 0,
  },
  statLabel: {
    fontSize: fontSizes.xs,
    marginTop: 2,
  },
  statDivider: {
    width: 1,
    height: 24,
    backgroundColor: colors.divider + '55',
  },
  actionButtons: {
    marginTop: spacing.sm,
  },
  buttonRow: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: spacing.sm,
  },
  buttonRowWide: {
    justifyContent: 'center',
    gap: spacing.md,
  },
  editButton: {
    flex: 1,
  },
  followButton: {
    flex: 1,
  },
  followButtonWide: {
    flex: 0,
    minWidth: 120,
  },
  messageButton: {
    width: 44,
    height: 44,
    borderRadius: borderRadius.md,
    backgroundColor: colors.primary.light + '20',
    justifyContent: 'center',
    alignItems: 'center',
  },
  moreButton: {
    width: 44,
    height: 44,
    borderRadius: borderRadius.md,
    backgroundColor: colors.background.default,
    justifyContent: 'center',
    alignItems: 'center',
  },
  settingsButtonOnly: {
    alignSelf: 'center',
    padding: spacing.sm,
  },
  });
}

// 使用 React.memo 避免不必要的重新渲染
const MemoizedUserProfileHeader = React.memo(UserProfileHeader);

export default MemoizedUserProfileHeader;
