/**
 * 用户主页共享逻辑 Hook
 * 提取 ProfileScreen 和 UserScreen 的共同逻辑
 */

import { useState, useEffect, useCallback, useMemo } from 'react';
import { StyleSheet } from 'react-native';
import { useRouter } from 'expo-router';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { spacing, type AppColors } from '../../theme';
import { Post, User } from '../../types';
import { useUserStore } from '../../stores';
import { useCurrentUser } from '../../stores/authStore';
import { postService, authService, messageService } from '../../services';
import { userManager } from '../../stores/userManager';
import * as hrefs from '../../navigation/hrefs';
import { PostCardAction } from '../../components/business/PostCard';

export type ProfileMode = 'self' | 'other';

export interface UseUserProfileOptions {
  mode: ProfileMode;
  userId?: string; // 仅 other 模式需要
  isDesktop?: boolean;
  isTablet?: boolean;
}

export interface UseUserProfileReturn {
  // 用户数据
  user: User | null;
  posts: Post[];
  favorites: Post[];
  loading: boolean;
  refreshing: boolean;
  isBlocked: boolean;
  
  // Tab 相关
  activeTab: number;
  setActiveTab: (tab: number) => void;
  
  // 布局相关
  scrollBottomInset: number;
  
  // 操作
  onRefresh: () => Promise<void>;
  handleFollow: () => void;
  handlePostPress: (postId: string, scrollToComments?: boolean) => void;
  handleUserPress: (postUserId: string) => void;
  handleDeletePost: (postId: string) => Promise<void>;
  handleFollowingPress: () => void;
  handleFollowersPress: () => void;
  handlePostAction: (post: Post, action: PostCardAction) => void;
  
  // 仅 other 模式
  handleMessage?: () => Promise<void>;
  handleMore?: () => void;
  
  // 仅 self 模式
  handleSettings?: () => void;
  handleEditProfile?: () => void;
  
  // 判断
  isCurrentUser: boolean;
  currentUser: User | null;
}

export const useUserProfile = (options: UseUserProfileOptions): UseUserProfileReturn => {
  const { mode, userId, isDesktop = false } = options;

  const insets = useSafeAreaInsets();
  const router = useRouter();
  
  const { followUser, unfollowUser, posts: storePosts } = useUserStore();
  const currentUser = useCurrentUser();
  
  // 状态
  const [user, setUser] = useState<User | null>(null);
  const [posts, setPosts] = useState<Post[]>([]);
  const [favorites, setFavorites] = useState<Post[]>([]);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [activeTab, setActiveTab] = useState(0);
  const [isBlocked, setIsBlocked] = useState(false);
  
  // 获取其他用户数据（other 模式）
  const loadOtherUserData = useCallback(async (forceRefresh = false) => {
    if (mode !== 'other' || !userId) {
      setLoading(false);
      return null;
    }
    
    try {
      const userData = await userManager.getUserById(userId, forceRefresh);
      setUser(userData || null);
      const blockStatus = await authService.getBlockStatus(userId);
      setIsBlocked(blockStatus);
      
      const response = await postService.getUserPosts(userId);
      setPosts(response.list);
      
      return userData;
    } catch (error) {
      console.error('加载用户数据失败:', error);
      return null;
    } finally {
      setLoading(false);
    }
  }, [mode, userId]);
  
  // 加载当前用户的帖子（self 模式）
  const loadSelfPosts = useCallback(async () => {
    if (mode !== 'self' || !currentUser) {
      setLoading(false);
      return;
    }
    
    try {
      const response = await postService.getUserPosts(currentUser.id);
      setPosts(response.list);
    } catch (error) {
      console.error('获取用户帖子失败:', error);
    }
    setLoading(false);
  }, [mode, currentUser]);
  
  // 加载收藏
  const loadFavorites = useCallback(async () => {
    const targetUserId = mode === 'self' ? currentUser?.id : userId;
    if (!targetUserId) return;
    
    try {
      const response = await postService.getUserFavorites(targetUserId);
      setFavorites(response.list);
    } catch (error) {
      console.error('获取用户收藏失败:', error);
    }
  }, [mode, currentUser?.id, userId]);
  
  // 初始化加载
  useEffect(() => {
    if (mode === 'self') {
      loadSelfPosts();
    } else {
      loadOtherUserData(true);
    }
  }, [mode, loadSelfPosts, loadOtherUserData]);
  
  // Tab 切换加载收藏
  useEffect(() => {
    if (activeTab === 1 && favorites.length === 0) {
      loadFavorites();
    }
  }, [activeTab, favorites.length, loadFavorites]);
  
  // 同步 store 中的帖子状态
  useEffect(() => {
    if (posts.length > 0) {
      let hasChanges = false;
      const updatedPosts = posts.map(localPost => {
        const storePost = storePosts.find(sp => sp.id === localPost.id);
        if (storePost && (
          storePost.is_liked !== localPost.is_liked ||
          storePost.is_favorited !== localPost.is_favorited ||
          storePost.likes_count !== localPost.likes_count ||
          storePost.favorites_count !== localPost.favorites_count
        )) {
          hasChanges = true;
          return {
            ...localPost,
            is_liked: storePost.is_liked,
            is_favorited: storePost.is_favorited,
            likes_count: storePost.likes_count,
            favorites_count: storePost.favorites_count,
          };
        }
        return localPost;
      });
      
      if (hasChanges) {
        setPosts(updatedPosts);
      }
    }
    
    if (favorites.length > 0) {
      let hasChanges = false;
      const updatedFavorites = favorites.map(localPost => {
        const storePost = storePosts.find(sp => sp.id === localPost.id);
        if (storePost && (
          storePost.is_liked !== localPost.is_liked ||
          storePost.is_favorited !== localPost.is_favorited ||
          storePost.likes_count !== localPost.likes_count ||
          storePost.favorites_count !== localPost.favorites_count
        )) {
          hasChanges = true;
          return {
            ...localPost,
            is_liked: storePost.is_liked,
            is_favorited: storePost.is_favorited,
            likes_count: storePost.likes_count,
            favorites_count: storePost.favorites_count,
          };
        }
        return localPost;
      });
      
      if (hasChanges) {
        setFavorites(updatedFavorites);
      }
    }
  }, [storePosts]);
  
  // 下拉刷新
  const onRefresh = useCallback(async () => {
    setRefreshing(true);
    try {
      if (mode === 'self') {
        const { useAuthStore } = await import('../../stores');
        const { fetchCurrentUser } = useAuthStore.getState();
        await fetchCurrentUser();
        await loadSelfPosts();
      } else {
        await loadOtherUserData(true);
      }
    } catch (error) {
      console.error('刷新失败:', error);
    } finally {
      setRefreshing(false);
    }
  }, [mode, loadSelfPosts, loadOtherUserData]);
  
  // 关注/取消关注
  const handleFollow = useCallback(() => {
    const targetUser = mode === 'self' ? currentUser : user;
    if (!targetUser) return;
    
    if (targetUser.is_following) {
      unfollowUser(targetUser.id);
      if (mode === 'other') {
        setUser({ ...targetUser, is_following: false, followers_count: targetUser.followers_count - 1 });
      }
    } else {
      followUser(targetUser.id);
      if (mode === 'other') {
        setUser({ ...targetUser, is_following: true, followers_count: targetUser.followers_count + 1 });
      }
    }
  }, [mode, currentUser, user, unfollowUser, followUser]);
  
  // 跳转到关注列表
  const handleFollowingPress = useCallback(() => {
    const targetUserId = mode === 'self' ? currentUser?.id : userId;
    if (targetUserId) {
      router.push(hrefs.hrefFollowList(targetUserId, 'following'));
    }
  }, [mode, currentUser?.id, userId, router]);

  // 跳转到粉丝列表
  const handleFollowersPress = useCallback(() => {
    const targetUserId = mode === 'self' ? currentUser?.id : userId;
    if (targetUserId) {
      router.push(hrefs.hrefFollowList(targetUserId, 'followers'));
    }
  }, [mode, currentUser?.id, userId, router]);

  // 跳转到帖子详情
  const handlePostPress = useCallback(
    (postId: string, scrollToComments: boolean = false) => {
      router.push(hrefs.hrefPostDetail(postId, scrollToComments));
    },
    [router]
  );

  // 跳转到用户主页
  const handleUserPress = useCallback(
    (postUserId: string) => {
      if (mode === 'self') {
        return;
      }
      if (postUserId !== userId) {
        router.push(hrefs.hrefUserProfile(postUserId));
      }
    },
    [mode, userId, router]
  );
  
  // 删除帖子
  const handleDeletePost = useCallback(async (postId: string) => {
    try {
      const success = await postService.deletePost(postId);
      if (success) {
        setPosts(prev => prev.filter(p => p.id !== postId));
        setFavorites(prev => prev.filter(p => p.id !== postId));
      } else {
        console.error('删除帖子失败');
      }
    } catch (error) {
      console.error('删除帖子失败:', error);
      throw error;
    }
  }, []);
  
  // 统一的 PostCard Action 处理
  const handlePostAction = useCallback((post: Post, action: PostCardAction) => {
    switch (action.type) {
      case 'press':
        handlePostPress(post.id);
        break;
      case 'userPress':
        if (post.author) {
          handleUserPress(post.author.id);
        }
        break;
      case 'like':
      case 'unlike':
        post.is_liked ? postService.unlikePost(post.id) : postService.likePost(post.id);
        break;
      case 'comment':
        handlePostPress(post.id, true);
        break;
      case 'bookmark':
      case 'unbookmark':
        post.is_favorited ? postService.unfavoritePost(post.id) : postService.favoritePost(post.id);
        break;
      case 'share':
        break;
      case 'delete':
        handleDeletePost(post.id);
        break;
    }
  }, [handlePostPress, handleUserPress, handleDeletePost]);
  
  // 发消息（仅 other 模式）
  const handleMessage = useCallback(async () => {
    if (!user) return;
    
    try {
      const conversation = await messageService.createConversation(user.id);
      if (conversation) {
        router.push(
          hrefs.hrefChat({
            conversationId: conversation.id.toString(),
            userId: user.id,
          }) as any
        );
      }
    } catch (error) {
      console.error('创建会话失败:', error);
    }
  }, [user, router]);
  
  // 更多操作（仅 other 模式）
  const handleMore = useCallback(() => {
    if (!user) return;
    
    const { Alert } = require('react-native');
    Alert.alert(
      '更多操作',
      undefined,
      [
        { text: '取消', style: 'cancel' },
        {
          text: isBlocked ? '取消拉黑' : '拉黑用户',
          style: 'destructive',
          onPress: () => {
            Alert.alert(
              isBlocked ? '确认取消拉黑' : '确认拉黑',
              isBlocked
                ? '取消拉黑后，对方可以重新与你建立关系。'
                : '拉黑后，对方将无法给你发送私聊消息，且会互相移除关注关系。',
              [
                { text: '取消', style: 'cancel' },
                {
                  text: '确定',
                  style: 'destructive',
                  onPress: async () => {
                    const ok = isBlocked
                      ? await authService.unblockUser(user.id)
                      : await authService.blockUser(user.id);
                    if (!ok) {
                      Alert.alert('失败', isBlocked ? '取消拉黑失败，请稍后重试' : '拉黑失败，请稍后重试');
                      return;
                    }
                    setUser(prev =>
                      prev
                        ? { ...prev, is_following: false, is_following_me: false }
                        : prev
                    );
                    setIsBlocked(!isBlocked);
                    Alert.alert('成功', isBlocked ? '已取消拉黑' : '已拉黑该用户');
                  },
                },
              ]
            );
          },
        },
      ]
    );
  }, [user, isBlocked]);
  
  // 设置页跳转（仅 self 模式）
  const handleSettings = useCallback(() => {
    router.push(hrefs.hrefProfileSettings());
  }, [router]);

  // 编辑资料页跳转（仅 self 模式）
  const handleEditProfile = useCallback(() => {
    router.push(hrefs.hrefProfileEdit());
  }, [router]);
  
  // 计算滚动底部间距
  const scrollBottomInset = useMemo(() => {
    if (isDesktop) return spacing.lg;
    const FLOATING_TAB_BAR_HEIGHT = 64 + 24;
    return FLOATING_TAB_BAR_HEIGHT + insets.bottom + spacing.md;
  }, [isDesktop, insets.bottom]);
  
  // 获取显示的用户
  const displayUser = mode === 'self' ? currentUser : user;
  
  return {
    user: displayUser,
    posts,
    favorites,
    loading,
    refreshing,
    isBlocked,
    activeTab,
    setActiveTab,
    scrollBottomInset,
    onRefresh,
    handleFollow,
    handlePostPress,
    handleUserPress,
    handleDeletePost,
    handleFollowingPress,
    handleFollowersPress,
    handlePostAction,
    handleMessage: mode === 'other' ? handleMessage : undefined,
    handleMore: mode === 'other' ? handleMore : undefined,
    handleSettings: mode === 'self' ? handleSettings : undefined,
    handleEditProfile: mode === 'self' ? handleEditProfile : undefined,
    isCurrentUser: mode === 'self',
    currentUser,
  };
};

export function createSharedProfileStyles(colors: AppColors) {
  return StyleSheet.create({
    container: {
      flex: 1,
      backgroundColor: colors.background.default,
    },
    scrollContent: {
      flexGrow: 1,
    },
    desktopContainer: {
      flex: 1,
      flexDirection: 'row',
      gap: spacing.lg,
      padding: spacing.lg,
    },
    desktopSidebar: {
      width: 380,
      flexShrink: 0,
    },
    desktopContent: {
      flex: 1,
      minWidth: 0,
    },
    desktopScrollContent: {
      flexGrow: 1,
    },
    tabBarContainer: {
      marginTop: spacing.xs,
      marginBottom: 2,
    },
    contentContainer: {
      flex: 1,
      minHeight: 350,
      paddingTop: spacing.xs,
    },
    postsContainer: {
      paddingHorizontal: spacing.md,
      paddingTop: spacing.sm,
    },
    postWrapper: {
      marginBottom: spacing.md,
      backgroundColor: colors.background.paper,
      borderRadius: 16,
      overflow: 'hidden',
      shadowColor: colors.chat.shadow,
      shadowOffset: { width: 0, height: 2 },
      shadowOpacity: 0.06,
      shadowRadius: 8,
      elevation: 2,
    },
    lastPost: {
      marginBottom: spacing['2xl'],
    },
  });
}

// Tab 配置
export const TABS = ['帖子', '收藏'];
export const TAB_ICONS = ['file-document-outline', 'bookmark-outline'];
