import React, { useState } from 'react';
import styles from './MonitoringPage.module.css';

/**
 * HELPER: Unified sender function
 * In a real app, you might move this to a /services or /hooks folder
 */
const sendUserInterrupt = async (type: string, context: string) => {
  try {
    const response = await fetch("http://localhost:8000/button_pressed", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ type, context }),
    });
    if (!response.ok) throw new Error("Backend response error");
    console.log(`Interrupt Sent - Type: ${type}, Context: ${context}`);
  } catch (err) {
    console.error(`Failed to send interrupt:`, err);
  }
};

// --- GESTURE COMPONENT ---
export const GestureControls: React.FC = () => {
  const [selectedGesture, setSelectedGesture] = useState("animations/Stand/BodyTalk/Speaking/BodyTalk_1");

  const gestures = [
    { label: "Body Talk 1", value: "animations/Stand/BodyTalk/Speaking/BodyTalk_1" },
    { label: "Thinking 8", value: "animations/Stand/Gestures/Thinking_8" },
    { label: "Thinking 1", value: "animations/Stand/Gestures/Thinking_1" },
    { label: "Happy", value: "animations/Stand/Emotions/Positive/Happy_1" },
  ];

  return (
    <div className={styles.gestures}>
      <h4>Gestures</h4>
      <div className={styles.gestureInputGroup}>
        <select 
          value={selectedGesture} 
          onChange={(e) => setSelectedGesture(e.target.value)}
        >
          {gestures.map(g => <option key={g.value} value={g.value}>{g.label}</option>)}
        </select>
        <button onClick={() => sendUserInterrupt("gesture", selectedGesture)}>
          Actuate
        </button>
      </div>
    </div>
  );
};

// --- PRESET SPEECH COMPONENT ---
export const SpeechPresets: React.FC = () => {
  const phrases = [
    { label: "Hello, I'm Pepper", text: "Hello, I'm Pepper" },
    { label: "Repeat please", text: "Could you repeat that please" },
    { label: "About yourself", text: "Tell me something about yourself" },
  ];

  return (
    <div className={styles.speech}>
      <h4>Speech Presets</h4>
      <ul>
        {phrases.map((phrase, i) => (
          <li key={i}>
            <button 
              className={styles.speechBtn} 
              onClick={() => sendUserInterrupt("speech", phrase.text)}
            >
              "{phrase.label}"
            </button>
          </li>
        ))}
      </ul>
    </div>
  );
};

// --- DIRECT SPEECH (INPUT) COMPONENT ---
export const DirectSpeechInput: React.FC = () => {
  const [text, setText] = useState("");

  const handleSend = () => {
    if (!text.trim()) return;
    sendUserInterrupt("speech", text);
    setText(""); // Clear after sending
  };

  return (
    <div className={styles.directSpeech}>
      <h4>Direct Pepper Speech</h4>
      <div className={styles.speechInput}>
        <input 
          type="text" 
          value={text}
          onChange={(e) => setText(e.target.value)}
          placeholder="Type message..." 
          onKeyDown={(e) => e.key === 'Enter' && handleSend()}
        />
        <button onClick={handleSend}>Send</button>
      </div>
    </div>
  );
};

// --- interface for goals/triggers/norms/conditional norms ---
interface StatusListProps {
  title: string;
  items: any[];
  type: 'goal' | 'trigger' | 'norm'| 'cond_norm';
}

// --- STATUS LIST COMPONENT ---
export const StatusList: React.FC<StatusListProps> = ({ title, items, type }) => {
  return (
    <section className={styles.phaseBox}>
      <h3>{title}</h3>
      <ul>
        {items.length > 0 ? (
          items.map((item, idx) => {
            const isAchieved = item.achieved;
            const showIndicator = type !== 'norm';
            const canOverride = showIndicator && !isAchieved;

            return (
              <li key={item.id ?? idx} className={styles.statusItem}>
                {showIndicator && (
                  <span 
                    className={`${styles.statusIndicator} ${canOverride ? styles.clickable : ''}`}
                    onClick={() => canOverride && sendUserInterrupt("override", String(item.id))}
                    title={canOverride ? `Send override for ID: ${item.id}` : 'Achieved'}
                    style={{ cursor: canOverride ? 'pointer' : 'default' }}
                  >
                    {isAchieved ? "✔️" : "❌"}
                  </span>
                )}

                <span className={styles.itemDescription}>
                  {item.description || item.label || item.norm}
                </span>
              </li>
            );
          })
        ) : (
          <p className={styles.emptyText}>No {title.toLowerCase()} defined.</p>
        )}
      </ul>
    </section>
  );
};