import { useState, useRef, useCallback, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { OracleResultCard } from './OracleResultCard';
import styles from './OracleBar.module.css';

type QueryState = 'idle' | 'thinking' | 'result';

/**
 * OracleBar
 * The persistent natural-language prompt bar for Pillar 1.
 * UX Master Plan §4.5 choreography:
 *   - Bar expands 48px → 80px on focus (200ms)
 *   - Ghost-text autocomplete suggestion
 *   - "Thinking" state: Velocity logo pulses inside bar
 *   - Placeholder result card at opacity 0.3, scale 0.98 (layout reserved)
 *   - Response: stagger-fades each data row at 100ms intervals
 *   - Oracle machinery (canvas ID, fork/merge, schema catalog) NEVER shown
 */

const SUGGESTIONS = [
  'Which leads are closest to closing this week?',
  'Show me site visit trends for April',
  'Who hasn\'t been contacted in 7 days?',
  'What is the average QD score by project?',
];

export function OracleBar() {
  const [queryState, setQueryState] = useState<QueryState>('idle');
  const [query, setQuery] = useState('');
  const [isFocused, setIsFocused] = useState(false);
  const [suggestion, setSuggestion] = useState('');
  const [result, setResult] = useState<any>(null);
  const inputRef = useRef<HTMLTextAreaElement>(null);

  // Rotate ghost-text suggestions
  useEffect(() => {
    const idx = Math.floor(Math.random() * SUGGESTIONS.length);
    setSuggestion(SUGGESTIONS[idx]);
  }, []);

  const handleSubmit = useCallback(async () => {
    if (!query.trim() || queryState === 'thinking') return;
    setQueryState('thinking');
    setResult(null);

    try {
      const resp = await fetch('/api/oracle/query', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ query, context: 'command_pillar' }),
      });
      const data = await resp.json();
      setResult(data);
      setQueryState('result');
    } catch {
      setQueryState('idle');
    }
  }, [query, queryState]);

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSubmit();
    }
    if (e.key === 'Escape') {
      setIsFocused(false);
      inputRef.current?.blur();
    }
  };

  const handleReset = () => {
    setQuery('');
    setResult(null);
    setQueryState('idle');
    inputRef.current?.focus();
  };

  return (
    <div className={styles.wrapper}>
      {/* ── Prompt bar ─────────────────────────────────────── */}
      <motion.div
        className={`${styles.bar} ${isFocused ? styles.focused : ''} glass`}
        animate={{ height: isFocused ? 80 : 48 }}
        transition={{ duration: 0.2, ease: [0.4, 0, 0.2, 1] }}
      >
        {/* Velocity logo / thinking pulse */}
        <motion.div
          className={styles.logoMark}
          animate={queryState === 'thinking'
            ? { opacity: [0.4, 1, 0.4], scale: [0.95, 1.05, 0.95] }
            : { opacity: 1, scale: 1 }
          }
          transition={queryState === 'thinking'
            ? { duration: 1.5, repeat: Infinity }
            : { duration: 0.2 }
          }
        >
          <span>✦</span>
        </motion.div>

        {/* Text input */}
        <div className={styles.inputWrap}>
          {!query && !isFocused && (
            <span className={styles.ghostText}>{suggestion}</span>
          )}
          <textarea
            ref={inputRef}
            className={styles.input}
            value={query}
            onChange={e => setQuery(e.target.value)}
            onFocus={() => setIsFocused(true)}
            onBlur={() => !query && setIsFocused(false)}
            onKeyDown={handleKeyDown}
            placeholder=""
            rows={1}
            disabled={queryState === 'thinking'}
            aria-label="Ask Oracle anything about your pipeline"
          />
        </div>

        {/* Submit / clear */}
        <AnimatePresence mode="wait">
          {query && queryState !== 'thinking' && (
            <motion.button
              className={styles.submitBtn}
              onClick={handleSubmit}
              initial={{ scale: 0, opacity: 0 }}
              animate={{ scale: 1, opacity: 1 }}
              exit={{ scale: 0, opacity: 0 }}
              transition={{ type: 'spring', stiffness: 400, damping: 30 }}
              aria-label="Submit query"
            >
              ↵
            </motion.button>
          )}
          {(result || queryState === 'result') && (
            <motion.button
              className={styles.clearBtn}
              onClick={handleReset}
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              aria-label="Clear result"
            >
              ✕
            </motion.button>
          )}
        </AnimatePresence>
      </motion.div>

      {/* ── Placeholder card (layout reserved before content) ─ */}
      <AnimatePresence mode="wait">
        {queryState === 'thinking' && (
          <motion.div
            className={`${styles.placeholderCard} glass shimmer`}
            initial={{ opacity: 0, scale: 0.98 }}
            animate={{ opacity: 0.35, scale: 0.99 }}
            exit={{ opacity: 0 }}
            transition={{ duration: 0.2 }}
            aria-hidden
          />
        )}

        {/* ── Result card ──────────────────────────────────── */}
        {queryState === 'result' && result && (
          <OracleResultCard result={result} query={query} />
        )}
      </AnimatePresence>
    </div>
  );
}
