import { useState, useEffect, useRef } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Phone, ArrowLeft, Mic, Send, X } from 'lucide-react';
import { useDispatch, useSelector } from 'react-redux';
import { AppDispatch, RootState } from '../app/store';
import { fetchSingleMessageData, sendMessageReply, updateMessages } from '../app/reducers/singlemessage';

// Add a simple loading spinner component
const MessageLoadingSpinner = () => (
  <div className="flex justify-center items-center h-full">
    <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary"></div>
  </div>
);

export default function MessageDetails() {
  const chat_receiver_photo = localStorage.getItem('chat_receiver_photo');
  const chat_receiver_name = localStorage.getItem('chat_receiver_name');
  const singlemessage = useSelector((state: RootState) => state.singlemessage);
  const dispatch = useDispatch<AppDispatch>();
  const userJson = localStorage.getItem('user');
  const user = userJson ? JSON.parse(userJson) : null;
  const { id } = useParams();
  const navigate = useNavigate();
  const [newMessage, setNewMessage] = useState('');
  const messagesContainerRef = useRef<HTMLDivElement>(null);
  
  // Voice recording states
  const [isRecording, setIsRecording] = useState(false);
  const [audioURL, setAudioURL] = useState<string | null>(null);
  const [recordingTime, setRecordingTime] = useState(0);
  const mediaRecorderRef = useRef<MediaRecorder | null>(null);
  const audioChunksRef = useRef<Blob[]>([]);
  const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const MAX_RECORDING_TIME = 180; // 3 minutes in seconds

  // Fetch conversation data
  useEffect(() => {
    if (id) {
      dispatch(fetchSingleMessageData(id))
    }
  }, [id, dispatch]);

  // Scroll to bottom function
  const scrollToBottom = () => {
    if (messagesContainerRef.current) {
      messagesContainerRef.current.scrollTop = messagesContainerRef.current.scrollHeight;
    }
  };

  // Scroll to bottom on initial load and when messages change
  useEffect(() => {
    if (!singlemessage.loading && singlemessage) {
      scrollToBottom();
    }
  }, [singlemessage]);

  // Handle recording timer
  useEffect(() => {
    if (isRecording) {
      timerRef.current = setInterval(() => {
        setRecordingTime(prev => {
          const newTime = prev + 1;
          // Auto-stop recording when reaching max time
          if (newTime >= MAX_RECORDING_TIME) {
            stopRecording();
            return MAX_RECORDING_TIME;
          }
          return newTime;
        });
      }, 1000);
    } else {
      if (timerRef.current) {
        clearInterval(timerRef.current);
      }
    }

    return () => {
      if (timerRef.current) {
        clearInterval(timerRef.current);
      }
    };
  }, [isRecording]);

  // Format recording time
  const formatTime = (seconds: number) => {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  };

  // Start recording
  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/mp3' });
        const url = URL.createObjectURL(audioBlob);
        setAudioURL(url);
        
        // Stop all tracks
        stream.getTracks().forEach(track => track.stop());
      };

      mediaRecorder.start();
      setIsRecording(true);
    } catch (err) {
      console.error('Error accessing microphone:', err);
      alert('Could not access microphone. Please check your permissions.');
    }
  };

  // Stop recording
  const stopRecording = () => {
    if (mediaRecorderRef.current && isRecording) {
      mediaRecorderRef.current.stop();
      setIsRecording(false);
    }
  };

  // Cancel recording
  const cancelRecording = () => {
    if (mediaRecorderRef.current && isRecording) {
      mediaRecorderRef.current.stop();
    }
    setIsRecording(false);
    setAudioURL(null);
  };

  // Convert Blob to File
  const blobToFile = (blob: Blob, fileName: string): File => {
    return new File([blob], fileName, { type: blob.type });
  };

  const handleSendMessage = async () => {
    if (newMessage.trim() === '' && !audioURL) return;
    
    if (audioURL) {
      // For voice message
      try {
        const response = await fetch(audioURL);
        const audioBlob = await response.blob();
        const audioFile = blobToFile(audioBlob, `voice-message-${Date.now()}.mp3`);
        
        // Update UI immediately with voice message
        dispatch(updateMessages({ 
          message: "Voice message",
          attachment: audioURL
        }));
        
        // Send to server
        dispatch(sendMessageReply({
          message: "Voice message",
          chat_thread_id: Number(id),
          attachment: audioFile
        }));
        
        // Clear audio
        setAudioURL(null);
      } catch (err) {
        console.error('Error sending voice message:', err);
      }
    } else {
      // For text message
      dispatch(updateMessages({ message: newMessage }));

      const newData = {
        message: newMessage,
        chat_thread_id: Number(id)
      };
      
      dispatch(sendMessageReply(newData));
      setNewMessage('');
    }
  };

  const handleBack = () => {
    navigate('/messages');
  };
  console.log(singlemessage)

  return (
    <div className="h-[84vh] mt-[90px] md:mt-[20px] flex flex-col bg-amber-50 rounded-lg shadow-md mx-3 md:mx-auto mb-3 max-w-4xl">
      {/* Header */}
      <div className="bg-white p-3 flex items-center justify-between shadow-sm rounded-t-lg">
        <div className="flex items-center">
          <button 
            onClick={handleBack}
            className="mr-2 p-1 rounded-full hover:bg-gray-100"
          >
            <ArrowLeft size={20} />
          </button>
          <div className="flex items-center">
            <div className="relative">
              <img 
                src={chat_receiver_photo || "/src/images/registration/profile.png"}
                alt={chat_receiver_name || "Loading"} 
                className="w-10 h-10 rounded-full object-cover"
                referrerPolicy="no-referrer"
              />
            </div>
            <div className="ml-3">
              <h3 className="font-medium">{chat_receiver_name || "Loading"} </h3>
            </div>
          </div>
        </div>
        <button className="p-2 rounded-full bg-primary text-white">
          <Phone size={18} />
        </button>
      </div>

      {/* Messages */}
      <div ref={messagesContainerRef} className="flex-1 p-4 overflow-y-auto">
        {singlemessage?.loading ? (
          <div className="h-full flex items-center justify-center">
            <MessageLoadingSpinner />
          </div>
        ) : singlemessage.error ? (
          <div className="h-full flex items-center justify-center text-red-500">
            {singlemessage.error}
          </div>
        ) : singlemessage?.messages && singlemessage.messages.length > 0 ? (
          [...singlemessage.messages].reverse().map(message => (
            <div 
              key={message.id} 
              className={`mb-4 flex ${parseInt(message.sender_user_id) === user?.id ? 'justify-end' : 'justify-start'}`}
            >
              <div 
                className={`max-w-[70%] p-3 rounded-lg ${
                  parseInt(message.sender_user_id) === user?.id 
                    ? 'bg-primary text-white rounded-br-none' 
                    : 'bg-white text-gray-800 rounded-bl-none'
                }`}
              >
                {message.attachment && message.attachment.includes('audio') ? (
                  <audio controls className="max-w-full">
                    <source src={message.attachment} type="audio/mp3" />
                    Your browser does not support the audio element.
                  </audio>
                ) : message.attachment ? (
                  <img 
                    src={message.attachment} 
                    alt="Attachment" 
                    className="rounded-lg max-w-full mb-2" 
                  />
                ) : null}
                <p className="whitespace-pre-line">{message.message}</p>
              </div>
            </div>
          ))
        ) : (
          <div className="h-full flex items-center justify-center text-gray-500">
            No messages yet. Start a conversation!
          </div>
        )}
      </div>

      {/* Audio Preview */}
      {audioURL && (
        <div className="p-2 bg-gray-100">
          <div className="flex items-center justify-between">
            <audio controls className="w-full max-w-[250px]">
              <source src={audioURL} type="audio/mp3" />
              Your browser does not support the audio element.
            </audio>
            <button 
              onClick={() => setAudioURL(null)}
              className="ml-2 bg-red-500 text-white rounded-full p-1"
            >
              <X size={16} />
            </button>
          </div>
        </div>
      )}

      {/* Message Input */}
      <div className="p-3 bg-white rounded-b-lg">
        {isRecording ? (
          <div className="flex items-center justify-between bg-blue-500 p-2 rounded-full text-white">
            <div className="flex items-center">
              <button 
                onClick={cancelRecording}
                className="p-1 text-white mr-2"
              >
                <X size={20} />
              </button>
              <div className="animate-pulse h-3 w-3 bg-red-500 rounded-full mr-2"></div>
              <span>{formatTime(recordingTime)}</span>
              <div className="ml-2 text-xs">
                {MAX_RECORDING_TIME - recordingTime}s left
              </div>
            </div>
            <button 
              onClick={stopRecording}
              className="p-1 text-white bg-blue-600 rounded-full"
            >
              <Send size={20} />
            </button>
          </div>
        ) : (
          <div className="flex items-center">
            <input
              type="text"
              placeholder="Message"
              className="flex-1 border rounded-full py-2 px-4 focus:outline-none focus:ring-1 focus:ring-primary"
              value={newMessage}
              onChange={(e) => setNewMessage(e.target.value)}
              onKeyPress={(e) => e.key === 'Enter' && handleSendMessage()}
              disabled={!!audioURL}
            />
            {!audioURL && (
              <button 
                className="p-2 ml-2 text-gray-500 hover:text-primary"
                onClick={startRecording}
              >
                <Mic size={20} />
              </button>
            )}
            <button 
              className="p-2 ml-1 bg-primary text-white rounded-full"
              onClick={handleSendMessage}
            >
              <Send size={20} />
            </button>
          </div>
        )}
      </div>
    </div>
  );
}