import { Heart, Mic, Pause, Phone, Play, Send, Square, ThumbsUp, X } from "lucide-react";
import { useDispatch, useSelector } from "react-redux";
import { AppDispatch, RootState } from "../../app/store";
import { useRef, useState, useEffect, useCallback } from "react";
import { feedReactionSave, memberFollow, updateMemberFollow, updateReaction } from "../../app/reducers/feed";
import { Link, useParams } from "react-router-dom";
import { fetchMemberFeed } from "../../app/reducers/profile";

export default function ProfileFeeds() {
    const { postDataFetched, feedPosts, postPagination, loading, dataFetched } = useSelector((state: RootState) => state.profile);
    const postsEndRef = useRef<HTMLDivElement>(null);
    const dispatch = useDispatch<AppDispatch>();
    const [showReactions, setShowReactions] = useState<{[key: string]: boolean}>({});
    const timeoutRef = useRef<{[key: string]: ReturnType<typeof setTimeout>}>({});
    const [showInterestModal, setShowInterestModal] = useState(false);
    const [selectedPost, setSelectedPost] = useState<number | null>(null);
    const [selectedUserId, setSelectedUserId] = useState<number | null>(null);
    const [showVoiceModal, setShowVoiceModal] = useState(false);
    const [isRecording, setIsRecording] = useState(false);
    const [isPaused, setIsPaused] = useState(false);
    const [recordingTime, setRecordingTime] = useState(0);
    const [audioBlob, setAudioBlob] = useState<Blob | null>(null);
    const mediaRecorderRef = useRef<MediaRecorder | null>(null);
    const audioChunksRef = useRef<BlobPart[]>([]);
    const timerRef = useRef<ReturnType<typeof setInterval> | null>(null);
    const [selectedVoicePostId, setSelectedVoicePostId] = useState<number | null>(null);
    const { id } = useParams();

    const handleMouseEnter = (postId: number) => {
        const key = `post-${postId}`;
        if (timeoutRef.current[key]) {
            clearTimeout(timeoutRef.current[key]);
        }
        setShowReactions(prev => ({...prev, [key]: true}));
    };

    const handleMouseLeave = (postId: number) => {
        const key = `post-${postId}`;
        timeoutRef.current[key] = setTimeout(() => {
            setShowReactions(prev => ({...prev, [key]: false}));
        }, 1000); // 1 seconds delay
    };

    const handleReactionSelect = (postId: number, reactionType: string, userId: number) => {
        const key = `post-${postId}`;
        setShowReactions(prev => ({...prev, [key]: false}));
        dispatch(updateReaction({postId: postId, reaction: reactionType}))
        dispatch(feedReactionSave({reaction: reactionType, postId: postId, userId: userId}))
    };

    const handleMemberFollow = (userId: number) => {
          dispatch(updateMemberFollow({userId: userId}))
          dispatch(memberFollow(userId))
      }

      const handleInterestClick = (postId: number, userId: number) => {
        setSelectedPost(postId);
        setSelectedUserId(userId);
        setShowInterestModal(true);
    };

    const handleInterestConfirm = () => {
        if (selectedPost && selectedUserId) {
            console.log(`Sending interest to post ${selectedPost} by user ${selectedUserId}`);
            // You would typically dispatch an action here
            // dispatch(sendInterest({postId: selectedPost, userId: selectedUserId}));
        }
        setShowInterestModal(false);
    };

    const closeInterestModal = () => {
        setShowInterestModal(false);
    };

    // Clean up timeouts on unmount
    useEffect(() => {
        return () => {
            Object.values(timeoutRef.current).forEach(timeout => clearTimeout(timeout));
        };
    }, []);


    const handleVoiceClick = (postId: number) => {
        setSelectedVoicePostId(postId);
        setShowVoiceModal(true);
        // Reset recording state
        setIsRecording(false);
        setIsPaused(false);
        setRecordingTime(0);
        setAudioBlob(null);
        audioChunksRef.current = [];
    };
    
    const startRecording = async () => {
      try {
          setRecordingTime(0);

          const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
          const mediaRecorder = new MediaRecorder(stream);
          mediaRecorderRef.current = mediaRecorder;
          
          mediaRecorder.ondataavailable = (event) => {
              if (event.data.size > 0) {
                  audioChunksRef.current.push(event.data);
              }
          };
          
          mediaRecorder.onstop = () => {
              const audioBlob = new Blob(audioChunksRef.current, { type: 'audio/wav' });
              setAudioBlob(audioBlob);
          };
          
          // Clear any existing timer first
          if (timerRef.current) {
              clearInterval(timerRef.current);
              timerRef.current = null;
          }
          
          // Start recording
          mediaRecorder.start();
          setIsRecording(true);
          
          // Start timer immediately with a shorter interval for the first update
          setTimeout(() => {
              setRecordingTime(1); // Force an update to 1 second immediately
              
              // Then continue with regular interval
              timerRef.current = setInterval(() => {
                  setRecordingTime(prev => prev + 1);
              }, 1000);
          }, 100);
          
      } catch (error) {
          console.error('Error accessing microphone:', error);
      }
  };
    
    const pauseRecording = () => {
        if (mediaRecorderRef.current && isRecording && !isPaused) {
            mediaRecorderRef.current.pause();
            setIsPaused(true);
            
            // Pause timer
            if (timerRef.current) {
                clearInterval(timerRef.current);
                timerRef.current = null;
            }
        }
    };
    
    const resumeRecording = () => {
        if (mediaRecorderRef.current && isRecording && isPaused) {
            mediaRecorderRef.current.resume();
            setIsPaused(false);
            
            // Resume timer
            timerRef.current = setInterval(() => {
                setRecordingTime(prev => prev + 1);
            }, 1000);
        }
    };
    
    const stopRecording = () => {
        if (mediaRecorderRef.current && isRecording) {
            mediaRecorderRef.current.stop();
            setIsRecording(false);
            setIsPaused(false);
            
            // Stop timer
            if (timerRef.current) {
                clearInterval(timerRef.current);
                timerRef.current = null;
            }
            
            // Stop all tracks on the stream
            mediaRecorderRef.current.stream.getTracks().forEach(track => track.stop());
        }
    };
    
    const sendVoiceMessage = () => {
        if (audioBlob && selectedVoicePostId) {
            console.log(`Sending voice message to post ${selectedVoicePostId}`);
            // Here you would dispatch an action to send the voice message
            // dispatch(sendVoiceMessage({ postId: selectedVoicePostId, audio: audioBlob }));
            
            // Close the modal
            closeVoiceModal();
        }
    };
    
    const closeVoiceModal = () => {
        // Stop recording if active
        if (isRecording) {
            stopRecording();
        }
        
        setShowVoiceModal(false);
    };
    
    // Format time as MM:SS
    const formatTime = (seconds: number) => {
        const minutes = Math.floor(seconds / 60);
        const remainingSeconds = seconds % 60;
        return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
    };
    
    

    
    // Clean up on unmount
    useEffect(() => {
        return () => {
            if (timerRef.current) {
                clearInterval(timerRef.current);
            }
            
            if (mediaRecorderRef.current && isRecording) {
                mediaRecorderRef.current.stream.getTracks().forEach(track => track.stop());
            }
        };
    }, [isRecording]);

     const loadMorePosts = useCallback(() => {
            if (!loading && postPagination && postPagination.current_page < postPagination.last_page) {
                const nextPage = postPagination.current_page + 1;
                if (!id) return;
                const decodedId = atob(id);
                dispatch(fetchMemberFeed({ id: decodedId, page: nextPage }));
            }
        }, [loading, postPagination, dispatch, id]);

        useEffect(() => {
            const observer = new IntersectionObserver(
                (entries) => {
                    const target = entries[0];
                    if (target.isIntersecting && dataFetched) {
                        loadMorePosts();
                    }
                },
                {
                    root: null,
                    rootMargin: '100px', // Load more posts when 100px before reaching the end
                    threshold: 0.1
                }
            );
    
            const currentRef = postsEndRef.current;
            if (currentRef) {
                observer.observe(currentRef);
            }
    
            return () => {
                if (currentRef) {
                    observer.unobserve(currentRef);
                }
            };
        }, [dataFetched, loadMorePosts]);

    return(
      <>
        <div className="space-y-3">
          {/* Actual posts */}
          {feedPosts.map((post, index) => (
            <div key={`${post.id}-${index}`} className="bg-white rounded-2xl shadow-lg overflow-hidden">
              {/* Post header */}
              <div className="p-4 flex items-center justify-between">
                <div className="flex items-center gap-3">
                    <Link to={`/profile/${post.user_id}`}>
                        <img 
                            src={post.user_photo}
                            alt={post.name.split(' ')[0]} 
                            className="w-10 h-10 rounded-full object-cover"
                            referrerPolicy="no-referrer"
                        />
                    </Link>
                  <div>
                    <div className="flex items-center gap-2">
                      <h3 className="font-medium text-sm">{post.name.split(' ')[0]}</h3>
                      <span className="text-gray-500 text-xs">{post.gender === 'Male' ? ' Updated his':  'Updated her '} {post.picture_type}</span>
                    </div>
                    <p className="text-xs text-gray-500">{post.time}</p>
                  </div>
                </div>
                {!post.is_follow || post.is_follow === "1" ? (
                  <button onClick={() => handleMemberFollow(post.user_id)} className="text-blue-500 text-xs font-medium">
                    Follow
                  </button>
                ) : ''}
              </div>
              {post.content && (
                <div className="px-4 pb-3">
                  <p className="text-md text-gray-800">{post.content}</p>
                </div>
              )}
              {/* Post image */}
              <img 
                src={post.image}
                alt="Post" 
                referrerPolicy="no-referrer"
                className="w-full object-contain max-h-[550px] lg:max-h-[800px]"
              />
              
              {/* Reactions count */}
              <div className="px-4 py-2 border-b flex items-center">
                <div className="flex -space-x-1 relative group">
                  {post.like && post.like >= 1 ? (
                    <div className="w-5 h-5 rounded-full bg-blue-500 flex items-center justify-center text-white text-xs">
                      <img src="/src/images/feed/like_emoji.gif" alt="Like" className="w-5 h-5" />
                    </div>
                  ) : ''}
                  {post.love && post.love >= 1 ? (
                    <div className="w-5 h-5 rounded-full bg-blue-500 flex items-center justify-center text-white text-xs">
                      <img src="/src/images/feed/love_emoji.gif" alt="Love" className="w-5 h-5" />
                    </div>
                  ) : ''}
                  {post.care && post.care >= 1 ? (
                    <div className="w-5 h-5 rounded-full bg-blue-500 flex items-center justify-center text-white text-xs">
                      <img src="/src/images/feed/care.png" alt="Care" className="w-5 h-5" />
                    </div>
                  ) : ''}
                  {post.laugh && post.laugh >= 1 ? (
                    <div className="w-5 h-5 rounded-full bg-blue-500 flex items-center justify-center text-white text-xs">
                      <img src="/src/images/feed/laugh_emoji.gif" alt="laugh" className="w-5 h-5" />
                    </div>
                  ) : ''}
                </div>
                <span className="text-xs text-gray-500 ml-2">{post.total_react || ''}</span>
              </div>
              
              {/* Action buttons */}
              <div className="flex border-b py-4">
                <button 
                    className={`flex-1 py-2 flex items-center justify-center gap-1 ${post.provide_react ? 'text-blue-500' : 'text-gray-600'} hover:bg-gray-50 relative`}
                    onMouseEnter={() => handleMouseEnter(post.id)}
                    onMouseLeave={() => handleMouseLeave(post.id)}
                >
                    {post.provide_react ? (
                        <>
                            {post.provide_react === 'like' && <img src="/src/images/feed/like_emoji.gif" alt="Care" className="w-5 h-5" />}
                            {post.provide_react === 'love' && <img src="/src/images/feed/love_emoji.gif" alt="Care" className="w-5 h-5" />}
                            {post.provide_react === 'care' && <img src="/src/images/feed/care_emoji.gif" alt="Care" className="w-5 h-5" />}
                            {post.provide_react === 'laugh' && <img src="/src/images/feed/laugh_emoji.gif" alt="Laugh" className="w-5 h-5" />}
                            {post.provide_react === 'wow' && <img src="/src/images/feed/wow_emoji.gif" alt="Wow" className="w-5 h-5" />}
                            {post.provide_react === 'sad' && <img src="/src/images/feed/sad_emoji.gif" alt="Sad" className="w-5 h-5" />}
                            {post.provide_react === 'angry' && <img src="/src/images/feed/angry_emoji.gif" alt="Angry" className="w-5 h-5" />}
                            <span className="text-sm">
                            {post.provide_react?.charAt(0).toUpperCase() + post.provide_react?.slice(1)}
                            </span>
                        </>
                    ) : (
                        <>
                            <ThumbsUp size={18} />
                            <span className="text-sm">Like</span>
                        </>
                    )}
                    
                    {/* Emoji reaction popup with delayed hide */}
                    <div className={`absolute bottom-full left-[140px] transform -translate-x-1/2 mb-2 ${showReactions[`post-${post.id}`] ? 'block' : 'hidden'} bg-white rounded-full shadow-lg p-1 transition-all duration-200 z-50`}>
                        <div className="flex space-x-1">
                            <button 
                                className={post.provide_react === 'like' ? 'w-8 h-8 rounded-full flex items-center justify-center transition-transform scale-110 bg-gray-100' : 'w-8 h-8 rounded-full flex items-center justify-center transition-transform hover:scale-110 hover:bg-gray-100'}
                                onClick={() => handleReactionSelect(post.id, 'like', post.user_id)}
                            >
                                <img src="/src/images/feed/like_emoji.gif" alt="Like" className="w-6 h-6" />
                            </button>
                            <button 
                                className={post.provide_react === 'love' ? 'w-8 h-8 rounded-full flex items-center justify-center transition-transform scale-110 bg-gray-100' : 'w-8 h-8 rounded-full flex items-center justify-center transition-transform hover:scale-110 hover:bg-gray-100'}
                                onClick={() => handleReactionSelect(post.id, 'love', post.user_id)}
                            >
                                <img src="/src/images/feed/love_emoji.gif" alt="Love" className="w-6 h-6" />
                            </button>
                            <button 
                                className={post.provide_react === 'care' ? 'w-8 h-8 rounded-full flex items-center justify-center transition-transform scale-110 bg-gray-100' : 'w-8 h-8 rounded-full flex items-center justify-center transition-transform hover:scale-110 hover:bg-gray-100'}
                                onClick={() => handleReactionSelect(post.id, 'care', post.user_id)}
                            >
                                <img src="/src/images/feed/care_emoji.gif" alt="Care" className="w-6 h-6" />
                            </button>
                            <button 
                                className={post.provide_react === 'laugh' ? 'w-8 h-8 rounded-full flex items-center justify-center transition-transform scale-110 bg-gray-100' : 'w-8 h-8 rounded-full flex items-center justify-center transition-transform hover:scale-110 hover:bg-gray-100'}
                                onClick={() => handleReactionSelect(post.id, 'laugh', post.user_id)}
                            >
                                <img src="/src/images/feed/laugh_emoji.gif" alt="Laugh" className="w-6 h-6" />
                            </button>
                            <button 
                                className={post.provide_react === 'wow' ? 'w-8 h-8 rounded-full flex items-center justify-center transition-transform scale-110 bg-gray-100' : 'w-8 h-8 rounded-full flex items-center justify-center transition-transform hover:scale-110 hover:bg-gray-100'}
                                onClick={() => handleReactionSelect(post.id, 'wow', post.user_id)}
                            >
                                <img src="/src/images/feed/wow_emoji.gif" alt="Wow" className="w-6 h-6" />
                            </button>
                            <button 
                                className={post.provide_react === 'sad' ? 'w-8 h-8 rounded-full flex items-center justify-center transition-transform scale-110 bg-gray-100' : 'w-8 h-8 rounded-full flex items-center justify-center transition-transform hover:scale-110 hover:bg-gray-100'}
                                onClick={() => handleReactionSelect(post.id, 'sad', post.user_id)}
                            >
                                <img src="/src/images/feed/sad_emoji.gif" alt="Sad" className="w-6 h-6" />
                            </button>
                            <button 
                                className={post.provide_react === 'angry' ? 'w-8 h-8 rounded-full flex items-center justify-center transition-transform scale-110 bg-gray-100' : 'w-8 h-8 rounded-full flex items-center justify-center transition-transform hover:scale-110 hover:bg-gray-100'}
                                onClick={() => handleReactionSelect(post.id, 'angry', post.user_id)}
                            >
                                <img src="/src/images/feed/angry_emoji.gif" alt="Angry" className="w-6 h-6" />
                            </button>
                        </div>
                    </div>
                </button>
                <button 
                      className="flex-1 py-2 flex items-center justify-center gap-1 text-gray-600 hover:bg-gray-50"
                      onClick={() => handleInterestClick(post.id, post.user_id)}
                  >
                      <Heart size={18} />
                      <span className="text-sm">Interest</span>
                  </button>
                  <button 
                      className="flex-1 py-2 flex items-center justify-center gap-1 text-gray-600 hover:bg-gray-50"
                      onClick={() => handleVoiceClick(post.id)}
                  >
                      <Mic size={18} />
                      <span className="text-sm">Voice</span>
                  </button>
                <button className="flex-1 py-2 flex items-center justify-center gap-1 text-gray-600 hover:bg-gray-50">
                  <Phone size={18} />
                  <span className="text-sm">Contact</span>
                </button>
              </div>
            </div>
          ))}
          
          {/* Loading indicator for more posts */}
          {!postDataFetched &&(
            <>
              {[1, 2].map((item) => (
                <div key={`post-skeleton-${item}`} className="bg-white rounded-lg shadow-md overflow-hidden animate-pulse">
                  <div className="p-4 flex items-center">
                    <div className="w-10 h-10 rounded-full bg-gray-300"></div>
                    <div className="ml-3 flex-1">
                      <div className="h-4 bg-gray-300 rounded w-1/3 mb-2"></div>
                      <div className="h-3 bg-gray-300 rounded w-1/4"></div>
                    </div>
                  </div>
                  <div className="h-[300px] bg-gray-300"></div>
                  <div className="p-4">
                    <div className="h-4 bg-gray-300 rounded w-1/4 mb-3"></div>
                    <div className="flex justify-between">
                      <div className="h-8 bg-gray-300 rounded w-1/5"></div>
                      <div className="h-8 bg-gray-300 rounded w-1/5"></div>
                      <div className="h-8 bg-gray-300 rounded w-1/5"></div>
                      <div className="h-8 bg-gray-300 rounded w-1/5"></div>
                    </div>
                  </div>
                </div>
              ))}
            </>
          )}
          
          {/* End of posts marker for intersection observer */}
          <div ref={postsEndRef}></div>
        </div>

       {/* Interest Confirmation Modal */}
       {showInterestModal && (
          <div className="fixed inset-0 mt-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
              <div className="bg-white rounded-lg shadow-lg p-6 max-w-sm w-full mx-4 relative">
                  <button 
                      onClick={closeInterestModal}
                      className="absolute top-3 right-3 text-gray-500 hover:text-gray-700"
                  >
                      <X size={20} />
                  </button>
                  
                  <p className="text-center text-gray-700 mb-6 font-medium">
                      নিশ্চিত হয়ে কনফার্ম বাটন ক্লিক করুন।
                  </p>
                  
                  <div className="flex justify-between mb-3">
                      <span className="text-gray-600">Available interest :</span>
                      <span className="font-medium">8</span>
                  </div>
                  
                  <div className="flex justify-between mb-3">
                      <span className="text-gray-600">Cost :</span>
                      <span className="font-medium">1</span>
                  </div>
                  
                  <div className="flex justify-between mb-6">
                      <span className="text-gray-600">Remaining interest :</span>
                      <span className="font-medium">7</span>
                  </div>
                  
                  <button 
                      onClick={handleInterestConfirm}
                      className="w-full bg-primary text-white py-3 rounded-md transition-colors font-medium"
                  >
                      Confirm
                  </button>
              </div>
          </div>
      )}

       {/* Voice Recording Modal */}
       {showVoiceModal && (
                <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
                    <div className="bg-white rounded-lg shadow-lg p-6 max-w-sm w-full mx-4 relative h-[400px] flex flex-col">
                        <button 
                            onClick={closeVoiceModal}
                            className="absolute top-3 right-3 text-gray-500 hover:text-gray-700"
                        >
                            <X size={20} />
                        </button>
                        
                        {/* Top section - Title */}
                        <div className="mb-auto">
                            <h3 className="text-center text-lg font-medium text-gray-800">
                                Voice Message
                            </h3>
                        </div>
                        
                        {/* Middle section - Recording UI */}
                        <div className="my-auto py-8 flex flex-col items-center">
                            {/* Recording time */}
                            <div className="text-4xl font-bold text-gray-700 mb-8">
                                {formatTime(recordingTime)}
                            </div>
                            
                            {/* Audio player if recording is complete */}
                            {audioBlob && !isRecording && (
                                <audio 
                                    src={URL.createObjectURL(audioBlob)} 
                                    controls 
                                    className="w-full mb-6"
                                />
                            )}
                            
                            {/* Recording status */}
                            <div className="text-center mb-6">
                                {isRecording && !isPaused && (
                                    <span className="text-red-500 flex items-center gap-2">
                                        <span className="inline-block w-3 h-3 bg-red-500 rounded-full animate-pulse"></span>
                                        Recording...
                                    </span>
                                )}
                                {isPaused && (
                                    <span className="text-yellow-500">Paused</span>
                                )}
                                {!isRecording && audioBlob && (
                                    <span className="text-green-500">Recording complete</span>
                                )}
                            </div>
                            
                            {/* Control buttons */}
                            <div className="flex gap-4">
                                {!isRecording && !audioBlob && (
                                    <button 
                                        onClick={startRecording}
                                        className="p-3 bg-red-500 text-white rounded-full hover:bg-red-600"
                                    >
                                        <Mic size={24} />
                                    </button>
                                )}
                                
                                {isRecording && !isPaused && (
                                    <>
                                        <button 
                                            onClick={pauseRecording}
                                            className="p-3 bg-yellow-500 text-white rounded-full hover:bg-yellow-600"
                                        >
                                            <Pause size={24} />
                                        </button>
                                        
                                        <button 
                                            onClick={stopRecording}
                                            className="p-3 bg-red-500 text-white rounded-full hover:bg-red-600"
                                        >
                                            <Square size={24} />
                                        </button>
                                    </>
                                )}
                                
                                {isRecording && isPaused && (
                                    <>
                                        <button 
                                            onClick={resumeRecording}
                                            className="p-3 bg-green-500 text-white rounded-full hover:bg-green-600"
                                        >
                                            <Play size={24} />
                                        </button>
                                        
                                        <button 
                                            onClick={stopRecording}
                                            className="p-3 bg-red-500 text-white rounded-full hover:bg-red-600"
                                        >
                                            <Square size={24} />
                                        </button>
                                    </>
                                )}
                            </div>
                        </div>
                        
                        {/* Bottom section - Send button */}
                        <div className="mt-auto">
                            <button 
                                onClick={sendVoiceMessage}
                                disabled={!audioBlob}
                                className={`w-full py-3 rounded-md flex items-center justify-center gap-2 font-medium ${
                                    audioBlob 
                                        ? 'bg-primary text-white' 
                                        : 'bg-gray-200 text-gray-500 cursor-not-allowed'
                                }`}
                            >
                                <Send size={18} />
                                Send Voice Message
                            </button>
                        </div>
                    </div>
                </div>
            )}
      </>
    )
}