import { useDispatch, useSelector } from "react-redux";
import { AppDispatch, RootState } from "../../app/store";
import { feedPostSave, setShowPostModal } from "../../app/reducers/feed";
import { Edit, Mic, Pause, Square, X } from "lucide-react";
import { useEffect, useRef, useState } from "react";

export default function PostModal() {
    const { feedPosting, showPostModal } = useSelector((state: RootState) => state.feed);
    const dispatch = useDispatch<AppDispatch>();
    const [postContent, setPostContent] = useState('');
    const [selectedImage, setSelectedImage] = useState<File | null>(null);
    const [imagePreview, setImagePreview] = useState<string | null>(null);
    const fileInputRef = useRef<HTMLInputElement>(null);
    const [isRecording, setIsRecording] = useState(false);
    const [audioBlob, setAudioBlob] = useState<Blob | null>(null);
    const [audioURL, setAudioURL] = useState<string | null>(null);
    const [recordingTimeDisplay, setRecordingTimeDisplay] = useState('00:00');
    const mediaRecorderRef = useRef<MediaRecorder | null>(null);
    const audioChunksRef = useRef<Blob[]>([]);
    const timerRef = useRef<number | null>(null);


    

    const startRecording = async () => {
        try {
          const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
          const mediaRecorder = new MediaRecorder(stream);
          mediaRecorderRef.current = mediaRecorder;
          audioChunksRef.current = [];
    
          mediaRecorder.ondataavailable = (e) => {
            if (e.data.size > 0) {
              audioChunksRef.current.push(e.data);
            }
          };
    
          mediaRecorder.onstop = () => {
            const audioBlob = new Blob(audioChunksRef.current, { type: 'audio/wav' });
            const audioUrl = URL.createObjectURL(audioBlob);
            setAudioBlob(audioBlob);
            setAudioURL(audioUrl);
            stream.getTracks().forEach(track => track.stop());
          };
    
          mediaRecorder.start();
          setIsRecording(true);
          
          // Start timer
          let seconds = 0;
          timerRef.current = window.setInterval(() => {
            seconds++;
            const minutes = Math.floor(seconds / 60);
            const remainingSeconds = seconds % 60;
            setRecordingTimeDisplay(
              `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`
            );
          }, 1000);
        } catch (error) {
          console.error('Error accessing microphone:', error);
        }
      };
    
      const stopRecording = () => {
        if (mediaRecorderRef.current && isRecording) {
          mediaRecorderRef.current.stop();
          setIsRecording(false);
          
          // Clear timer
          if (timerRef.current) {
            clearInterval(timerRef.current);
            timerRef.current = null;
          }
        }
      };
    
      const handleAudioDelete = () => {
        setAudioBlob(null);
        setAudioURL(null);
        setRecordingTimeDisplay('00:00');
      };
    
      const handleImageSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
        if (e.target.files && e.target.files[0]) {
          const file = e.target.files[0];
          setSelectedImage(file);
          // Create preview URL
          const reader = new FileReader();
          reader.onloadend = () => {
            setImagePreview(reader.result as string);
          };
          reader.readAsDataURL(file);
        }
      };
    
      const handleImageClick = () => {
        if (fileInputRef.current) {
          fileInputRef.current.click();
        }
      };
      
      const submitPost = () => {
        if (postContent.trim() || selectedImage || audioBlob) {
          const payload: { post?: string; photo?: File; audio?: Blob } = {};
          
          if (postContent.trim()) {
            payload.post = postContent;
          }
          if (selectedImage) {
            payload.photo = selectedImage;
          }
          if (audioBlob) {
            payload.audio = audioBlob;
          }
          
          dispatch(feedPostSave(payload))
            .unwrap()
            .then(() => {
              setPostContent('');
              setSelectedImage(null);
              setImagePreview(null);
              setAudioBlob(null);
              setAudioURL(null);
              setRecordingTimeDisplay('00:00');
              dispatch(setShowPostModal(false));
            });
        }
      };
    
      const handleRemoveImage = () => {
        setSelectedImage(null);
        setImagePreview(null);
        if (fileInputRef.current) {
          fileInputRef.current.value = '';
        }
      };
      
      // Clean up audio resources when component unmounts
      useEffect(() => {
        return () => {
          if (timerRef.current) {
            clearInterval(timerRef.current);
          }
          if (audioURL) {
            URL.revokeObjectURL(audioURL);
          }
        };
      }, [audioURL]);
    return(
        <>
            {showPostModal && (
                <div className="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4">
                <div className="bg-white rounded-lg w-full max-w-xl overflow-hidden">
                    <div className="p-4 flex justify-between items-center border-b border-gray-300">
                    <h2 className="text-xl font-semibold text-black">Create post</h2>
                    <button 
                        onClick={() => dispatch(setShowPostModal(false))}
                        className="text-black hover:text-gray-600"
                    >
                        <X size={24} />
                    </button>
                    </div>
                    
                    <div className="p-4">
                    <div className="flex items-center gap-3 mb-4">
                        <img 
                        src="/src/images/registration/profile.png" 
                        alt="Profile" 
                        className="w-12 h-12 rounded-full"
                        />
                        <div>
                        <p className="font-semibold text-black">Shamim Hasan</p>
                        </div>
                    </div>
                    
                    <textarea
                        placeholder="What's on your mind, Shamim?"
                        className="w-full bg-transparent text-black text-xl border-none focus:outline-none resize-none min-h-[150px]"
                        value={postContent}
                        onChange={(e) => setPostContent(e.target.value)}
                        autoFocus
                    />
                    
                    {/* Image preview section */}
                    {imagePreview && (
                        <div className="relative mt-3 mb-4 border rounded-lg overflow-hidden">
                        <img 
                            src={imagePreview} 
                            alt="Selected" 
                            className="w-full max-h-[300px] object-contain"
                        />
                        <div className="absolute top-2 right-2 flex gap-2">
                            <button 
                            onClick={handleImageClick}
                            className="bg-white p-1.5 rounded-full shadow-md text-gray-700 hover:text-gray-900"
                            >
                            <Edit size={16} />
                            </button>
                            <button 
                            onClick={handleRemoveImage}
                            className="bg-white p-1.5 rounded-full shadow-md text-gray-700 hover:text-gray-900"
                            >
                            <X size={16} />
                            </button>
                        </div>
                        </div>
                    )}
                    
                    {/* Audio recording/playback section */}
                    {(isRecording || audioURL) && (
                        <div className="mt-3 mb-4 border rounded-lg p-3 bg-gray-50">
                        <div className="flex items-center justify-between">
                            <div className="flex items-center gap-2">
                            <div className={`w-3 h-3 rounded-full ${isRecording ? 'bg-red-500 animate-pulse' : 'bg-gray-400'}`}></div>
                            <span className="text-gray-700 font-medium">
                                {isRecording ? 'Recording...' : 'Audio recorded'}
                            </span>
                            </div>
                            <div className="text-gray-500">{recordingTimeDisplay}</div>
                        </div>
                        
                        {audioURL && !isRecording && (
                            <div className="mt-3">
                            <audio src={audioURL} controls className="w-full h-10"></audio>
                            </div>
                        )}
                        
                        <div className="flex justify-end mt-2 gap-2">
                            {isRecording ? (
                            <button 
                                onClick={stopRecording}
                                className="bg-red-500 text-white p-1.5 rounded-full shadow-md hover:bg-red-600"
                            >
                                <Square size={16} />
                            </button>
                            ) : (
                            <button 
                                onClick={handleAudioDelete}
                                className="bg-white p-1.5 rounded-full shadow-md text-gray-700 hover:text-gray-900"
                            >
                                <X size={16} />
                            </button>
                            )}
                        </div>
                        </div>
                    )}
                    
                    {/* Hidden file input */}
                    <input 
                        type="file" 
                        ref={fileInputRef}
                        className="hidden"
                        accept="image/*"
                        onChange={handleImageSelect}
                    />
                    
                    <div className="flex items-center w-full justify-between mt-4 mb-5">
                        <span className="text-gray-700">Add to your post</span>
                        <div className="flex items-center gap-3">
                        <button 
                            className="bg-gray-800 text-white p-2 rounded-full"
                            onClick={handleImageClick}
                            disabled={isRecording}
                        >
                            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect width="18" height="18" x="3" y="3" rx="2"/><circle cx="9" cy="9" r="2"/><path d="m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"/></svg>
                        </button>
                        <button 
                            className={`${isRecording ? 'bg-red-500' : 'bg-primary'} text-white p-2 rounded-full`}
                            onClick={isRecording ? stopRecording : startRecording}
                            disabled={!!audioURL && !isRecording}
                        >
                            {isRecording ? <Pause size={24} /> : <Mic size={24} />}
                        </button>
                        </div>
                    </div>
                    
                    <button 
                        onClick={() => submitPost()} 
                        disabled={(!postContent.trim() && !selectedImage && !audioBlob) || feedPosting || isRecording}
                        className={`w-full py-2 rounded-lg font-medium ${
                        feedPosting 
                            ? 'bg-primary text-white opacity-80' 
                            : (postContent.trim() || selectedImage || audioBlob) && !isRecording
                            ? 'bg-primary text-white' 
                            : 'bg-gray-300 text-gray-500 cursor-not-allowed'
                        }`}
                    >
                        {feedPosting ? (
                        <div className="flex items-center justify-center">
                            <svg className="animate-spin -ml-1 mr-2 h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                            <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                            <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                            </svg>
                            Posting...
                        </div>
                        ) : 'Post'}
                    </button>
                    </div>
                </div>
                </div>
            )}
        </>
    )
}