'use client';

import { useEffect, useRef } from 'react';
import { useTranslations } from 'next-intl';
import { motion, AnimatePresence, useMotionValue, useTransform } from 'framer-motion';
import { Mic, MicOff, PhoneOff, Loader2 } from 'lucide-react';
import { cn } from '@/lib/utils';
import { useVoiceAgent, type TranscriptEntry } from './VoiceAgentProvider';
import type { WizardFormData } from './WizardContainer';

// ─── Types ───────────────────────────────────────────────────────────────────

interface VoiceAgentProps {
  locale: string;
  onComplete: (brief: string, formData: WizardFormData) => void;
}

// ─── Transcript Bubble ───────────────────────────────────────────────────────

function TranscriptBubble({ entry }: { entry: TranscriptEntry }) {
  return (
    <motion.div
      initial={{ opacity: 0, y: 6 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.25, ease: [0.16, 1, 0.3, 1] }}
      className={cn(
        'flex',
        entry.role === 'agent' ? 'justify-start' : 'justify-end',
      )}
    >
      <div
        className={cn(
          'max-w-[85%] rounded-xl px-3 py-2 text-xs leading-relaxed',
          entry.role === 'agent'
            ? 'bg-surface-low text-on-surface'
            : 'bg-primary/10 text-primary-dark',
        )}
      >
        {entry.text}
      </div>
    </motion.div>
  );
}

// ─── Main Component ──────────────────────────────────────────────────────────

export default function VoiceAgent({ locale, onComplete }: VoiceAgentProps) {
  const t = useTranslations('configurator');
  const {
    status,
    errorMessage,
    isMicActive,
    toggleMic,
    transcript,
    isAnalyzingSite,
    isGeneratingBrief,
    agentAmplitude,
    startConversation,
    endConversation,
    completedBrief,
    completedFormData,
    pendingContact,
    confirmContact,
    updatePendingContact,
    canReconnect,
    reconnect,
  } = useVoiceAgent();

  const transcriptEndRef = useRef<HTMLDivElement>(null);

  // Auto-scroll transcript
  useEffect(() => {
    transcriptEndRef.current?.scrollIntoView({ behavior: 'smooth', block: 'end' });
  }, [transcript]);

  // Handle completion — end the call, then transition
  useEffect(() => {
    if (completedBrief && completedFormData) {
      console.log('[VoiceAgent] Brief complete, ending conversation and transitioning in 1.5s...');
      endConversation();
      const timer = setTimeout(() => {
        console.log('[VoiceAgent] Calling onComplete');
        onComplete(completedBrief, completedFormData);
      }, 1500);
      return () => clearTimeout(timer);
    }
  }, [completedBrief, completedFormData, onComplete, endConversation]);

  // Orb animation driven by agent amplitude
  const amplitudeValue = useMotionValue(0);
  useEffect(() => {
    amplitudeValue.set(agentAmplitude);
  }, [agentAmplitude, amplitudeValue]);
  const orbScale = useTransform(amplitudeValue, [0, 0.5], [1, 1.18]);
  const orbGlow = useTransform(
    amplitudeValue,
    [0, 0.5],
    ['0px 0px 0px rgba(0,100,148,0)', '0px 0px 30px rgba(0,100,148,0.3)'],
  );

  return (
    <div className="flex flex-col gap-5">
      {/* Agent card header */}
      <div className="flex items-center gap-3 px-1">
        <div className="w-8 h-8 rounded-lg bg-gradient-to-br from-primary to-primary-dark/80 flex items-center justify-center">
          <span className="text-white font-serif text-xs font-bold">L</span>
        </div>
        <div className="flex-1">
          <p className="text-sm font-semibold text-on-surface">{t('voice.agentName')}</p>
          <div className="flex items-center gap-1.5">
            <span
              className={cn(
                'w-1.5 h-1.5 rounded-full',
                status === 'active' ? 'bg-green-500' : status === 'connecting' ? 'bg-amber-400 animate-pulse' : 'bg-outline-variant/50',
              )}
            />
            <span className="text-[10px] text-outline">
              {status === 'active' ? 'Connected' : status === 'connecting' ? t('voice.connecting') : 'Ready'}
            </span>
          </div>
        </div>
      </div>

      {/* Waveform orb */}
      <div className="flex flex-col items-center gap-3 py-4">
        <motion.div
          style={{ scale: status === 'active' ? orbScale : 1, boxShadow: status === 'active' ? orbGlow : 'none' }}
          className={cn(
            'w-24 h-24 rounded-full flex items-center justify-center transition-colors duration-300',
            status === 'active'
              ? 'bg-gradient-to-br from-primary to-primary-dark'
              : status === 'connecting' || (status === 'idle' && isGeneratingBrief)
                ? 'bg-primary/20'
                : 'bg-surface-low border-2 border-outline-variant/30',
          )}
        >
          {status === 'idle' && !isGeneratingBrief && (
            <Mic size={32} strokeWidth={1.5} className="text-outline" />
          )}
          {(status === 'connecting' || (status === 'idle' && isGeneratingBrief)) && (
            <motion.div animate={{ rotate: 360 }} transition={{ duration: 1.5, repeat: Infinity, ease: 'linear' }}>
              <Loader2 size={32} strokeWidth={1.5} className="text-primary" />
            </motion.div>
          )}
          {status === 'active' && (
            <motion.div
              animate={{ scale: [1, 1.1, 1] }}
              transition={{ duration: 2, repeat: Infinity, ease: 'easeInOut' }}
            >
              <Mic size={32} strokeWidth={1.5} className="text-white" />
            </motion.div>
          )}
        </motion.div>

        {/* Status badges */}
        <AnimatePresence>
          {isAnalyzingSite && (
            <motion.div
              initial={{ opacity: 0, y: -4 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -4 }}
              className="flex items-center gap-1.5 px-3 py-1 rounded-full bg-primary/10 text-primary-dark text-xs font-medium"
            >
              <motion.div animate={{ rotate: 360 }} transition={{ duration: 1, repeat: Infinity, ease: 'linear' }}>
                <Loader2 size={11} />
              </motion.div>
              {t('voice.analyzingSite')}
            </motion.div>
          )}
          {isGeneratingBrief && !completedBrief && (
            <motion.div
              initial={{ opacity: 0, y: -4 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -4 }}
              className="flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-primary/10 text-primary-dark text-xs font-medium"
            >
              <motion.div animate={{ rotate: 360 }} transition={{ duration: 1, repeat: Infinity, ease: 'linear' }}>
                <Loader2 size={11} />
              </motion.div>
              {t('voice.generatingBrief')}
            </motion.div>
          )}
        </AnimatePresence>

        {/* Error message */}
        {errorMessage && !canReconnect && (
          <p className="text-xs text-red-600 text-center max-w-xs">{errorMessage}</p>
        )}
      </div>

      {/* Live transcript */}
      {transcript.length > 0 && (
        <div className="rounded-xl border border-outline-variant/30 bg-surface-high p-3 max-h-72 overflow-y-auto scrollbar-thin">
          <div className="flex flex-col gap-2">
            {transcript.map((entry, i) => (
              <TranscriptBubble key={`${entry.timestamp}-${i}`} entry={entry} />
            ))}
            <div ref={transcriptEndRef} />
          </div>
        </div>
      )}

      {/* Contact confirmation card */}
      <AnimatePresence>
        {pendingContact && !completedBrief && (
          <motion.div
            initial={{ opacity: 0, y: 8 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -8 }}
            transition={{ duration: 0.3, ease: [0.16, 1, 0.3, 1] }}
            className="rounded-xl border border-primary/20 bg-primary/5 p-4"
          >
            <p className="text-xs font-semibold uppercase tracking-label text-outline mb-3">
              {t('voice.contactConfirm')}
            </p>
            <div className="flex flex-col gap-2">
              <div className="flex items-center gap-2">
                <label className="text-xs text-outline w-12 flex-shrink-0">
                  {t('fields.name')}
                </label>
                <input
                  type="text"
                  value={pendingContact.name}
                  onChange={(e) => updatePendingContact('name', e.target.value)}
                  className="flex-1 text-sm text-on-surface bg-white rounded-lg border border-outline-variant/30 px-3 py-1.5 focus:outline-none focus:ring-1 focus:ring-primary/40"
                />
              </div>
              <div className="flex items-center gap-2">
                <label className="text-xs text-outline w-12 flex-shrink-0">
                  {t('fields.email')}
                </label>
                <input
                  type="email"
                  value={pendingContact.email}
                  onChange={(e) => updatePendingContact('email', e.target.value)}
                  className="flex-1 text-sm text-on-surface bg-white rounded-lg border border-outline-variant/30 px-3 py-1.5 focus:outline-none focus:ring-1 focus:ring-primary/40"
                />
              </div>
            </div>
            <button
              type="button"
              onClick={confirmContact}
              className="mt-3 w-full py-2 rounded-lg text-xs font-medium text-white transition-all hover:-translate-y-px active:translate-y-0"
              style={{ background: 'linear-gradient(135deg, #006494, #5BA4D9)' }}
            >
              {t('voice.contactConfirmButton')}
            </button>
          </motion.div>
        )}
      </AnimatePresence>

      {/* Controls — sticky on mobile for thumb reach */}
      <div className="flex items-center justify-center gap-3 pt-2 sticky bottom-0 bg-surface-high/95 backdrop-blur-sm pb-2 -mx-6 px-6 sm:static sm:bg-transparent sm:backdrop-blur-none sm:pb-0 sm:mx-0">
        {status === 'idle' && !completedBrief && !isGeneratingBrief && (
          <button
            type="button"
            onClick={startConversation}
            className="flex items-center gap-2 px-6 py-3 rounded-xl text-sm font-medium text-white transition-all hover:-translate-y-px active:translate-y-0"
            style={{ background: 'linear-gradient(135deg, #006494, #5BA4D9)' }}
          >
            <Mic size={16} />
            {t('voice.startConversation')}
          </button>
        )}

        {status === 'active' && (
          <>
            <button
              type="button"
              onClick={toggleMic}
              className={cn(
                'w-11 h-11 rounded-full flex items-center justify-center transition-all',
                isMicActive
                  ? 'bg-surface-low text-on-surface hover:bg-outline-variant/30'
                  : 'bg-red-100 text-red-600',
              )}
            >
              {isMicActive ? <Mic size={18} /> : <MicOff size={18} />}
            </button>
            <button
              type="button"
              onClick={endConversation}
              className="flex items-center gap-2 px-4 py-2.5 rounded-xl bg-red-50 text-red-700 text-xs font-medium hover:bg-red-100 transition-colors"
            >
              <PhoneOff size={14} />
              {t('voice.endConversation')}
            </button>
          </>
        )}

        {status === 'connecting' && (
          <p className="text-sm text-outline animate-pulse">{t('voice.connecting')}</p>
        )}

        {(status === 'error' || canReconnect) && !completedBrief && (
          <div className="flex flex-col items-center gap-2">
            <p className="text-xs text-outline text-center">
              {t('voice.connectionLost')}
            </p>
            <button
              type="button"
              onClick={reconnect}
              className="flex items-center gap-2 px-5 py-2.5 rounded-xl text-sm font-medium text-white transition-all hover:-translate-y-px active:translate-y-0"
              style={{ background: 'linear-gradient(135deg, #006494, #5BA4D9)' }}
            >
              {t('voice.reconnect')}
            </button>
          </div>
        )}
      </div>
    </div>
  );
}
