import React, { useState } from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import {
    MessageSquare,
    Send,
    MessageCircle,
    Share2,
    MoreHorizontal,
    Image,
    Link2,
    User,
    Clock,
    ThumbsUp
} from 'lucide-react';
import { Button } from '@nexuscrm/salesforce-crm-standard-frontend/platform/components/ui';
import { useSuccessToast, useErrorToast } from '@nexuscrm/salesforce-crm-standard-frontend/platform/components/ui';
import { Logger } from '../core/services/Logger';
import { chatterAPI } from '../infrastructure/api/chatter';

const formatTimeAgo = (dateStr: string): string => {
    const date = new Date(dateStr);
    const seconds = Math.floor((Date.now() - date.getTime()) / 1000);
    if (seconds < 60) return 'Just now';
    const minutes = Math.floor(seconds / 60);
    if (minutes < 60) return `${minutes}m ago`;
    const hours = Math.floor(minutes / 60);
    if (hours < 24) return `${hours}h ago`;
    const days = Math.floor(hours / 24);
    return `${days}d ago`;
};

// Feed Comments Component
const FeedComments: React.FC<{
    feedItemId: string;
    commentInput: string;
    onCommentChange: (val: string) => void;
    onAddComment: () => void;
}> = ({ feedItemId, commentInput, onCommentChange, onAddComment }) => {
    // Fetch comments
    const { data: comments = [], isLoading } = useQuery({
        queryKey: ['chatter', 'comments', feedItemId],
        queryFn: async () => {
            return await chatterAPI.getComments(feedItemId);
        },
    });

    return (
        <div className="px-4 py-3 bg-slate-50 border-t border-slate-100">
            {isLoading ? (
                <div className="py-2 text-center text-xs text-slate-500">Loading comments...</div>
            ) : comments.length > 0 ? (
                <div className="space-y-3 mb-3 pl-2 border-l-2 border-slate-200">
                    {comments.map(comment => (
                        <div key={comment.Id} className="text-sm">
                            <div className="flex items-center gap-2 mb-1">
                                <span className="font-semibold text-slate-800">{comment.CreatedBy?.Name || 'Unknown User'}</span>
                                <span className="text-xs text-slate-500">{formatTimeAgo(comment.CreatedDate)}</span>
                            </div>
                            <p className="text-slate-700">{comment.CommentBody}</p>
                        </div>
                    ))}
                </div>
            ) : null}

            {/* Add Comment */}
            <div className="flex gap-2 mt-2">
                <div className="w-8 h-8 rounded-full bg-gradient-to-br from-blue-500 to-indigo-600 flex items-center justify-center text-white text-xs shrink-0">
                    <User size={14} />
                </div>
                <div className="flex-1 flex gap-2">
                    <input
                        type="text"
                        value={commentInput}
                        onChange={(e) => onCommentChange(e.target.value)}
                        placeholder="Write a comment..."
                        className="flex-1 px-3 py-1.5 text-sm border border-slate-200 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                        onKeyDown={(e) => {
                            if (e.key === 'Enter' && !e.shiftKey) {
                                e.preventDefault();
                                onAddComment();
                            }
                        }}
                    />
                    <Button
                        variant="primary"
                        size="sm"
                        onClick={onAddComment}
                        disabled={!commentInput.trim()}
                    >
                        <Send size={14} />
                    </Button>
                </div>
            </div>
        </div>
    );
};

export const Chatter: React.FC = () => {
    const showSuccess = useSuccessToast();
    const showError = useErrorToast();
    const queryClient = useQueryClient();

    const [newPost, setNewPost] = useState('');
    const [activeTab, setActiveTab] = useState<'all' | 'mentions' | 'following'>('all');
    const [expandedComments, setExpandedComments] = useState<Set<string>>(new Set());
    const [commentInputs, setCommentInputs] = useState<Record<string, string>>({});

    // Fetch feed from Salesforce API
    const { data: feedItems = [], isLoading, error } = useQuery({
        queryKey: ['chatter', 'feed', activeTab],
        queryFn: async () => {
            const data = await chatterAPI.getFeed();
            return data;
        },
        staleTime: 30000,
    });

    // Handle error with useEffect to avoid calling showError during render
    React.useEffect(() => {
        if (error) {
            Logger.error('[Chatter] Failed to fetch feed', {}, error);
            showError('Could not load the feed');
        }
    }, [error, showError]);

    // Toggle like - calls Salesforce API
    const handleLike = async (itemId: string) => {
        try {
            await chatterAPI.likeFeedItem(itemId);
            Logger.info('[Chatter] Like toggled', { itemId });
            showSuccess('Your reaction has been recorded');
            // Invalidate feed cache to update LikeCount
            queryClient.invalidateQueries({ queryKey: ['chatter', 'feed'] });
        } catch (err: unknown) {
            Logger.error('[Chatter] Failed to like item', { itemId }, err);
            showError('Could not like this post');
        }
    };

    // Toggle comments visibility
    const toggleComments = (itemId: string) => {
        setExpandedComments(prev => {
            const next = new Set(prev);
            if (next.has(itemId)) {
                next.delete(itemId);
            } else {
                next.add(itemId);
            }
            return next;
        });
    };

    // Add comment - calls Salesforce API
    const handleAddComment = async (itemId: string) => {
        const comment = commentInputs[itemId]?.trim();
        if (!comment) return;

        try {
            await chatterAPI.createComment(itemId, comment);
            Logger.info('[Chatter] Comment added', { itemId, comment });
            setCommentInputs(prev => ({ ...prev, [itemId]: '' }));
            showSuccess('Your comment has been posted');
            // Invalidate feed cache to update CommentCount
            queryClient.invalidateQueries({ queryKey: ['chatter', 'feed'] });
        } catch (err: unknown) {
            Logger.error('[Chatter] Failed to add comment', { itemId }, err);
            showError('Could not post your comment');
        }
    };

    // Create new post - calls Salesforce API
    const handleCreatePost = async () => {
        const content = newPost.trim();
        if (!content) return;

        try {
            // Use current user's profile as parent (typically UserProfile ID)
            await chatterAPI.createPost('me', content);
            Logger.info('[Chatter] Post created', { content });
            setNewPost('');
            showSuccess('Your post has been shared');
            // Invalidate feed cache to refetch
            queryClient.invalidateQueries({ queryKey: ['chatter', 'feed'] });
        } catch (err: unknown) {
            Logger.error('[Chatter] Failed to create post', {}, err);
            showError('Could not create your post');
        }
    };

    return (
        <div className="p-6 max-w-3xl mx-auto">
            {/* Header */}
            <div className="flex items-center gap-3 mb-6">
                <div className="p-2 bg-gradient-to-br from-blue-500 to-indigo-600 rounded-xl shadow-lg">
                    <MessageSquare className="w-6 h-6 text-white" />
                </div>
                <div>
                    <h1 className="text-2xl font-bold text-gray-900 dark:text-white">Chatter</h1>
                    <p className="text-sm text-gray-500 dark:text-gray-400">
                        Stay connected with your team
                    </p>
                </div>
            </div>

            {/* Compose Box */}
            <div className="bg-white rounded-xl shadow-sm border border-slate-200 p-4 mb-6">
                <div className="flex gap-3">
                    <div className="w-10 h-10 rounded-full bg-gradient-to-br from-blue-500 to-indigo-600 flex items-center justify-center text-white font-semibold shrink-0">
                        <User size={20} />
                    </div>
                    <div className="flex-1">
                        <textarea
                            value={newPost}
                            onChange={(e) => setNewPost(e.target.value)}
                            placeholder="What's on your mind?"
                            rows={3}
                            className="w-full px-3 py-2 border border-slate-200 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 resize-none"
                        />
                        <div className="flex justify-between items-center mt-2">
                            <div className="flex gap-2">
                                <button type="button" className="p-2 text-slate-400 hover:text-slate-600 hover:bg-slate-100 rounded-lg transition-colors">
                                    <Image size={18} />
                                </button>
                                <button type="button" className="p-2 text-slate-400 hover:text-slate-600 hover:bg-slate-100 rounded-lg transition-colors">
                                    <Link2 size={18} />
                                </button>
                            </div>
                            <Button variant="primary" size="sm" onClick={handleCreatePost} disabled={!newPost.trim()}>
                                <Send size={16} className="mr-1" />
                                Post
                            </Button>
                        </div>
                    </div>
                </div>
            </div>

            {/* Feed Tabs */}
            <div className="flex gap-1 bg-slate-100 p-1 rounded-lg mb-6">
                {(['all', 'mentions', 'following'] as const).map(tab => (
                    <button
                        key={tab}
                        type="button"
                        onClick={() => setActiveTab(tab)}
                        className={`flex-1 py-2 px-4 rounded-md text-sm font-medium transition-all ${activeTab === tab
                            ? 'bg-white text-slate-900 shadow-sm'
                            : 'text-slate-600 hover:text-slate-900'
                            }`}
                    >
                        {tab.charAt(0).toUpperCase() + tab.slice(1)}
                    </button>
                ))}
            </div>

            {/* Feed Items */}
            {isLoading ? (
                <div className="py-12 text-center text-slate-500">
                    <div className="w-8 h-8 border-4 border-blue-600 border-t-transparent rounded-full animate-spin mx-auto mb-4" />
                    Loading feed...
                </div>
            ) : feedItems.length === 0 ? (
                <div className="py-12 text-center">
                    <MessageSquare className="w-12 h-12 text-slate-300 mx-auto mb-3" />
                    <p className="text-slate-500">No posts yet. Be the first to share something!</p>
                </div>
            ) : (
                <div className="space-y-4">
                    {feedItems.map(item => (
                        <div key={item.Id} className="bg-white rounded-xl shadow-sm border border-slate-200 overflow-hidden">
                            {/* Post Header */}
                            <div className="p-4">
                                <div className="flex items-start gap-3">
                                    <div className="w-10 h-10 rounded-full bg-gradient-to-br from-blue-400 to-indigo-500 flex items-center justify-center text-white font-semibold shrink-0">
                                        {item.CreatedBy?.Name?.charAt(0) || 'U'}
                                    </div>
                                    <div className="flex-1 min-w-0">
                                        <div className="flex items-center gap-2">
                                            <span className="font-semibold text-slate-900">{item.CreatedBy?.Name || 'Unknown User'}</span>
                                            {item.Type === 'TrackedChange' && (
                                                <span className="text-xs px-2 py-0.5 bg-blue-100 text-blue-700 rounded-full">Update</span>
                                            )}
                                            {item.Type === 'ContentPost' && (
                                                <span className="text-xs px-2 py-0.5 bg-green-100 text-green-700 rounded-full">Shared</span>
                                            )}
                                        </div>
                                        <div className="flex items-center gap-1 text-sm text-slate-500">
                                            <Clock size={12} />
                                            <span>{formatTimeAgo(item.CreatedDate)}</span>
                                        </div>
                                    </div>
                                    <button type="button" className="p-1.5 text-slate-400 hover:text-slate-600 hover:bg-slate-100 rounded-lg transition-colors">
                                        <MoreHorizontal size={18} />
                                    </button>
                                </div>

                                {/* Content */}
                                <p className="mt-3 text-slate-700 whitespace-pre-wrap">{item.Body}</p>
                            </div>

                            {/* Actions */}
                            <div className="px-4 py-2 border-t border-slate-100 flex items-center gap-4">
                                <button
                                    type="button"
                                    onClick={() => handleLike(item.Id)}
                                    className="flex items-center gap-1.5 text-sm font-medium text-slate-500 hover:text-blue-600 transition-colors"
                                >
                                    <ThumbsUp size={16} />
                                    <span>{item.LikeCount ?? 0}</span>
                                </button>
                                <button
                                    type="button"
                                    onClick={() => toggleComments(item.Id)}
                                    className="flex items-center gap-1.5 text-sm font-medium text-slate-500 hover:text-blue-600 transition-colors"
                                >
                                    <MessageCircle size={16} />
                                    <span>{item.CommentCount ?? 0} Comments</span>
                                </button>
                                <button type="button" className="flex items-center gap-1.5 text-sm font-medium text-slate-500 hover:text-blue-600 transition-colors ml-auto">
                                    <Share2 size={16} />
                                    Share
                                </button>
                            </div>

                            {/* Comments Section */}
                            {expandedComments.has(item.Id) && (
                                <FeedComments
                                    feedItemId={item.Id}
                                    commentInput={commentInputs[item.Id] || ''}
                                    onCommentChange={(val) => setCommentInputs(prev => ({ ...prev, [item.Id]: val }))}
                                    onAddComment={() => handleAddComment(item.Id)}
                                />
                            )}
                        </div>
                    ))}
                </div>
            )}
        </div>
    );
};

export default Chatter;
