import { useState, useRef } from 'react';
import { motion } from 'framer-motion';
import { useConversations } from '@/shared/hooks/useClient360';
import styles from './Conversations.module.css';

/**
 * Conversations Tab
 * Unified chronological feed: WhatsApp threads + call records + emails.
 * All in one scroll — no navigation to separate Comms module ever needed.
 * WhatsApp threads render inline with reply. Calls show key moments.
 */

interface ConversationsTabProps {
  personId: string;
}

type EventType = 'whatsapp' | 'call' | 'email';

interface ConvEvent {
  id: string;
  type: EventType;
  timestamp: string;
  timestampRelative: string;
  // WhatsApp
  messages?: { sender: 'client' | 'you'; text: string; status?: '✓' | '✓✓' }[];
  // Call
  duration?: string;
  direction?: 'inbound' | 'outbound';
  keyMoments?: string[];
  hasTranscript?: boolean;
  // Email
  subject?: string;
  preview?: string;
}

export function ConversationsTab({ personId }: ConversationsTabProps) {
  const { events, isLoading, sendWhatsApp } = useConversations(personId);
  const [replyText, setReplyText] = useState('');
  const [replyingToId, setReplyingToId] = useState<string | null>(null);

  if (isLoading) {
    return (
      <div className={styles.root}>
        {[0, 1, 2].map(i => (
          <div key={i} className={`${styles.skeleton} shimmer`} />
        ))}
      </div>
    );
  }

  return (
    <div className={styles.root}>
      {events.map((event, i) => (
        <motion.div
          key={event.id}
          className={`${styles.eventCard} glass-card`}
          initial={{ opacity: 0, y: 12 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: i * 0.06, duration: 0.25 }}
        >
          {/* Event header */}
          <div className={styles.eventHeader}>
            <span className={styles.channelBadge}
              data-type={event.type}>
              {event.type === 'whatsapp' ? '💬 WhatsApp'
               : event.type === 'call' ? '📞 Call'
               : '✉️ Email'}
            </span>
            <span className={styles.timestamp}>{event.timestampRelative}</span>
          </div>

          {/* WhatsApp thread */}
          {event.type === 'whatsapp' && event.messages && (
            <div className={styles.thread}>
              {event.messages.map((msg, mi) => (
                <div
                  key={mi}
                  className={`${styles.bubble} ${msg.sender === 'you' ? styles.outbound : styles.inbound}`}
                >
                  <span className={styles.bubbleText}>{msg.text}</span>
                  {msg.sender === 'you' && msg.status && (
                    <span className={styles.status}>{msg.status}</span>
                  )}
                </div>
              ))}
              {/* Inline reply */}
              {replyingToId === event.id ? (
                <div className={styles.replyBox}>
                  <input
                    value={replyText}
                    onChange={e => setReplyText(e.target.value)}
                    placeholder="Type a reply…"
                    className={styles.replyInput}
                    autoFocus
                    onKeyDown={e => {
                      if (e.key === 'Enter' && replyText.trim()) {
                        sendWhatsApp(replyText);
                        setReplyText('');
                        setReplyingToId(null);
                      }
                    }}
                  />
                  <button className="btn-primary" onClick={() => {
                    if (replyText.trim()) { sendWhatsApp(replyText); setReplyText(''); setReplyingToId(null); }
                  }}>Send</button>
                  <button className="btn-ghost" onClick={() => setReplyingToId(null)}>Cancel</button>
                </div>
              ) : (
                <div className={styles.threadActions}>
                  <button className="btn-ghost" onClick={() => setReplyingToId(event.id)}>
                    Reply in WhatsApp
                  </button>
                  <button className="btn-ghost">AI ✦ Summarize</button>
                </div>
              )}
            </div>
          )}

          {/* Call record */}
          {event.type === 'call' && (
            <div className={styles.callRecord}>
              <div className={styles.callMeta}>
                <span>{event.direction === 'inbound' ? '↙ Inbound' : '↗ Outbound'}</span>
                {event.duration && <span>· {event.duration}</span>}
                {event.hasTranscript && <span>· Transcript available</span>}
              </div>
              {event.keyMoments && event.keyMoments.length > 0 && (
                <div className={styles.keyMoments}>
                  <span className={styles.kmLabel}>Key moments:</span>
                  {event.keyMoments.map((m, mi) => (
                    <span key={mi} className={styles.kmChip}>{m}</span>
                  ))}
                </div>
              )}
              {event.hasTranscript && (
                <div className={styles.callActions}>
                  <button className="btn-ghost">Read Transcript</button>
                  <button className="btn-ghost">View Extracted Facts</button>
                </div>
              )}
            </div>
          )}
        </motion.div>
      ))}
    </div>
  );
}
