import React, { useState, useEffect } from 'react';
import axios from 'axios';
import SpeechRecognition, { useSpeechRecognition } from 'react-speech-recognition';
import { v4 as uuidv4 } from 'uuid';

const ChatBox = () => {
  const [sessionId] = useState(uuidv4());
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState('');
  const [isTyping, setIsTyping] = useState(false);

  const { transcript, listening, resetTranscript, browserSupportsSpeechRecognition } = useSpeechRecognition();

  // 🧠 Speak the AI reply using Web Speech API
  const speak = (text) => {
    const utterance = new SpeechSynthesisUtterance(text);
    utterance.lang = 'en-US';
    speechSynthesis.speak(utterance);
  };

  // 📨 Send message to backend
  const sendMessage = async (msg) => {
    if (!msg.trim()) return;

    setMessages((prev) => [...prev, { sender: 'You', text: msg }]);
    setInput('');
    setIsTyping(true);

    try {
      const res = await axios.post('http://localhost:8080/chat', {
        session_id: sessionId,
        message: msg
      });

      const aiReply = res.data.response;
      setIsTyping(false);
      setMessages((prev) => [...prev, { sender: 'AI', text: aiReply }]);
      speak(aiReply);
    } catch (err) {
      setIsTyping(false);
      const errorMsg = 'Error: ' + (err.message || 'Network Error');
      setMessages((prev) => [...prev, { sender: 'AI', text: errorMsg }]);
      speak(errorMsg);
    }
  };

  const handleVoiceSend = () => {
    if (transcript.trim()) {
      sendMessage(transcript);
      resetTranscript();
    }
  };

  const handleTextSend = () => {
    sendMessage(input);
  };

  // Auto-scroll to bottom when new messages arrive
  useEffect(() => {
    const chatContainer = document.getElementById('chat-container');
    if (chatContainer) {
      chatContainer.scrollTop = chatContainer.scrollHeight;
    }
  }, [messages]);

  return (
    <div style={{
      maxWidth: 800,
      margin: '40px auto',
      fontFamily: '"Poppins", sans-serif',
      background: 'linear-gradient(135deg, #f5f7fa 0%, #e4edf5 100%)',
      padding: '30px',
      borderRadius: '20px',
      boxShadow: '0 12px 24px rgba(0, 0, 0, 0.1)'
    }}>
      <h1 style={{
        color: '#2a6dd7',
        textAlign: 'center',
        margin: '0 0 20px',
        fontSize: '28px',
        fontWeight: '700',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        gap: '10px'
      }}>
        <span style={{ fontSize: '32px' }}>🎙️</span> 
        Voice Chat with Gemini AI
      </h1>

      <div id="chat-container" style={{
        height: 400, 
        overflowY: 'auto',
        border: 'none',
        padding: '20px',
        marginBottom: '20px',
        background: 'rgba(255, 255, 255, 0.8)',
        borderRadius: '16px',
        boxShadow: 'inset 0 2px 10px rgba(0, 0, 0, 0.05)'
      }}>
        {messages.map((msg, idx) => (
          <div key={idx} style={{
            display: 'flex',
            flexDirection: 'column',
            alignItems: msg.sender === 'You' ? 'flex-end' : 'flex-start',
            marginBottom: '15px'
          }}>
            <div style={{
              maxWidth: '70%',
              padding: '12px 16px',
              borderRadius: msg.sender === 'You' ? '18px 18px 0 18px' : '18px 18px 18px 0',
              background: msg.sender === 'You' ? '#2a6dd7' : '#f0f4f9',
              color: msg.sender === 'You' ? 'white' : '#333',
              boxShadow: '0 2px 5px rgba(0, 0, 0, 0.1)',
              wordBreak: 'break-word',
              lineHeight: '1.4'
            }}>
              {msg.text}
            </div>
            <span style={{
              fontSize: '12px',
              color: '#888',
              marginTop: '4px',
              fontWeight: '500'
            }}>
              {msg.sender}
            </span>
          </div>
        ))}
        {isTyping && (
          <div style={{
            display: 'flex',
            alignItems: 'flex-start',
            marginBottom: '15px'
          }}>
            <div style={{
              padding: '12px 16px',
              borderRadius: '18px 18px 18px 0',
              background: '#f0f4f9',
              color: '#333',
              boxShadow: '0 2px 5px rgba(0, 0, 0, 0.1)'
            }}>
              <div style={{ display: 'flex', gap: '4px', alignItems: 'center' }}>
                <div className="typing-dot" style={{ 
                  height: '8px', 
                  width: '8px', 
                  borderRadius: '50%', 
                  background: '#2a6dd7',
                  animation: 'typingAnimation 1s infinite 0s'
                }}></div>
                <div className="typing-dot" style={{ 
                  height: '8px', 
                  width: '8px', 
                  borderRadius: '50%', 
                  background: '#2a6dd7',
                  animation: 'typingAnimation 1s infinite 0.2s'
                }}></div>
                <div className="typing-dot" style={{ 
                  height: '8px', 
                  width: '8px', 
                  borderRadius: '50%', 
                  background: '#2a6dd7',
                  animation: 'typingAnimation 1s infinite 0.4s'
                }}></div>
              </div>
            </div>
            <span style={{
              fontSize: '12px',
              color: '#888',
              marginTop: '4px',
              marginLeft: '4px',
              fontWeight: '500'
            }}>
              AI is typing...
            </span>
          </div>
        )}
      </div>

      <div style={{ display: 'flex', gap: '10px', marginBottom: '20px' }}>
        <input
          style={{
            flex: 1,
            padding: '14px 20px',
            borderRadius: '30px',
            border: '2px solid #e1e8ef',
            outline: 'none',
            fontSize: '16px',
            transition: 'all 0.3s ease',
            boxShadow: '0 2px 5px rgba(0, 0, 0, 0.05)'
          }}
          value={input}
          onChange={(e) => setInput(e.target.value)}
          onKeyDown={(e) => e.key === 'Enter' && handleTextSend()}
          placeholder="Type your message..."
        />
        <button 
          onClick={handleTextSend}
          style={{
            background: '#2a6dd7',
            color: 'white',
            border: 'none',
            borderRadius: '30px',
            padding: '14px 24px',
            cursor: 'pointer',
            fontWeight: 'bold',
            transition: 'all 0.3s ease',
            boxShadow: '0 4px 10px rgba(42, 109, 215, 0.3)'
          }}
        >
          Send
        </button>
      </div>

      <div style={{ 
        marginTop: '15px',
        background: 'rgba(255, 255, 255, 0.7)',
        padding: '20px',
        borderRadius: '16px',
        boxShadow: '0 2px 10px rgba(0, 0, 0, 0.05)'
      }}>
        {!browserSupportsSpeechRecognition ? (
          <p style={{ color: '#e74c3c', textAlign: 'center' }}>
            🎙️ Your browser doesn't support speech recognition.
          </p>
        ) : (
          <>
            <div style={{ 
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'center',
              marginBottom: '15px'
            }}>
              <p style={{ 
                margin: 0,
                display: 'flex',
                alignItems: 'center',
                gap: '8px',
                color: listening ? '#2ecc71' : '#7f8c8d',
                fontWeight: '600'
              }}>
                <span style={{ fontSize: '22px' }}>🎤</span> 
                {listening ? 'Listening...' : 'Mic ready'}
              </p>
              <div style={{ display: 'flex', gap: '10px' }}>
                <button 
                  onClick={SpeechRecognition.startListening}
                  style={{
                    background: listening ? '#e0f7ea' : '#4cd964',
                    color: listening ? '#2ecc71' : 'white',
                    border: 'none',
                    borderRadius: '30px',
                    padding: '8px 15px',
                    cursor: 'pointer',
                    fontWeight: '600',
                    transition: 'all 0.3s ease',
                    opacity: listening ? 0.7 : 1
                  }}
                  disabled={listening}
                >
                  Start
                </button>
                <button 
                  onClick={SpeechRecognition.stopListening}
                  style={{
                    background: listening ? '#e74c3c' : '#ffeded',
                    color: listening ? 'white' : '#e74c3c',
                    border: 'none',
                    borderRadius: '30px',
                    padding: '8px 15px',
                    cursor: 'pointer',
                    fontWeight: '600',
                    transition: 'all 0.3s ease',
                    opacity: !listening ? 0.7 : 1
                  }}
                  disabled={!listening}
                >
                  Stop
                </button>
                <button 
                  onClick={handleVoiceSend}
                  style={{
                    background: transcript.trim() ? '#2a6dd7' : '#e4edf5',
                    color: transcript.trim() ? 'white' : '#aaa',
                    border: 'none',
                    borderRadius: '30px',
                    padding: '8px 15px',
                    cursor: transcript.trim() ? 'pointer' : 'not-allowed',
                    fontWeight: '600',
                    transition: 'all 0.3s ease',
                    boxShadow: transcript.trim() ? '0 4px 10px rgba(42, 109, 215, 0.3)' : 'none'
                  }}
                  disabled={!transcript.trim()}
                >
                  Send Voice
                </button>
              </div>
            </div>
            
            {transcript && (
              <div style={{ 
                background: 'rgba(255, 255, 255, 0.7)',
                padding: '15px',
                borderRadius: '12px',
                border: '1px dashed #2a6dd7',
                marginTop: '10px'
              }}>
                <p style={{ margin: 0, color: '#444', fontWeight: '500' }}>
                  <strong style={{ color: '#2a6dd7' }}>You said:</strong> {transcript}
                </p>
              </div>
            )}
          </>
        )}
      </div>
      
      <style>
        {`
          @keyframes typingAnimation {
            0% { opacity: 0.3; transform: translateY(0px); }
            50% { opacity: 1; transform: translateY(-2px); }
            100% { opacity: 0.3; transform: translateY(0px); }
          }
          
          button:hover:not(:disabled) {
            transform: translateY(-2px);
            filter: brightness(1.05);
          }
          
          button:active:not(:disabled) {
            transform: translateY(0);
          }
          
          input:focus {
            border-color: #2a6dd7;
            box-shadow: 0 0 0 3px rgba(42, 109, 215, 0.2);
          }
          
          /* For a nice scrollbar */
          #chat-container::-webkit-scrollbar {
            width: 8px;
          }
          
          #chat-container::-webkit-scrollbar-track {
            background: rgba(0, 0, 0, 0.05);
            border-radius: 10px;
          }
          
          #chat-container::-webkit-scrollbar-thumb {
            background: rgba(42, 109, 215, 0.3);
            border-radius: 10px;
          }
          
          #chat-container::-webkit-scrollbar-thumb:hover {
            background: rgba(42, 109, 215, 0.5);
          }
        `}
      </style>
    </div>
  );
};

export default ChatBox; , make ui perfect level make more relevent ui ux better it