/**
 * UserProfileHeader 用户资料头部组件 - Twitter/X 风格
 * 显示用户封面、头像、昵称、简介、关注/粉丝数
 * 采用 Twitter/X 扁平化设计，左对齐布局
 * 支持互关状态显示
 */

import React, { useMemo, useState, useRef, useCallback } from 'react';
import {
  View,
  Image,
  TouchableOpacity,
  StyleSheet,
  Modal,
  Pressable,
  Dimensions,
} from 'react-native';
import { MaterialCommunityIcons } from '@expo/vector-icons';
import { spacing, fontSizes, borderRadius, useAppColors, type AppColors } from '../../theme';
import { User, UserIdentity, VerificationStatus } from '../../types';
import Text from '../common/Text';
import Avatar from '../common/Avatar';
import { ImageGallery } from '../common';
import type { GalleryImageItem } from '../common';
import { useResponsive } from '../../hooks';

interface UserProfileHeaderProps {
  user: User;
  isCurrentUser?: boolean;
  isBlocked?: boolean;
  onFollow: () => void;
  onSettings?: () => void;
  onEditProfile?: () => void;
  onMessage?: () => void;
  onBlock?: () => void;
  onFollowingPress?: () => void;
  onFollowersPress?: () => void;
  onAvatarPress?: () => void;
}

const UserProfileHeader: React.FC<UserProfileHeaderProps> = ({
  user,
  isCurrentUser = false,
  isBlocked = false,
  onFollow,
  onSettings,
  onEditProfile,
  onMessage,
  onBlock,
  onFollowingPress,
  onFollowersPress,
  onAvatarPress,
}) => {
  const colors = useAppColors();
  const styles = useMemo(() => createUserProfileHeaderStyles(colors), [colors]);
  const { isWideScreen, isDesktop, width } = useResponsive();
  const [menuVisible, setMenuVisible] = useState(false);
  const [menuPosition, setMenuPosition] = useState({ x: 0, y: 0 });
  const moreButtonRef = useRef<View>(null);
  const [galleryVisible, setGalleryVisible] = useState(false);
  const [galleryImages, setGalleryImages] = useState<GalleryImageItem[]>([]);
  const [galleryIndex, setGalleryIndex] = useState(0);

  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 => user.posts_count ?? 0;
  const getFollowersCount = (): number => user.followers_count ?? 0;
  const getFollowingCount = (): number => user.following_count ?? 0;
  const getIsFollowing = (): boolean => user.is_following ?? false;
  const getIsFollowingMe = (): boolean => user.is_following_me ?? false;

  const getButtonConfig = (): { title: string; variant: 'primary' | 'outline' | 'ghost'; 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 ? 280 : isWideScreen ? 240 : (width * 10) / 16;
  const avatarSize = isDesktop ? 140 : isWideScreen ? 120 : 88;

  const handleMorePress = useCallback(() => {
    moreButtonRef.current?.measure((_fx, _fy, _w, h, px, py) => {
      const screenWidth = Dimensions.get('window').width;
      const menuWidth = 180;
      let x = px + _w / 2 - menuWidth / 2;
      if (x + menuWidth > screenWidth - 12) {
        x = screenWidth - menuWidth - 12;
      }
      if (x < 12) x = 12;
      setMenuPosition({ x, y: py + h + 4 });
      setMenuVisible(true);
    });
  }, []);

  const handleBlockPress = useCallback(() => {
    setMenuVisible(false);
    onBlock?.();
  }, [onBlock]);

  const openImageGallery = useCallback((images: GalleryImageItem[], index: number = 0) => {
    setGalleryImages(images);
    setGalleryIndex(index);
    setGalleryVisible(true);
  }, []);

  const handleCoverPress = useCallback(() => {
    if (user.cover_url) {
      openImageGallery([{ id: 'cover', url: user.cover_url }], 0);
    }
  }, [user.cover_url, openImageGallery]);

  const handleAvatarPressPreview = useCallback(() => {
    if (user.avatar) {
      openImageGallery([{ id: 'avatar', url: user.avatar }], 0);
    }
  }, [user.avatar, openImageGallery]);

  const renderStatLink = (count: number, label: string, onPress?: () => void) => {
    if (!onPress) {
      return (
        <View style={styles.statItem}>
          <Text style={styles.statNumber}>{formatCount(count)}</Text>
          <Text style={styles.statLabel}>{label}</Text>
        </View>
      );
    }
    return (
      <TouchableOpacity style={styles.statItem} onPress={onPress} activeOpacity={0.7}>
        <Text style={styles.statNumber}>{formatCount(count)}</Text>
        <Text style={styles.statLabel}>{label}</Text>
      </TouchableOpacity>
    );
  };

  const renderDropdownMenu = () => (
    <Modal
      visible={menuVisible}
      transparent
      animationType="fade"
      onRequestClose={() => setMenuVisible(false)}
    >
      <Pressable style={styles.menuBackdrop} onPress={() => setMenuVisible(false)}>
        <View
          style={[
            styles.menuContainer,
            { left: menuPosition.x, top: menuPosition.y },
          ]}
        >
          <TouchableOpacity
            style={styles.menuItem}
            onPress={handleBlockPress}
            activeOpacity={0.7}
          >
            <MaterialCommunityIcons
              name={isBlocked ? 'account-check-outline' : 'account-off-outline'}
              size={18}
              color={isBlocked ? colors.success.main : colors.error.main}
            />
            <Text
              style={[
                styles.menuItemText,
                { color: isBlocked ? colors.success.main : colors.error.main },
              ]}
            >
              {isBlocked ? '取消拉黑' : '拉黑用户'}
            </Text>
          </TouchableOpacity>
        </View>
      </Pressable>
    </Modal>
  );

  return (
    <View style={styles.container}>
      {/* 全宽封面背景 */}
      <View style={[styles.coverContainer, { height: coverHeight }]}>
        <TouchableOpacity
          style={styles.coverTouchable}
          onPress={handleCoverPress}
          activeOpacity={0.9}
          disabled={!user.cover_url}
        >
          {user.cover_url ? (
            <Image
              source={{ uri: user.cover_url }}
              style={styles.coverImage}
              resizeMode="cover"
            />
          ) : (
            <View style={[styles.coverFallback, { backgroundColor: colors.primary.main }]}>
              <MaterialCommunityIcons name="image-outline" size={48} color="rgba(255,255,255,0.4)" />
            </View>
          )}
        </TouchableOpacity>

        {/* 顶部导航栏按钮 */}
        <View style={styles.topBar}>
          {isCurrentUser && onSettings && (
            <TouchableOpacity style={styles.iconButton} onPress={onSettings}>
              <MaterialCommunityIcons name="cog-outline" size={20} color={colors.text.primary} />
            </TouchableOpacity>
          )}
        </View>
      </View>

      {/* 用户信息区 */}
      <View style={styles.infoSection}>
        {/* 头像与操作按钮行 */}
        <View style={styles.avatarActionRow}>
          <View style={[styles.avatarWrapper, { marginTop: -avatarSize / 2 }]}>
            <TouchableOpacity
              style={[styles.avatarContainer, { width: avatarSize, height: avatarSize }]}
              onPress={isCurrentUser && onAvatarPress ? onAvatarPress : handleAvatarPressPreview}
              activeOpacity={0.9}
              disabled={isCurrentUser ? !onAvatarPress : !user.avatar}
            >
              <Avatar
                source={user.avatar}
                size={avatarSize - 6}
                name={user.nickname}
              />
              {isCurrentUser && onAvatarPress && (
                <View style={styles.editAvatarButton} pointerEvents="none">
                  <MaterialCommunityIcons name="camera" size={14} color={colors.text.inverse} />
                </View>
              )}
            </TouchableOpacity>
          </View>

          <View style={styles.actionButtons}>
            {isCurrentUser ? (
              <TouchableOpacity style={styles.editProfileButton} onPress={onEditProfile} activeOpacity={0.8}>
                <Text style={styles.editProfileText}>编辑资料</Text>
              </TouchableOpacity>
            ) : (
              <View style={styles.buttonRow}>
                <View ref={moreButtonRef} collapsable={false}>
                  <TouchableOpacity style={styles.iconButtonSmall} onPress={handleMorePress}>
                    <MaterialCommunityIcons name="dots-horizontal" size={20} color={colors.text.primary} />
                  </TouchableOpacity>
                </View>
                <TouchableOpacity style={styles.iconButtonSmall} onPress={onMessage}>
                  <MaterialCommunityIcons name="email-outline" size={18} color={colors.text.primary} />
                </TouchableOpacity>
                <TouchableOpacity
                  style={[
                    styles.followBtn,
                    getButtonConfig().variant === 'outline' && styles.followBtnOutline,
                    getButtonConfig().variant === 'primary' && styles.followBtnPrimary,
                  ]}
                  onPress={onFollow}
                  activeOpacity={0.8}
                >
                  <Text
                    style={[
                      styles.followBtnText,
                      ...(getButtonConfig().variant === 'primary' ? [styles.followBtnTextPrimary] : []),
                    ]}
                  >
                    {getButtonConfig().title}
                  </Text>
                </TouchableOpacity>
              </View>
            )}
          </View>
        </View>

        {/* 用户名 */}
        <View style={styles.nameSection}>
          <View style={styles.nicknameRow}>
            <Text style={styles.nickname}>{user.nickname}</Text>
            <VerificationBadge identity={user.identity} verificationStatus={user.verification_status} />
          </View>
          <Text style={styles.username}>@{user.username}</Text>
        </View>

        {/* 简介 */}
        {user.bio ? (
          <Text style={styles.bio}>{user.bio}</Text>
        ) : null}

        {/* 元信息 */}
        <View style={styles.metaInfo}>
          {user.location?.trim() ? (
            <View style={styles.metaItem}>
              <MaterialCommunityIcons name="map-marker-outline" size={14} color={colors.text.hint} />
              <Text style={styles.metaText}>{user.location}</Text>
            </View>
          ) : null}
          {user.website?.trim() ? (
            <View style={styles.metaItem}>
              <MaterialCommunityIcons name="link-variant" size={14} color={colors.info.main} />
              <Text style={[styles.metaText, styles.metaLink]}>{user.website.replace(/^https?:\/\//, '')}</Text>
            </View>
          ) : null}
          <View style={styles.metaItem}>
            <MaterialCommunityIcons name="calendar-outline" size={14} color={colors.text.hint} />
            <Text style={styles.metaText}>
              {(() => {
                const d = new Date(user.created_at || Date.now());
                if (Number.isNaN(d.getTime())) return '加入于 未知时间';
                return `加入于 ${d.getFullYear()}年${d.getMonth() + 1}月`;
              })()}
            </Text>
          </View>
        </View>

        {/* 统计数据 - Twitter 风格内联 */}
        <View style={styles.statsRow}>
          {renderStatLink(getFollowingCount(), '正在关注', onFollowingPress)}
          {renderStatLink(getFollowersCount(), '关注者', onFollowersPress)}
        </View>
      </View>

      {renderDropdownMenu()}

      {/* 图片预览 */}
      <ImageGallery
        visible={galleryVisible}
        images={galleryImages}
        initialIndex={galleryIndex}
        onClose={() => setGalleryVisible(false)}
        enableSave
      />
    </View>
  );
};

function createUserProfileHeaderStyles(colors: AppColors) {
  return StyleSheet.create({
    container: {
      backgroundColor: colors.background.paper,
    },
    // 封面
    coverContainer: {
      position: 'relative',
      backgroundColor: colors.background.default,
    },
    coverTouchable: {
      width: '100%',
      height: '100%',
    },
    coverImage: {
      width: '100%',
      height: '100%',
    },
    coverFallback: {
      width: '100%',
      height: '100%',
      justifyContent: 'center',
      alignItems: 'center',
    },
    // 顶部栏
    topBar: {
      position: 'absolute',
      top: 0,
      left: 0,
      right: 0,
      flexDirection: 'row',
      justifyContent: 'flex-end',
      paddingHorizontal: spacing.md,
      paddingTop: spacing.md,
    },
    iconButton: {
      width: 36,
      height: 36,
      borderRadius: borderRadius.full,
      backgroundColor: 'rgba(255, 255, 255, 0.85)',
      justifyContent: 'center',
      alignItems: 'center',
      ...shadows.sm,
    },
    // 信息区
    infoSection: {
      paddingHorizontal: spacing.lg,
      paddingTop: spacing.sm,
      paddingBottom: spacing.lg,
    },
    avatarActionRow: {
      flexDirection: 'row',
      justifyContent: 'space-between',
      alignItems: 'flex-end',
      marginBottom: spacing.sm,
    },
    avatarWrapper: {
      // 负边距在 inline style 中计算
    },
    avatarContainer: {
      borderRadius: borderRadius.full,
      backgroundColor: colors.background.paper,
      padding: 3,
      justifyContent: 'center',
      alignItems: 'center',
    },
    editAvatarButton: {
      position: 'absolute',
      bottom: 4,
      right: 4,
      width: 28,
      height: 28,
      borderRadius: 14,
      backgroundColor: colors.primary.main,
      justifyContent: 'center',
      alignItems: 'center',
      borderWidth: 2,
      borderColor: colors.background.paper,
    },
    // 操作按钮
    actionButtons: {
      flexDirection: 'row',
      alignItems: 'center',
      marginBottom: spacing.sm,
    },
    buttonRow: {
      flexDirection: 'row',
      alignItems: 'center',
      gap: spacing.sm,
    },
    iconButtonSmall: {
      width: 38,
      height: 38,
      borderRadius: borderRadius.full,
      borderWidth: 1,
      borderColor: colors.divider,
      justifyContent: 'center',
      alignItems: 'center',
    },
    editProfileButton: {
      paddingHorizontal: spacing.lg,
      paddingVertical: spacing.sm,
      borderRadius: borderRadius.full,
      borderWidth: 1,
      borderColor: colors.divider,
      backgroundColor: colors.background.paper,
    },
    editProfileText: {
      fontSize: fontSizes.md,
      fontWeight: '600',
      color: colors.text.primary,
    },
    followBtn: {
      paddingHorizontal: spacing.lg,
      paddingVertical: spacing.sm,
      borderRadius: borderRadius.full,
      minWidth: 80,
      alignItems: 'center',
      justifyContent: 'center',
    },
    followBtnPrimary: {
      backgroundColor: colors.text.primary,
    },
    followBtnOutline: {
      backgroundColor: colors.background.paper,
      borderWidth: 1,
      borderColor: colors.divider,
    },
    followBtnText: {
      fontSize: fontSizes.md,
      fontWeight: '700',
      color: colors.text.primary,
    },
    followBtnTextPrimary: {
      color: colors.background.paper,
    },
    // 名字
    nameSection: {
      marginBottom: spacing.sm,
    },
    nicknameRow: {
      flexDirection: 'row',
      alignItems: 'center',
      gap: spacing.xs,
      marginBottom: 2,
    },
    nickname: {
      fontSize: fontSizes['2xl'],
      fontWeight: '800',
      color: colors.text.primary,
    },
    username: {
      fontSize: fontSizes.md,
      color: colors.text.hint,
    },
    // 简介
    bio: {
      fontSize: fontSizes.md,
      color: colors.text.primary,
      lineHeight: 20,
      marginBottom: spacing.sm,
    },
    // 元信息
    metaInfo: {
      flexDirection: 'row',
      flexWrap: 'wrap',
      gap: spacing.md,
      marginBottom: spacing.sm,
    },
    metaItem: {
      flexDirection: 'row',
      alignItems: 'center',
      gap: 4,
    },
    metaText: {
      fontSize: fontSizes.sm,
      color: colors.text.hint,
    },
    metaLink: {
      color: colors.info.main,
    },
    // 统计
    statsRow: {
      flexDirection: 'row',
      gap: spacing.lg,
      marginTop: spacing.xs,
    },
    statItem: {
      flexDirection: 'row',
      alignItems: 'center',
      gap: 4,
    },
    statNumber: {
      fontSize: fontSizes.md,
      fontWeight: '700',
      color: colors.text.primary,
    },
    statLabel: {
      fontSize: fontSizes.sm,
      color: colors.text.hint,
    },
    // 下拉菜单
    menuBackdrop: {
      flex: 1,
      backgroundColor: 'transparent',
    },
    menuContainer: {
      position: 'absolute',
      minWidth: 160,
      backgroundColor: colors.background.paper,
      borderRadius: borderRadius.lg,
      ...shadows.lg,
      borderWidth: StyleSheet.hairlineWidth,
      borderColor: colors.divider,
      overflow: 'hidden',
    },
    menuItem: {
      flexDirection: 'row',
      alignItems: 'center',
      gap: spacing.sm,
      paddingVertical: spacing.md,
      paddingHorizontal: spacing.lg,
    },
    menuItemText: {
      fontSize: fontSizes.md,
      fontWeight: '600',
    },
  });
}

import { shadows } from '../../theme';

// ==================== VerificationBadge ====================

interface VerificationBadgeProps {
  identity?: UserIdentity;
  verificationStatus?: VerificationStatus;
}

const IDENTITY_CONFIG: Record<
  UserIdentity,
  { label: string; color: string; bg: string }
> = {
  general: { label: '未认证', color: '#9CA3AF', bg: '#F3F4F6' },
  student: { label: '学生认证', color: '#10B981', bg: '#D1FAE5' },
  teacher: { label: '教师认证', color: '#3B82F6', bg: '#DBEAFE' },
  staff: { label: '官方', color: '#D4AF37', bg: '#FFF8DC' },
  alumni: { label: '校友认证', color: '#F59E0B', bg: '#FEF3C7' },
  external: { label: '未认证', color: '#9CA3AF', bg: '#F3F4F6' },
};

const VerificationBadge: React.FC<VerificationBadgeProps> = ({
  identity,
  verificationStatus,
}) => {
  const colors = useAppColors();

  // 默认值：未认证状态
  const effectiveIdentity = identity || 'general';
  const effectiveStatus = verificationStatus || 'none';

  const isApproved = effectiveStatus === 'approved';
  // none 表示未认证，统一用 general 的未认证样式
  const displayIdentity = isApproved ? effectiveIdentity : 'general';
  const config = IDENTITY_CONFIG[displayIdentity] || IDENTITY_CONFIG.general;

  return (
    <View style={{ width: 22, height: 22, justifyContent: 'center', alignItems: 'center' }}>
      {isApproved ? (
        <MaterialCommunityIcons name="check-decagram" size={22} color={config.color} />
      ) : (
        <>
          <MaterialCommunityIcons name="decagram" size={22} color="#9CA3AF" />
          <MaterialCommunityIcons name="decagram-outline" size={22} color="#9CA3AF" style={{ position: 'absolute' }} />
          <Text style={{ position: 'absolute', fontSize: 11, fontWeight: '800', color: '#FFFFFF', marginTop: 1 }}>?</Text>
        </>
      )}
    </View>
  );
};

const MemoizedUserProfileHeader = React.memo(UserProfileHeader);
export default MemoizedUserProfileHeader;
