import { useState, useEffect, useRef } from 'react';
import axios from 'axios';

const API_URL = 'http://localhost:3001/api';

function GoddessChat({ onComplete }) {
  const [conversationId, setConversationId] = useState(null);
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState('');
  const [playerName, setPlayerName] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [goddessState, setGoddessState] = useState(null);
  const [gamePhase, setGamePhase] = useState('name');

  const messagesEndRef = useRef(null);
  const inputRef = useRef(null);

  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  useEffect(() => {
    if (goddessState) {
      updateGamePhase(goddessState);
    }
  }, [goddessState]);

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };

  const startConversation = async () => {
    try {
      const res = await axios.post(`${API_URL}/goddess/start`);
      setConversationId(res.data.conversationId);
    } catch (err) {
      console.error('Failed to start:', err);
    }
  };

  const sendMessage = async (customMessage = null) => {
    const messageToSend = customMessage || input;
    if (!messageToSend.trim() || !conversationId || isLoading) return;

    setIsLoading(true);
    setMessages(prev => [...prev, { role: 'player', content: messageToSend }]);
    setInput('');

    try {
      // Send CURRENT state (after any updates from handleItemSelect, handleBlessingChoice, etc.)
      console.log('[UI] Sending message with currentState:', {
        blessingAccepted: goddessState?.blessingAccepted,
        item: goddessState?.item?.name,
        itemOptions: goddessState?.itemOptions?.length
      });
      
      const res = await axios.post(`${API_URL}/goddess/chat`, {
        conversationId,
        message: messageToSend,
        playerName: playerName || undefined,
        currentState: goddessState // Send the CURRENT state
      });

      console.log('[UI] Received response, new state:', {
        blessingAccepted: res.data.state?.blessingAccepted,
        item: res.data.state?.item?.name,
        world: res.data.state?.world?.title
      });

      setMessages(prev => [...prev, { role: 'goddess', content: res.data.response }]);
      setGoddessState(res.data.state);

      if (res.data.ready) {
        handleComplete(res.data.state);
      }
    } catch (err) {
      console.error('Goddess chat error:', err);
      setMessages(prev => [...prev, { 
        role: 'goddess', 
        content: '*The goddess seems distant for a moment...*' 
      }]);
    } finally {
      setIsLoading(false);
    }
  };

  const handleComplete = (state) => {
    onComplete({
      playerName: state.playerName || playerName,
      blessing: state.blessing,
      item: state.item,
      world: state.world,
      prophecy: state.prophecy,
      playerAnswers: state.playerAnswers
    });
  };

  const handleNameSubmit = () => {
    if (!playerName.trim()) return;
    startConversation();
    
    const greeting = `*[A luminous figure materializes before you, her form shifting between countless aspects. Stars swirl in her eyes.]*

"I am Aethera," she speaks, and her words resonate in your very soul. "Keeper of the Cycle, Guide of Transmigrating Souls."

She regards you with warmth beyond measure.

"Welcome, **${playerName}**. Your previous journey has ended... but here, a new story awaits."

The goddess extends her hand.

"Tell me... what do you seek in this new existence?"`;
    
    setMessages([{ role: 'goddess', content: greeting }]);
    setGamePhase('chat');
    setInput('');
    setTimeout(() => inputRef.current?.focus(), 100);
  };

  const handleBlessingChoice = (choice) => {
    console.log('[UI] Blessing choice:', choice);
    
    if (choice === 'accept') {
      // Update state FIRST, then send message with new state
      const newState = { ...goddessState, blessingAccepted: true };
      setGoddessState(newState);
      
      // Send message WITH the updated state
      sendAcceptanceMessage(newState);
    } else if (choice === 'decline') {
      sendMessage('Could I have a different blessing? I was hoping for something more suited to my needs.');
    } else if (choice === 'custom') {
      setInput('I was hoping for a blessing that ');
      inputRef.current?.focus();
    }
  };

  const sendAcceptanceMessage = async (stateWithAcceptance) => {
    const message = 'I accept this blessing.';
    if (!message.trim() || !conversationId || isLoading) return;

    setIsLoading(true);
    setMessages(prev => [...prev, { role: 'player', content: message }]);

    try {
      console.log('[UI] Sending acceptance with blessingAccepted:', stateWithAcceptance.blessingAccepted);
      
      const res = await axios.post(`${API_URL}/goddess/chat`, {
        conversationId,
        message: message,
        playerName: playerName || undefined,
        currentState: stateWithAcceptance // Send state WITH blessingAccepted = true
      });

      console.log('[UI] Received response, new state:', {
        blessingAccepted: res.data.state?.blessingAccepted,
        itemOptions: res.data.state?.itemOptions?.length
      });

      setMessages(prev => [...prev, { role: 'goddess', content: res.data.response }]);
      setGoddessState(res.data.state);

      if (res.data.ready) {
        handleComplete(res.data.state);
      }
    } catch (err) {
      console.error('Goddess chat error:', err);
    } finally {
      setIsLoading(false);
    }
  };

  const handleItemSelect = (item) => {
    console.log('[UI] Item selected:', item.name);
    
    // Update state FIRST
    const newState = { 
      ...goddessState, 
      item: item,
      itemOptions: null 
    };
    setGoddessState(newState);
    
    // Send message WITH updated state
    sendItemSelectionMessage(newState, item);
  };

  const sendItemSelectionMessage = async (stateWithItem, item) => {
    const message = `I choose the ${item.name}.`;
    if (!message.trim() || !conversationId || isLoading) return;

    setIsLoading(true);
    setMessages(prev => [...prev, { role: 'player', content: message }]);

    try {
      console.log('[UI] Sending item selection with item:', stateWithItem.item.name);
      
      const res = await axios.post(`${API_URL}/goddess/chat`, {
        conversationId,
        message: message,
        playerName: playerName || undefined,
        currentState: stateWithItem // Send state WITH item set
      });

      console.log('[UI] Received response, new state:', {
        item: res.data.state?.item?.name,
        world: res.data.state?.world?.title
      });

      setMessages(prev => [...prev, { role: 'goddess', content: res.data.response }]);
      setGoddessState(res.data.state);

      if (res.data.ready) {
        handleComplete(res.data.state);
      }
    } catch (err) {
      console.error('Goddess chat error:', err);
    } finally {
      setIsLoading(false);
    }
  };

  const handleCustomItemRequest = () => {
    setGoddessState(prev => ({ ...prev, itemOptions: null }));
    setInput('Could I have something else? I was thinking of ');
    inputRef.current?.focus();
  };

  const updateGamePhase = (state) => {
    console.log('[UI] State update:', {
      blessingOffer: state.blessingOffer,
      blessingAccepted: state.blessingAccepted,
      itemOptions: state.itemOptions?.length,
      item: state.item?.name,
      world: state.world?.title,
      prophecy: state.prophecy
    });
    
    if (state.blessingOffer && !state.blessingAccepted) {
      setGamePhase('blessing');
    } else if (state.itemOptions && state.itemOptions.length > 0 && !state.item) {
      setGamePhase('items');
    } else if (state.ready) {
      setGamePhase('complete');
    } else {
      setGamePhase('chat');
    }
  };

  const handleKeyDown = (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      sendMessage();
    }
  };

  return (
    <div className="goddess-chat-container">
      <div className="goddess-chat-background">
        <div className="floating-particles">
          {[...Array(40)].map((_, i) => (
            <div key={i} className="particle" style={{
              left: `${Math.random() * 100}%`,
              top: `${Math.random() * 100}%`,
              animationDelay: `${Math.random() * 5}s`,
              animationDuration: `${3 + Math.random() * 4}s`
            }} />
          ))}
        </div>
      </div>

      <div className="goddess-chat-content">
        <div className="goddess-chat-header">
          <div className="goddess-avatar-large">🌙</div>
          <div>
            <h2 className="goddess-chat-title">Aethera</h2>
            <p className="goddess-chat-subtitle">Goddess of Reincarnation</p>
          </div>
          <div className="phase-indicator">
            {gamePhase === 'name' ? 'Enter Your Name' :
             gamePhase === 'chat' ? 'Speaking with the Goddess' :
             gamePhase === 'blessing' ? 'Choose Your Blessing' :
             gamePhase === 'items' ? 'Select Starting Item' :
             gamePhase === 'complete' ? 'Ready to Begin' : 'Reincarnation'}
          </div>
        </div>

        <div className="goddess-messages">
          {messages.map((msg, idx) => (
            <div key={idx} className={`goddess-message ${msg.role}`}>
              <div className="message-avatar">
                {msg.role === 'goddess' ? '🌙' : '👤'}
              </div>
              <div className={`message-bubble ${msg.role}`}>
                <div style={{ whiteSpace: 'pre-wrap' }}>{msg.content}</div>
              </div>
            </div>
          ))}
          {isLoading && (
            <div className="goddess-message goddess">
              <div className="message-avatar">🌙</div>
              <div className="message-bubble goddess">
                <div className="typing-indicator">
                  <span></span><span></span><span></span>
                </div>
              </div>
            </div>
          )}
          <div ref={messagesEndRef} />
        </div>

        {/* Blessing Options */}
        {gamePhase === 'blessing' && (
          <div className="interaction-options">
            <p className="option-prompt">The goddess awaits your choice...</p>
            <div className="option-buttons">
              <button className="option-btn accept" onClick={() => handleBlessingChoice('accept')}>
                ✨ Accept Blessing
              </button>
              <button className="option-btn decline" onClick={() => handleBlessingChoice('decline')}>
                💬 Request Different
              </button>
              <button className="option-btn custom" onClick={() => handleBlessingChoice('custom')}>
                🎨 Describe Custom
              </button>
            </div>
          </div>
        )}

        {/* Item Selection */}
        {gamePhase === 'items' && goddessState?.itemOptions && (
          <div className="interaction-options items-panel">
            <p className="option-prompt">Choose your starting item (click to select):</p>
            <div className="item-cards">
              {goddessState.itemOptions.map((item, idx) => (
                <div key={idx} className="item-card" onClick={() => handleItemSelect(item)}>
                  <div className="item-card-icon">{item.icon || '📦'}</div>
                  <h4 className="item-card-name">{item.name}</h4>
                  <p className="item-card-desc">{item.description}</p>
                  {item.type && <span className="item-card-type">{item.type}</span>}
                </div>
              ))}
              <div className="item-card custom" onClick={handleCustomItemRequest}>
                <div className="item-card-icon">✨</div>
                <h4 className="item-card-name">Custom Request</h4>
                <p className="item-card-desc">Ask for something specific</p>
              </div>
            </div>
          </div>
        )}

        {/* Name Input */}
        {gamePhase === 'name' ? (
          <div className="name-input-container">
            <label className="name-label">
              <span className="label-icon">✨</span>
              The goddess awaits your name...
            </label>
            <div className="name-input-wrapper">
              <input
                type="text"
                className="fantasy-name-input"
                placeholder="Enter your name..."
                value={playerName}
                onChange={(e) => setPlayerName(e.target.value)}
                onKeyDown={(e) => e.key === 'Enter' && handleNameSubmit()}
                autoFocus
              />
              <button className="btn-submit-name" onClick={handleNameSubmit} disabled={!playerName.trim()}>
                Begin
              </button>
            </div>
          </div>
        ) : (
          <div className="goddess-input-container">
            <textarea
              ref={inputRef}
              className="goddess-input"
              rows="2"
              placeholder="Speak to the goddess..."
              value={input}
              onChange={(e) => setInput(e.target.value)}
              onKeyDown={handleKeyDown}
              disabled={isLoading || gamePhase === 'complete'}
            />
            <button
              className="goddess-send-btn"
              onClick={() => sendMessage()}
              disabled={isLoading || !input.trim() || gamePhase === 'complete'}
            >
              ✦
            </button>
          </div>
        )}

        <div className="goddess-hint">
          {gamePhase === 'name' 
            ? 'Enter your name to begin your reincarnation' 
            : 'Speak naturally. The goddess judges your character secretly.'}
        </div>
      </div>
    </div>
  );
}

export default GoddessChat;
