'use client';

import React, { useState, useEffect, useRef, useCallback } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
  Send, Loader2, Sparkles, Brain, Heart,
  ChevronUp, Star, Zap, MessageCircle,
} from 'lucide-react';
import { MATURITY_LEVELS, getMaturityLevel, getNextLevel } from '@/lib/ai-companion';
import { VoiceInputButton } from '@/components/ui/voice-input';

interface CompanionData {
  name: string;
  maturityLevel: number;
  xp: number;
  leveledUp?: boolean;
  newMemories?: number;
}

interface Message {
  id: string;
  role: 'user' | 'companion';
  content: string;
  timestamp: Date;
}

interface CompanionChatProps {
  userId: string;
}

export default function CompanionChat({ userId }: CompanionChatProps) {
  const [messages, setMessages] = useState<Message[]>([]);
  const [input, setInput] = useState('');
  const [loading, setLoading] = useState(false);
  const [companion, setCompanion] = useState<CompanionData | null>(null);
  const [showLevelUp, setShowLevelUp] = useState(false);
  const [initializing, setInitializing] = useState(true);
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLTextAreaElement>(null);

  const scrollToBottom = useCallback(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, []);

  useEffect(() => {
    scrollToBottom();
  }, [messages, scrollToBottom]);

  // Load companion profile
  useEffect(() => {
    const loadCompanion = async () => {
      try {
        const res = await fetch(`/api/ai-companion?userId=${encodeURIComponent(userId)}`);
        const data = await res.json();
        if (data.exists) {
          setCompanion({
            name: data.companion.name,
            maturityLevel: data.companion.maturityLevel,
            xp: data.companion.xp,
          });
        } else {
          // Will be created on first message
          setCompanion({ name: 'Ghost', maturityLevel: 0, xp: 0 });
        }
      } catch (e) {
        console.error('Failed to load companion:', e);
        setCompanion({ name: 'Ghost', maturityLevel: 0, xp: 0 });
      } finally {
        setInitializing(false);
      }
    };
    loadCompanion();
  }, [userId]);

  const sendMessage = async () => {
    if (!input.trim() || loading) return;

    const userMsg: Message = {
      id: `user-${Date.now()}`,
      role: 'user',
      content: input.trim(),
      timestamp: new Date(),
    };
    setMessages(prev => [...prev, userMsg]);
    setInput('');
    setLoading(true);

    try {
      const res = await fetch('/api/ai-companion', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ userId, message: userMsg.content }),
      });
      const data = await res.json();

      if (data.error) {
        setMessages(prev => [...prev, {
          id: `err-${Date.now()}`,
          role: 'companion',
          content: `*yawns* Something went wrong... ${data.error}`,
          timestamp: new Date(),
        }]);
      } else {
        setMessages(prev => [...prev, {
          id: `comp-${Date.now()}`,
          role: 'companion',
          content: data.response,
          timestamp: new Date(),
        }]);

        if (data.companion) {
          setCompanion(data.companion);
          if (data.companion.leveledUp) {
            setShowLevelUp(true);
            setTimeout(() => setShowLevelUp(false), 5000);
          }
        }
      }
    } catch (e) {
      console.error('Chat error:', e);
      setMessages(prev => [...prev, {
        id: `err-${Date.now()}`,
        role: 'companion',
        content: '*blinks* I seem to be having trouble thinking right now...',
        timestamp: new Date(),
      }]);
    } finally {
      setLoading(false);
    }
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      sendMessage();
    }
  };

  if (initializing) {
    return (
      <div className="flex items-center justify-center h-96">
        <Loader2 className="w-8 h-8 animate-spin text-brand" />
      </div>
    );
  }

  const level = companion ? getMaturityLevel(companion.maturityLevel) : MATURITY_LEVELS[0];
  const nextLevel = companion ? getNextLevel(companion.maturityLevel) : MATURITY_LEVELS[1];
  const xpProgress = companion && nextLevel 
    ? ((companion.xp - level.xpRequired) / (nextLevel.xpRequired - level.xpRequired)) * 100 
    : 100;

  return (
    <div className="flex flex-col h-full max-h-[calc(100vh-12rem)]">
      {/* Companion Status Bar */}
      <div className="flex items-center justify-between px-4 py-3 border-b border-white/10 bg-white/[0.02]">
        <div className="flex items-center gap-3">
          <div className="text-2xl">{level.icon}</div>
          <div>
            <div className="flex items-center gap-2">
              <span className="font-semibold text-white">{companion?.name || 'Ghost'}</span>
              <span className="text-xs px-2 py-0.5 rounded-full bg-brand-deep/20 text-brand">
                {level.name}
              </span>
            </div>
            <div className="text-xs text-gray-500">Level {level.level} • {companion?.xp || 0} XP</div>
          </div>
        </div>

        {/* XP Progress */}
        {nextLevel && (
          <div className="flex items-center gap-2">
            <div className="w-24 h-1.5 rounded-full bg-white/10 overflow-hidden">
              <motion.div
                className="h-full rounded-full bg-gradient-to-r from-brand-deep to-brand-secondary"
                initial={{ width: 0 }}
                animate={{ width: `${Math.min(xpProgress, 100)}%` }}
                transition={{ duration: 0.5 }}
              />
            </div>
            <span className="text-[10px] text-gray-500">
              {nextLevel.xpRequired - (companion?.xp || 0)} XP to {nextLevel.name}
            </span>
          </div>
        )}
      </div>

      {/* Level Up Animation */}
      <AnimatePresence>
        {showLevelUp && (
          <motion.div
            initial={{ opacity: 0, y: -20 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -20 }}
            className="mx-4 mt-3 p-3 rounded-lg bg-gradient-to-r from-brand-deep/20 to-brand-secondary/20 border border-brand-deep/30 text-center"
          >
            <div className="flex items-center justify-center gap-2">
              <ChevronUp className="w-5 h-5 text-brand" />
              <span className="font-semibold text-white">Level Up!</span>
              <Sparkles className="w-5 h-5 text-brand-secondary-light" />
            </div>
            <p className="text-sm text-gray-300 mt-1">
              {companion?.name} evolved to {level.name}!
            </p>
          </motion.div>
        )}
      </AnimatePresence>

      {/* Messages */}
      <div className="flex-1 overflow-y-auto px-4 py-4 space-y-4">
        {messages.length === 0 && (
          <div className="text-center py-12">
            <div className="text-5xl mb-4">{level.icon}</div>
            <h3 className="text-lg font-semibold text-white mb-2">
              {companion?.maturityLevel === 0 ? 'Your AI agent awaits' : `${companion?.name} is ready`}
            </h3>
            <p className="text-sm text-gray-400 max-w-sm mx-auto mb-6">
              {companion?.maturityLevel === 0
                ? 'Say hello to begin. Your companion starts as an infant and grows with every conversation.'
                : `${companion?.name} remembers your past conversations and continues to learn.`
              }
            </p>
            <div className="flex flex-wrap justify-center gap-2">
              {['Hello! Tell me about yourself.', 'What can you help me with?', 'What do you remember?'].map((suggestion) => (
                <button
                  key={suggestion}
                  onClick={() => { setInput(suggestion); inputRef.current?.focus(); }}
                  className="text-xs px-3 py-1.5 rounded-full bg-white/5 border border-white/10 text-gray-400 hover:text-white hover:border-white/20 transition-colors"
                >
                  {suggestion}
                </button>
              ))}
            </div>
          </div>
        )}

        {messages.map((msg) => (
          <motion.div
            key={msg.id}
            initial={{ opacity: 0, y: 10 }}
            animate={{ opacity: 1, y: 0 }}
            className={`flex ${msg.role === 'user' ? 'justify-end' : 'justify-start'}`}
          >
            <div
              className={`max-w-[80%] px-4 py-2.5 rounded-2xl ${
                msg.role === 'user'
                  ? 'bg-brand-deep/20 text-white rounded-br-md'
                  : 'bg-white/5 text-gray-200 rounded-bl-md border border-white/5'
              }`}
            >
              {msg.role === 'companion' && (
                <div className="flex items-center gap-1.5 mb-1">
                  <span className="text-sm">{level.icon}</span>
                  <span className="text-xs font-medium text-brand">{companion?.name}</span>
                </div>
              )}
              <p className="text-sm whitespace-pre-wrap leading-relaxed">{msg.content}</p>
            </div>
          </motion.div>
        ))}

        {loading && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            className="flex justify-start"
          >
            <div className="px-4 py-3 rounded-2xl rounded-bl-md bg-white/5 border border-white/5">
              <div className="flex items-center gap-2">
                <div className="flex gap-1">
                  <span className="w-2 h-2 rounded-full bg-brand animate-bounce" style={{ animationDelay: '0ms' }} />
                  <span className="w-2 h-2 rounded-full bg-brand animate-bounce" style={{ animationDelay: '150ms' }} />
                  <span className="w-2 h-2 rounded-full bg-brand animate-bounce" style={{ animationDelay: '300ms' }} />
                </div>
                <span className="text-xs text-gray-500">{companion?.name} is thinking...</span>
              </div>
            </div>
          </motion.div>
        )}

        <div ref={messagesEndRef} />
      </div>

      {/* Input Area */}
      <div className="px-4 py-3 border-t border-white/10 bg-white/[0.02]">
        <div className="flex items-end gap-2">
          <div className="flex-1 relative">
            <textarea
              ref={inputRef}
              value={input}
              onChange={(e) => setInput(e.target.value)}
              onKeyDown={handleKeyDown}
              placeholder={`Message ${companion?.name || 'your companion'}...`}
              rows={1}
              className="w-full px-4 py-2.5 pr-10 rounded-xl bg-white/5 border border-white/10 text-white placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-brand-deep/50 resize-none text-sm"
              disabled={loading}
            />
            <div className="absolute right-2 bottom-2">
              <VoiceInputButton
                onTranscript={(text) => setInput(prev => prev + (prev ? ' ' : '') + text)}
                disabled={loading}
              />
            </div>
          </div>
          <button
            onClick={sendMessage}
            disabled={!input.trim() || loading}
            className="p-2.5 rounded-xl bg-gradient-to-r from-brand-deep to-brand-secondary text-white disabled:opacity-50 disabled:cursor-not-allowed transition-opacity"
          >
            <Send className="w-4 h-4" />
          </button>
        </div>
      </div>
    </div>
  );
}
