'use client';

import React, { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import {
  Brain, Star, MessageCircle, BookOpen, Trophy,
  Zap, Heart, TrendingUp, Calendar, Sparkles,
} from 'lucide-react';
import { MATURITY_LEVELS, getMaturityLevel, getNextLevel } from '@/lib/ai-companion';

interface CompanionProfile {
  id: string;
  name: string;
  maturityLevel: number;
  xp: number;
  birthDate: string;
  lastActive: string;
  totalConversations: number;
  totalMemories: number;
  totalDiaryEntries: number;
  totalMilestones: number;
  milestones: Array<{
    id: string;
    type: string;
    title: string;
    description: string;
    xpEarned: number;
    achievedAt: string;
  }>;
  topMemories: Array<{
    id: string;
    category: string;
    key: string;
    content: string;
  }>;
}

interface CompanionGrowthProps {
  userId: string;
}

export default function CompanionGrowth({ userId }: CompanionGrowthProps) {
  const [profile, setProfile] = useState<CompanionProfile | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const load = async () => {
      try {
        const res = await fetch(`/api/ai-companion?userId=${encodeURIComponent(userId)}`);
        const data = await res.json();
        if (data.exists) {
          setProfile(data.companion);
        }
      } catch (e) {
        console.error('Failed to load profile:', e);
      } finally {
        setLoading(false);
      }
    };
    load();
  }, [userId]);

  if (loading) {
    return <div className="flex items-center justify-center h-64 text-gray-500">Loading growth data...</div>;
  }

  if (!profile) {
    return (
      <div className="text-center py-12">
        <div className="text-5xl mb-4">{MATURITY_LEVELS[0].icon}</div>
        <h3 className="text-lg font-semibold text-white mb-2">No Companion Yet</h3>
        <p className="text-sm text-gray-400">Start a conversation to start your AI agent.</p>
      </div>
    );
  }

  const level = getMaturityLevel(profile.maturityLevel);
  const nextLevel = getNextLevel(profile.maturityLevel);
  const xpProgress = nextLevel
    ? ((profile.xp - level.xpRequired) / (nextLevel.xpRequired - level.xpRequired)) * 100
    : 100;

  const daysSinceBirth = Math.floor(
    (Date.now() - new Date(profile.birthDate).getTime()) / (1000 * 60 * 60 * 24)
  );

  return (
    <div className="space-y-6">
      {/* Profile Header */}
      <div className="flex items-center gap-4 p-4 rounded-xl bg-gradient-to-r from-brand-deep/10 to-brand-secondary/10 border border-white/10">
        <div className="text-5xl">{level.icon}</div>
        <div className="flex-1">
          <h2 className="text-xl font-bold text-white">{profile.name}</h2>
          <div className="flex items-center gap-3 mt-1">
            <span className="text-sm text-brand">{level.name}</span>
            <span className="text-xs text-gray-500">Level {level.level}</span>
            <span className="text-xs text-gray-500">•</span>
            <span className="text-xs text-gray-500">{daysSinceBirth} days old</span>
          </div>
          <p className="text-xs text-gray-400 mt-1 italic">{level.personality}</p>
        </div>
        <div className="text-right">
          <div className="text-2xl font-bold text-white">{profile.xp}</div>
          <div className="text-xs text-gray-500">Total XP</div>
        </div>
      </div>

      {/* XP Progress Bar */}
      {nextLevel && (
        <div className="px-1">
          <div className="flex justify-between text-xs text-gray-500 mb-1">
            <span>{level.name} ({level.xpRequired} XP)</span>
            <span>{nextLevel.name} ({nextLevel.xpRequired} XP)</span>
          </div>
          <div className="h-3 rounded-full bg-white/5 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: 1, ease: 'easeOut' }}
            />
          </div>
        </div>
      )}

      {/* Stats Grid */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
        {[
          { icon: <MessageCircle className="w-4 h-4" />, label: 'Conversations', value: profile.totalConversations, color: 'text-brand' },
          { icon: <Brain className="w-4 h-4" />, label: 'Memories', value: profile.totalMemories, color: 'text-brand-secondary-light' },
          { icon: <BookOpen className="w-4 h-4" />, label: 'Diary Entries', value: profile.totalDiaryEntries, color: 'text-blue-400' },
          { icon: <Trophy className="w-4 h-4" />, label: 'Milestones', value: profile.totalMilestones, color: 'text-yellow-400' },
        ].map((stat) => (
          <div key={stat.label} className="p-3 rounded-lg bg-white/[0.03] border border-white/5">
            <div className={`flex items-center gap-2 mb-1 ${stat.color}`}>
              {stat.icon}
              <span className="text-xs">{stat.label}</span>
            </div>
            <div className="text-xl font-bold text-white">{stat.value}</div>
          </div>
        ))}
      </div>

      {/* Growth Stages Timeline */}
      <div>
        <h3 className="text-sm font-semibold text-gray-300 mb-3 flex items-center gap-2">
          <TrendingUp className="w-4 h-4 text-brand" />
          Growth Stages
        </h3>
        <div className="flex items-center gap-1">
          {MATURITY_LEVELS.map((ml, i) => {
            const isActive = i === profile.maturityLevel;
            const isPast = i < profile.maturityLevel;
            return (
              <React.Fragment key={ml.level}>
                <div className={`flex flex-col items-center flex-1 p-2 rounded-lg ${
                  isActive ? 'bg-brand-deep/10 border border-brand-deep/30' :
                  isPast ? 'bg-white/5' : 'opacity-40'
                }`}>
                  <div className="text-xl mb-1">{ml.icon}</div>
                  <div className={`text-[10px] font-medium ${
                    isActive ? 'text-brand' : isPast ? 'text-gray-300' : 'text-gray-600'
                  }`}>{ml.name}</div>
                  {isActive && <Sparkles className="w-3 h-3 text-brand mt-1" />}
                </div>
                {i < MATURITY_LEVELS.length - 1 && (
                  <div className={`w-4 h-0.5 ${
                    isPast ? 'bg-brand-deep' : 'bg-white/10'
                  }`} />
                )}
              </React.Fragment>
            );
          })}
        </div>
      </div>

      {/* Capabilities */}
      <div>
        <h3 className="text-sm font-semibold text-gray-300 mb-3 flex items-center gap-2">
          <Zap className="w-4 h-4 text-brand-secondary-light" />
          Current Capabilities
        </h3>
        <div className="flex flex-wrap gap-2">
          {level.capabilities.map((cap) => (
            <span key={cap} className="text-xs px-2.5 py-1 rounded-full bg-brand-secondary/10 text-brand-secondary-light border border-brand-secondary/20">
              {cap}
            </span>
          ))}
          {nextLevel && nextLevel.capabilities
            .filter(c => !level.capabilities.includes(c))
            .slice(0, 3)
            .map((cap) => (
              <span key={cap} className="text-xs px-2.5 py-1 rounded-full bg-white/5 text-gray-600 border border-white/5">
                🔒 {cap}
              </span>
            ))}
        </div>
      </div>

      {/* Milestones */}
      {profile.milestones.length > 0 && (
        <div>
          <h3 className="text-sm font-semibold text-gray-300 mb-3 flex items-center gap-2">
            <Trophy className="w-4 h-4 text-yellow-400" />
            Recent Milestones
          </h3>
          <div className="space-y-2">
            {profile.milestones.slice(0, 5).map((ms) => (
              <div key={ms.id} className="flex items-center gap-3 p-2.5 rounded-lg bg-white/[0.02] border border-white/5">
                <Star className="w-4 h-4 text-yellow-400 shrink-0" />
                <div className="flex-1 min-w-0">
                  <div className="text-sm font-medium text-white">{ms.title}</div>
                  <div className="text-xs text-gray-500 truncate">{ms.description}</div>
                </div>
                <span className="text-xs text-brand shrink-0">+{ms.xpEarned} XP</span>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Top Memories */}
      {profile.topMemories.length > 0 && (
        <div>
          <h3 className="text-sm font-semibold text-gray-300 mb-3 flex items-center gap-2">
            <Brain className="w-4 h-4 text-brand-secondary-light" />
            What {profile.name} Remembers
          </h3>
          <div className="space-y-2">
            {profile.topMemories.slice(0, 5).map((mem) => (
              <div key={mem.id} className="flex items-start gap-3 p-2.5 rounded-lg bg-white/[0.02] border border-white/5">
                <span className="text-xs px-1.5 py-0.5 rounded bg-brand-secondary/20 text-brand-secondary-light shrink-0">{mem.category}</span>
                <div className="min-w-0">
                  <div className="text-sm font-medium text-gray-300">{mem.key}</div>
                  <div className="text-xs text-gray-500 truncate">{mem.content}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}
