'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 Chip from '@/components/ui/Chip';
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,
    selections,
    isAnalyzingSite,
    agentAmplitude,
    startConversation,
    endConversation,
    completedBrief,
    completedFormData,
  } = useVoiceAgent();

  const transcriptEndRef = useRef<HTMLDivElement>(null);

  // Auto-scroll transcript within its container only
  useEffect(() => {
    const el = transcriptEndRef.current;
    if (el?.parentElement) {
      el.parentElement.scrollTop = el.parentElement.scrollHeight;
    }
  }, [transcript]);

  // Handle completion
  useEffect(() => {
    if (completedBrief && completedFormData) {
      const timer = setTimeout(() => {
        onComplete(completedBrief, completedFormData);
      }, 1500);
      return () => clearTimeout(timer);
    }
  }, [completedBrief, completedFormData, onComplete]);

  // 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)'],
  );

  // Build selection chips
  const chipLabels: string[] = [];
  if (selections.services) {
    for (const svc of selections.services) {
      try { chipLabels.push(t(`services.${svc}.title`)); } catch { chipLabels.push(svc); }
    }
  }
  if (selections.aiEnabled && selections.aiTypes) {
    for (const ai of selections.aiTypes) {
      try { chipLabels.push(t(`aiTypes.${ai}.title`)); } catch { chipLabels.push(ai); }
    }
  }
  if (selections.industry) {
    try { chipLabels.push(t(`industries.${selections.industry}`)); } catch { chipLabels.push(selections.industry); }
  }
  if (selections.timeline) {
    try { chipLabels.push(t(`timelines.${selections.timeline}`)); } catch { chipLabels.push(selections.timeline); }
  }

  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-20 h-20 rounded-full flex items-center justify-center transition-colors duration-300',
            status === 'active'
              ? 'bg-gradient-to-br from-primary to-primary-dark'
              : status === 'connecting'
                ? 'bg-primary/20'
                : 'bg-surface-low border-2 border-outline-variant/30',
          )}
        >
          {status === 'idle' && (
            <Mic size={28} strokeWidth={1.5} className="text-outline" />
          )}
          {status === 'connecting' && (
            <motion.div animate={{ rotate: 360 }} transition={{ duration: 1.5, repeat: Infinity, ease: 'linear' }}>
              <Loader2 size={28} 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={28} strokeWidth={1.5} className="text-white" />
            </motion.div>
          )}
        </motion.div>

        {/* Analyzing site badge */}
        <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>
          )}
        </AnimatePresence>

        {/* Error message */}
        {errorMessage && (
          <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-40 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>
      )}

      {/* Selection chips */}
      <AnimatePresence>
        {chipLabels.length > 0 && (
          <motion.div
            initial={{ opacity: 0, height: 0 }}
            animate={{ opacity: 1, height: 'auto' }}
            exit={{ opacity: 0, height: 0 }}
            className="overflow-hidden"
          >
            <p className="text-xs font-semibold uppercase tracking-label text-outline mb-2">
              {t('voice.capturedSoFar')}
            </p>
            <div className="flex flex-wrap gap-1.5">
              {chipLabels.map((label, i) => (
                <motion.div
                  key={label}
                  initial={{ opacity: 0, scale: 0.8 }}
                  animate={{ opacity: 1, scale: 1 }}
                  transition={{ delay: i * 0.05, duration: 0.2 }}
                >
                  <Chip active>{label}</Chip>
                </motion.div>
              ))}
            </div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* Controls */}
      <div className="flex items-center justify-center gap-3 pt-2">
        {status === 'idle' && (
          <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} />
            {locale === 'fr' ? 'Démarrer la conversation' : 'Start Conversation'}
          </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>
        )}
      </div>
    </div>
  );
}
