'use client';
import { useEffect, useRef } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { X, Mic, Volume2, Sparkles } from 'lucide-react';
import { type VoiceState } from './GeminiVoiceButton';
import WaveAnimation from './WaveAnimation';
import type { Message } from '@/utils/api';

interface Props {
  isOpen: boolean;
  voiceState: VoiceState;
  transcript: string;
  interimTranscript: string;
  audioLevel: number;
  recentMessages: Message[];
  onClose: () => void;
  onTap: () => void;
  clientName?: string;
}

const STATE_COLORS: Record<VoiceState, string> = {
  idle:      '#6366f1',
  listening: '#ef4444',
  thinking:  '#f59e0b',
  speaking:  '#3b82f6',
};

const STATE_LABELS: Record<VoiceState, string> = {
  idle:      'Tap mic to speak',
  listening: 'Listening...',
  thinking:  'James is thinking...',
  speaking:  'James is speaking...',
};

const STATE_ICONS: Record<VoiceState, React.ReactNode> = {
  idle:      <Mic className="w-5 h-5" />,
  listening: <Mic className="w-5 h-5" />,
  thinking:  <Sparkles className="w-5 h-5" />,
  speaking:  <Volume2 className="w-5 h-5" />,
};

export default function VoiceBottomSheet({
  isOpen, voiceState, transcript, interimTranscript, audioLevel,
  recentMessages, onClose, onTap, clientName = 'You'
}: Props) {
  const sheetRef   = useRef<HTMLDivElement>(null);
  const msgsEndRef = useRef<HTMLDivElement>(null);

  // Swipe down to close
  useEffect(() => {
    const el = sheetRef.current;
    if (!el) return;
    let startY = 0;
    const onTouchStart = (e: TouchEvent) => { startY = e.touches[0].clientY; };
    const onTouchEnd   = (e: TouchEvent) => { if (e.changedTouches[0].clientY - startY > 80) onClose(); };
    el.addEventListener('touchstart', onTouchStart, { passive: true });
    el.addEventListener('touchend',   onTouchEnd,   { passive: true });
    return () => { el.removeEventListener('touchstart', onTouchStart); el.removeEventListener('touchend', onTouchEnd); };
  }, [onClose]);

  // Auto-scroll messages
  useEffect(() => {
    msgsEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [recentMessages, transcript, interimTranscript]);

  const color = STATE_COLORS[voiceState];
  const lastFewMsgs = recentMessages.slice(-6);

  return (
    <AnimatePresence>
      {isOpen && (
        <>
          {/* Backdrop */}
          <motion.div
            initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}
            className="fixed inset-0 z-40"
            style={{ background: 'rgba(0,0,0,0.6)', backdropFilter: 'blur(12px)', WebkitBackdropFilter: 'blur(12px)' }}
            onClick={onClose}
          />

          {/* Sheet */}
          <motion.div
            ref={sheetRef}
            initial={{ y: '100%' }}
            animate={{ y: 0 }}
            exit={{ y: '100%' }}
            transition={{ type: 'spring', stiffness: 320, damping: 32 }}
            className="fixed bottom-0 left-0 right-0 z-50 flex flex-col"
            style={{
              maxHeight: '80vh',
              borderRadius: '24px 24px 0 0',
              background: 'var(--bg-card)',
              boxShadow: '0 -8px 40px rgba(0,0,0,0.25)',
            }}>

            {/* Drag handle */}
            <div className="flex justify-center pt-3 pb-1 flex-shrink-0">
              <div className="w-10 h-1 rounded-full" style={{ background: 'var(--border)' }} />
            </div>

            {/* Header */}
            <div className="flex items-center justify-between px-5 py-2 flex-shrink-0">
              <div className="flex items-center gap-3">
                <motion.div
                  animate={{ background: color }}
                  transition={{ duration: 0.3 }}
                  className="w-9 h-9 rounded-full flex items-center justify-center text-white">
                  {STATE_ICONS[voiceState]}
                </motion.div>
                <div>
                  <p className="text-sm font-bold" style={{ color: 'var(--text-primary)' }}>James Cole</p>
                  <motion.p key={voiceState} initial={{ opacity: 0 }} animate={{ opacity: 1 }}
                    className="text-xs font-medium" style={{ color }}>
                    {STATE_LABELS[voiceState]}
                  </motion.p>
                </div>
              </div>
              <button onClick={onClose}
                className="w-8 h-8 rounded-full flex items-center justify-center"
                style={{ background: 'var(--bg-secondary)' }}>
                <X className="w-4 h-4" style={{ color: 'var(--text-secondary)' }} />
              </button>
            </div>

            {/* Conversation history */}
            <div className="flex-1 overflow-y-auto px-4 py-2 space-y-3 min-h-0">
              {lastFewMsgs.map((msg, i) => (
                <motion.div key={i}
                  initial={{ opacity: 0, y: 8 }} animate={{ opacity: 1, y: 0 }}
                  className={`flex ${msg.role === 'user' ? 'justify-end' : 'justify-start'} gap-2`}>
                  {msg.role === 'assistant' && (
                    <div className="w-6 h-6 rounded-full flex items-center justify-center text-white text-xs font-bold flex-shrink-0 mt-0.5"
                      style={{ background: 'linear-gradient(135deg, #6366f1, #a855f7)' }}>J</div>
                  )}
                  <div className={msg.role === 'user' ? 'msg-user text-sm' : 'msg-ai text-sm'}
                    style={{ maxWidth: '80%', padding: '8px 12px' }}>
                    {msg.content}
                  </div>
                </motion.div>
              ))}

              {/* Live transcript */}
              <AnimatePresence>
                {(transcript || interimTranscript) && (
                  <motion.div initial={{ opacity: 0, y: 8 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0 }}
                    className="flex justify-end">
                    <div className="rounded-2xl px-3 py-2 text-sm text-white"
                      style={{ background: 'rgba(99,102,241,0.6)', maxWidth: '80%' }}>
                      {transcript || interimTranscript}
                      {interimTranscript && <span className="inline-block w-0.5 h-3.5 ml-0.5 bg-white animate-pulse" />}
                    </div>
                  </motion.div>
                )}
              </AnimatePresence>

              {/* Thinking indicator */}
              {voiceState === 'thinking' && (
                <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="flex items-center gap-2">
                  <div className="w-6 h-6 rounded-full flex items-center justify-center text-white text-xs font-bold"
                    style={{ background: 'linear-gradient(135deg, #6366f1, #a855f7)' }}>J</div>
                  <div className="msg-ai flex items-center gap-1.5 py-2 px-3">
                    <div className="typing-dot" /><div className="typing-dot" style={{ animationDelay: '0.2s' }} /><div className="typing-dot" style={{ animationDelay: '0.4s' }} />
                  </div>
                </motion.div>
              )}
              <div ref={msgsEndRef} />
            </div>

            {/* Wave + Button */}
            <div className="flex-shrink-0 flex flex-col items-center py-4 gap-3"
              style={{ borderTop: '1px solid var(--border)' }}>
              {/* Wave animation */}
              <AnimatePresence>
                {(voiceState === 'listening' || voiceState === 'speaking') && (
                  <motion.div initial={{ opacity: 0, scaleY: 0 }} animate={{ opacity: 1, scaleY: 1 }} exit={{ opacity: 0, scaleY: 0 }}>
                    <WaveAnimation isActive={true} audioLevel={audioLevel} barCount={24} />
                  </motion.div>
                )}
              </AnimatePresence>

              {/* Big voice button */}
              <motion.button
                onClick={onTap}
                whileTap={{ scale: 0.92 }}
                className="relative flex items-center justify-center rounded-full text-white"
                style={{
                  width: 72, height: 72,
                  background: `linear-gradient(135deg, ${color}, ${color}cc)`,
                  boxShadow: `0 8px 32px ${color}60`,
                }}>
                {/* Pulse ring when listening */}
                {voiceState === 'listening' && (
                  <motion.div className="absolute inset-0 rounded-full"
                    animate={{ scale: [1, 1.4], opacity: [0.5, 0] }}
                    transition={{ duration: 1.2, repeat: Infinity }}
                    style={{ background: color }} />
                )}
                <motion.div key={voiceState} initial={{ scale: 0 }} animate={{ scale: 1 }}
                  transition={{ type: 'spring', stiffness: 400, damping: 20 }}>
                  {STATE_ICONS[voiceState]}
                </motion.div>
              </motion.button>

              <p className="text-xs font-medium" style={{ color: 'var(--text-secondary)' }}>
                {voiceState === 'listening' ? 'Tap to stop • Swipe down to close' : STATE_LABELS[voiceState]}
              </p>
            </div>

            {/* Safe area */}
            <div className="safe-bottom flex-shrink-0" />
          </motion.div>
        </>
      )}
    </AnimatePresence>
  );
}
