import { useEffect, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { motion, AnimatePresence } from 'framer-motion';
import { QDRing } from './client360/QDRing';
import { useSentinelStore } from '../../store/sentinelStore';
import { useSentinelWebSocket } from '../../shared/hooks/useSentinelWebSocket';
import styles from './ShowroomMode.module.css';

/**
 * ShowroomMode
 * Full-screen contextual Sentinel view. Route: /showroom
 * Activated by SentinelAlertBanner or direct broker intent.
 *
 * Broker sees:
 *   - Anonymized silhouette visualization (not raw CCTV)
 *   - Live QD Engagement ring + zone label + rising/falling
 *   - AI observation (plain English, e.g. "Visitor spent 3.2min in living room")
 *   - Two actions: Tag as New Lead | Match to Existing Client
 *   - Session timer
 *   - Session end → one-action summary card
 *
 * Broker never sees: MediaPipe processing, WebSocket status, CCTV feed URL,
 *   perception calibration controls, consent record IDs.
 */

type ShowroomPhase = 'live' | 'summary';

export default function ShowroomMode() {
  const navigate = useNavigate();
  const [phase, setPhase] = useState<ShowroomPhase>('live');
  const [elapsed, setElapsed] = useState(0);  // seconds
  const timerRef = useRef<ReturnType<typeof setInterval> | null>(null);

  const {
    isShowroomActive,
    setShowroomActive,
    clearPendingAlert,
  } = useSentinelStore();

  // Live Sentinel data from WebSocket (abstracted — no raw WS state in UI)
  const { session } = useSentinelWebSocket();

  // Session timer
  useEffect(() => {
    timerRef.current = setInterval(() => setElapsed(s => s + 1), 1000);
    return () => {
      if (timerRef.current) clearInterval(timerRef.current);
    };
  }, []);

  // End session → summary
  const handleEndSession = () => {
    if (timerRef.current) clearInterval(timerRef.current);
    setPhase('summary');
    setShowroomActive(false);
  };

  const handleExitShowroom = () => {
    clearPendingAlert();
    navigate('/pipeline');
  };

  const formatTime = (s: number) =>
    `${String(Math.floor(s / 60)).padStart(2, '0')}:${String(s % 60).padStart(2, '0')}`;

  return (
    <motion.div
      className={styles.root}
      initial={{ opacity: 0, scale: 1.04 }}
      animate={{ opacity: 1, scale: 1 }}
      exit={{ opacity: 0, scale: 0.96 }}
      transition={{ duration: 0.35, ease: [0.4, 0, 0.2, 1] }}
    >
      {/* ── Header bar ───────────────────────────────────── */}
      <div className={styles.topBar}>
        <div className={styles.liveIndicator}>
          <span className="live-dot" />
          <span className={styles.liveLabel}>LIVE SHOWROOM INTELLIGENCE</span>
          <span className={styles.timer}>{formatTime(elapsed)}</span>
        </div>
        <button className="btn-ghost" onClick={handleExitShowroom}>
          Exit Showroom
        </button>
      </div>

      <AnimatePresence mode="wait">
        {phase === 'live' && (
          <motion.div
            key="live"
            className={styles.liveContent}
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
          >
            {/* ── Two-column layout ─────────────────────── */}
            <div className={styles.twoCol}>
              {/* Left: Anonymized silhouette visualization */}
              <div className={`${styles.vizPanel} glass`}>
                <SilhouetteViz zone={session?.currentZone} />
              </div>

              {/* Right: QD Engagement */}
              <div className={`${styles.engagementPanel} glass`}>
                <span className={styles.engLabel}>QD ENGAGEMENT</span>
                <div className={styles.qdCentered}>
                  <QDRing
                    score={session?.qdScore ?? 0}
                    size={96}
                    strokeWidth={6}
                    showLabel
                  />
                </div>
                <span
                  className={styles.engTrend}
                  style={{
                    color: (session?.qdTrend ?? 0) >= 0
                      ? 'var(--color-green)' : 'var(--color-red)',
                  }}
                >
                  {(session?.qdTrend ?? 0) >= 0 ? '▲ RISING' : '▼ FALLING'}
                  {session?.currentZone && ` — ${session.currentZone}`}
                </span>
              </div>
            </div>

            {/* ── AI Observation ────────────────────────── */}
            {session?.aiObservation && (
              <motion.div
                className={`${styles.observationCard} glass-card`}
                initial={{ opacity: 0, y: 8 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: 0.2 }}
              >
                <span className={styles.aiStar}>✦ AI OBSERVATION</span>
                <p className={styles.observation}>{session.aiObservation}</p>
              </motion.div>
            )}

            {/* ── Actions ──────────────────────────────── */}
            <div className={styles.actions}>
              <button className="btn-primary" onClick={() => {/* open new lead modal */}}>
                Tag as New Lead
              </button>
              <button className="btn-ghost" onClick={() => {/* open match modal */}}>
                Match to Existing Client
              </button>
              <button
                className={styles.endBtn}
                onClick={handleEndSession}
              >
                End Session
              </button>
            </div>
          </motion.div>
        )}

        {/* ── Session summary ───────────────────────────── */}
        {phase === 'summary' && (
          <motion.div
            key="summary"
            className={styles.summaryContent}
            initial={{ opacity: 0, scale: 0.96 }}
            animate={{ opacity: 1, scale: 1 }}
            transition={{ duration: 0.3, ease: [0.4, 0, 0.2, 1] }}
          >
            <div className={`${styles.summaryCard} glass-heavy`}>
              <h2 className={styles.summaryTitle}>Session Complete</h2>
              <p className={styles.summaryDuration}>
                Duration: {formatTime(elapsed)}
              </p>
              {session?.peakQd && (
                <p className={styles.summaryStat}>
                  Peak engagement: QD {session.peakQd}
                </p>
              )}
              <div className={styles.summaryActions}>
                <button
                  className="btn-primary"
                  onClick={() => navigate('/pipeline/new')}
                >
                  Create Lead Profile
                </button>
                <button className="btn-ghost" onClick={handleExitShowroom}>
                  Return to Pipeline
                </button>
              </div>
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </motion.div>
  );
}

// ── Silhouette visualization (never raw CCTV) ─────────────────
function SilhouetteViz({ zone }: { zone?: string }) {
  return (
    <div className={styles.silhouetteWrap}>
      {/* Abstract silhouette SVG — represents presence, not identity */}
      <svg viewBox="0 0 120 180" className={styles.silhouette}>
        <ellipse cx="60" cy="35" rx="22" ry="28" fill="rgba(124,58,237,0.3)" />
        <path
          d="M20 170 Q30 100 60 90 Q90 100 100 170"
          fill="rgba(124,58,237,0.2)"
          stroke="rgba(124,58,237,0.5)"
          strokeWidth="1"
        />
      </svg>
      {zone && (
        <span className={styles.zoneLabel}>Zone: {zone}</span>
      )}
    </div>
  );
}
