
import React from 'react';
import { User, Post } from '../types';
import { ArrowLeftIcon } from './icons/ArrowLeftIcon';
import { PencilIcon } from './icons/PencilIcon';
import { BanIcon } from './icons/BanIcon';

interface ProfileProps {
  profileUser: User;
  currentUser: User;
  posts: Post[];
  users: User[];
  onFollowToggle: (targetUserId: string) => void;
  onOpenPostDetail: (post: Post) => void;
  onOpenEditProfile: () => void;
  onNavigate: (view: 'feed' | 'profile' | 'admin', userId: string) => void;
  onApproveSuggestion: (postId: string, tagName: string) => void;
  onOpenUserListModal: (title: string, userIds: string[]) => void;
  onShowTagVoters: (tagName: string) => void;
  onClashVote: (postId: string, tagToVoteFor: string) => void;
  onShareRequest: (post: Post) => void;
  onReportRequest: (postId: string) => void;
}

const TagCloud: React.FC<{ posts: Post[]; onShowTagVoters: (tagName: string) => void; }> = ({ posts, onShowTagVoters }) => {
    const tagCounts = posts.flatMap(p => p.tags).reduce((acc: Record<string, number>, tag) => {
        acc[tag.name] = (acc[tag.name] || 0) + tag.count;
        return acc;
    }, {});

    // FIX: Cast the result of Object.entries to `[string, number][]` to resolve type inference issues.
    // This ensures that `count` variables are treated as numbers, fixing arithmetic and function call errors
    // in the sort method, `Math.min`/`Math.max` calls, and the `calculateFontSize` function.
    // The sort logic was also clarified for better readability.
    const topTags = (Object.entries(tagCounts) as [string, number][])
        .sort(([, countA], [, countB]) => countB - countA)
        .slice(0, 15);

    if (topTags.length === 0) {
        return (
             <div className="text-sm text-muted-foreground text-center py-8 bg-muted rounded-lg">
                No tags yet. Start posting to see your analytics!
             </div>
        );
    }
    
    const counts = topTags.map(([, count]) => count);
    const minCount = Math.min(...counts);
    const maxCount = Math.max(...counts);

    const calculateFontSize = (count: number) => {
        if (maxCount === minCount) return '1rem'; // 16px
        const minFontSize = 14; // in pixels
        const maxFontSize = 36; // in pixels
        const size = minFontSize + ((count - minCount) / (maxCount - minCount)) * (maxFontSize - minFontSize);
        return `${size}px`;
    };

    return (
        <div className="flex flex-wrap items-center justify-center gap-x-6 gap-y-3 p-6 bg-muted rounded-lg">
            {topTags.map(([name, count]) => (
                <button
                    key={name}
                    onClick={() => onShowTagVoters(name)}
                    className="font-bold text-foreground hover:text-primary hover:underline transition-transform hover:scale-105"
                    style={{ fontSize: calculateFontSize(count), lineHeight: '1.2' }}
                    title={`${count} clicks`}
                >
                    {name}
                </button>
            ))}
        </div>
    );
};

const PendingSuggestions: React.FC<{ 
    posts: Post[]; 
    users: User[];
    onApproveSuggestion: (postId: string, tagName: string) => void;
    onNavigate: (view: 'profile', userId: string) => void;
    onOpenPostDetail: (post: Post) => void;
}> = ({ posts, users, onApproveSuggestion, onNavigate, onOpenPostDetail }) => {

    const allPendingSuggestions = posts.flatMap(post => 
        post.suggestions
            .filter(s => s.status === 'pending')
            .map(s => ({ ...s, post }))
    );

    if (allPendingSuggestions.length === 0) {
        return null;
    }

    const getUserById = (userId: string) => users.find(u => u.id === userId);

    return (
        <div className="mt-8">
            <h3 className="text-2xl font-bold mb-4">Pending Tag Suggestions</h3>
            <div className="bg-background border border-accent rounded-lg p-4 space-y-4">
                {allPendingSuggestions.map(({ post, tagName, userId }) => {
                    const suggester = getUserById(userId);
                    return (
                        <div key={`${post.id}-${tagName}-${userId}`} className="flex items-center justify-between gap-4 p-2 rounded-md hover:bg-muted">
                            <div className="flex items-center gap-4">
                                <img 
                                    src={post.mediaType === 'video' ? post.posterUrl || post.mediaUrl : post.mediaUrl} 
                                    alt={post.caption} 
                                    className="w-12 h-12 rounded-md object-cover cursor-pointer"
                                    onClick={() => onOpenPostDetail(post)}
                                />
                                <div className="text-sm">
                                    <p>
                                        <strong>{tagName}</strong> suggested by <span className="font-semibold cursor-pointer hover:underline" onClick={() => onNavigate('profile', userId)}>{suggester?.username || 'a user'}</span>
                                    </p>
                                    <p className="text-muted-foreground truncate max-w-xs">on post: "{post.caption}"</p>
                                </div>
                            </div>
                            <button 
                                onClick={() => onApproveSuggestion(post.id, tagName)}
                                className="bg-primary text-primary-foreground px-3 py-1 rounded-md text-xs font-semibold hover:opacity-80 transition-opacity whitespace-nowrap"
                            >
                                Approve
                            </button>
                        </div>
                    );
                })}
            </div>
        </div>
    );
};


const Profile: React.FC<ProfileProps> = (props) => {
  const { profileUser, currentUser, posts, users, onFollowToggle, onOpenPostDetail, onOpenEditProfile, onNavigate, onApproveSuggestion, onOpenUserListModal, onShowTagVoters } = props;
  const isOwnProfile = profileUser.id === currentUser.id;
  const isFollowing = currentUser.following.includes(profileUser.id);

  if (profileUser.status !== 'active') {
    return (
        <div className="py-8">
          <div className="max-w-4xl mx-auto">
              <div className="mb-4">
                <button 
                  onClick={() => onNavigate('feed', currentUser.id)}
                  className="flex items-center gap-1 text-sm text-secondary hover:text-primary font-semibold"
                >
                  <ArrowLeftIcon className="w-5 h-5"/>
                  Back to Feed
                </button>
              </div>
              <div className="text-center bg-muted p-12 rounded-lg border border-accent">
                <BanIcon className="w-16 h-16 text-destructive mx-auto mb-4" />
                <h2 className="text-2xl font-bold">Account Unavailable</h2>
                <p className="text-secondary mt-2">
                    This account is currently {profileUser.status}. Its content is not visible.
                </p>
              </div>
          </div>
        </div>
    );
  }

  return (
    <div className="py-8">
      <div className="max-w-4xl mx-auto">
        <div className="flex justify-between items-center mb-4">
            <button 
              onClick={() => onNavigate('feed', currentUser.id)}
              className="flex items-center gap-1 text-sm text-secondary hover:text-primary font-semibold"
            >
              <ArrowLeftIcon className="w-5 h-5"/>
              Back to Feed
            </button>
            {isOwnProfile && (
               <button 
                  onClick={onOpenEditProfile}
                  className="flex items-center gap-1 text-sm text-secondary hover:text-primary font-semibold"
              >
                  <PencilIcon className="w-4 h-4"/>
                  Edit Profile
              </button>
            )}
        </div>

        <div className="bg-background p-6 rounded-lg border border-accent mb-8 flex flex-col md:flex-row items-center gap-6">
          <img src={profileUser.avatar} alt={profileUser.username} className="w-32 h-32 rounded-full border-4 border-muted object-cover" />
          <div className="flex-grow text-center md:text-left">
            <h2 className="text-3xl font-bold">{profileUser.username}</h2>
            <p className="text-secondary mt-1">{profileUser.bio}</p>
            <div className="flex justify-center md:justify-start gap-6 mt-4">
              <div><span className="font-bold">{posts.length}</span> Posts</div>
              <button onClick={() => onOpenUserListModal('Followers', profileUser.followers)} className="hover:underline">
                  <span className="font-bold">{profileUser.followers.length}</span> Followers
              </button>
              <button onClick={() => onOpenUserListModal('Following', profileUser.following)} className="hover:underline">
                  <span className="font-bold">{profileUser.following.length}</span> Following
              </button>
            </div>
            {!isOwnProfile && (
              <button 
                onClick={() => onFollowToggle(profileUser.id)}
                className={`mt-4 px-6 py-2 rounded-full font-semibold transition-colors ${
                  isFollowing ? 'bg-accent text-foreground hover:bg-gray-300' : 'bg-primary text-primary-foreground hover:opacity-80'
                }`}
              >
                {isFollowing ? 'Unfollow' : 'Follow'}
              </button>
            )}
          </div>
        </div>
        
        {isOwnProfile && <PendingSuggestions posts={posts} users={users} onApproveSuggestion={onApproveSuggestion} onNavigate={onNavigate} onOpenPostDetail={onOpenPostDetail}/>}

        <div className="mt-8">
            <h3 className="text-2xl font-bold mb-4">Tag Cloud</h3>
            <TagCloud posts={posts} onShowTagVoters={onShowTagVoters} />
        </div>
        
        <div className="mt-8">
          <h3 className="text-2xl font-bold mb-4">Posts</h3>
          <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
            {posts.map(post => (
              <div 
                key={post.id} 
                className="aspect-square bg-muted rounded-lg overflow-hidden cursor-pointer group relative"
                onClick={() => onOpenPostDetail(post)}
              >
                <img 
                  src={post.mediaType === 'video' ? post.posterUrl || post.mediaUrl : post.mediaUrl} 
                  alt={post.caption} 
                  className="w-full h-full object-cover group-hover:opacity-75 transition-opacity" 
                  loading="lazy"
                />
                <div className="absolute inset-0 bg-black bg-opacity-0 group-hover:bg-opacity-40 transition-opacity flex items-center justify-center">
                   <p className="text-white opacity-0 group-hover:opacity-100 transition-opacity font-bold">View Post</p>
                </div>
              </div>
            ))}
            {posts.length === 0 && (
              <p className="text-muted-foreground col-span-full text-center py-8">
                {isOwnProfile ? "You haven't posted anything yet." : `${profileUser.username} hasn't posted anything yet.`}
              </p>
            )}
          </div>
        </div>

      </div>
    </div>
  );
};

export default Profile;
