'use client';

import React, { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import {
  MessageCircle, TrendingUp, Settings, Pencil, Check, X,
  ArrowLeft, Sparkles,
} from 'lucide-react';
import Link from 'next/link';
import CompanionChat from './companion-chat';
import CompanionGrowth from './companion-growth';
import { MATURITY_LEVELS } from '@/lib/ai-companion';

type Tab = 'chat' | 'growth' | 'settings';

export default function CompanionDashboard() {
  const [activeTab, setActiveTab] = useState<Tab>('chat');
  const [userId, setUserId] = useState<string>('default-user');
  const [editingName, setEditingName] = useState(false);
  const [newName, setNewName] = useState('');
  const [companionName, setCompanionName] = useState('Ghost');

  // Load session user if available
  useEffect(() => {
    const stored = typeof window !== 'undefined' ? localStorage.getItem('gfs_user_id') : null;
    if (stored) setUserId(stored);
  }, []);

  const saveName = async () => {
    if (!newName.trim()) return;
    try {
      const res = await fetch('/api/ai-companion/name', {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ userId, name: newName.trim() }),
      });
      const data = await res.json();
      if (data.success) {
        setCompanionName(data.name);
        setEditingName(false);
      }
    } catch (e) {
      console.error('Failed to update name:', e);
    }
  };

  const tabs = [
    { id: 'chat' as Tab, label: 'Chat', icon: <MessageCircle className="w-4 h-4" /> },
    { id: 'growth' as Tab, label: 'Growth', icon: <TrendingUp className="w-4 h-4" /> },
    { id: 'settings' as Tab, label: 'Settings', icon: <Settings className="w-4 h-4" /> },
  ];

  return (
    <div className="max-w-4xl mx-auto px-4 py-6">
      {/* Header */}
      <div className="flex items-center gap-4 mb-6">
        <Link href="/ghost-control" className="text-gray-400 hover:text-white transition-colors">
          <ArrowLeft className="w-5 h-5" />
        </Link>
        <div className="flex items-center gap-3">
          <Sparkles className="w-6 h-6 text-brand" />
          <div>
            <h1 className="text-xl font-bold text-white">AI Agent</h1>
            <p className="text-xs text-gray-500">Your personal AI that grows with you</p>
          </div>
        </div>
      </div>

      {/* Tabs */}
      <div className="flex gap-1 mb-4 p-1 rounded-lg bg-white/5 border border-white/10">
        {tabs.map((tab) => (
          <button
            key={tab.id}
            onClick={() => setActiveTab(tab.id)}
            className={`flex-1 flex items-center justify-center gap-2 px-4 py-2 rounded-md text-sm font-medium transition-all ${
              activeTab === tab.id
                ? 'bg-white/10 text-white'
                : 'text-gray-500 hover:text-gray-300'
            }`}
          >
            {tab.icon}
            {tab.label}
          </button>
        ))}
      </div>

      {/* Content */}
      <div className="rounded-xl border border-white/10 bg-white/[0.02] overflow-hidden" style={{ minHeight: '500px' }}>
        {activeTab === 'chat' && (
          <CompanionChat userId={userId} />
        )}

        {activeTab === 'growth' && (
          <div className="p-4">
            <CompanionGrowth userId={userId} />
          </div>
        )}

        {activeTab === 'settings' && (
          <div className="p-6 space-y-6">
            <h3 className="text-lg font-semibold text-white">Companion Settings</h3>

            {/* Name */}
            <div className="space-y-2">
              <label className="text-sm text-gray-400">Companion Name</label>
              {editingName ? (
                <div className="flex items-center gap-2">
                  <input
                    value={newName}
                    onChange={(e) => setNewName(e.target.value)}
                    maxLength={30}
                    className="flex-1 px-3 py-2 rounded-lg bg-white/5 border border-white/10 text-white text-sm focus:outline-none focus:ring-2 focus:ring-brand-deep/50"
                    placeholder="Enter name..."
                    autoFocus
                  />
                  <button onClick={saveName} className="p-2 rounded-lg bg-brand-deep/20 text-brand hover:bg-brand-deep/30">
                    <Check className="w-4 h-4" />
                  </button>
                  <button onClick={() => setEditingName(false)} className="p-2 rounded-lg bg-white/5 text-gray-400 hover:text-white">
                    <X className="w-4 h-4" />
                  </button>
                </div>
              ) : (
                <div className="flex items-center gap-2">
                  <span className="text-white">{companionName}</span>
                  <button
                    onClick={() => { setNewName(companionName); setEditingName(true); }}
                    className="p-1 text-gray-500 hover:text-white transition-colors"
                  >
                    <Pencil className="w-3.5 h-3.5" />
                  </button>
                </div>
              )}
            </div>

            {/* User ID */}
            <div className="space-y-2">
              <label className="text-sm text-gray-400">Your User ID</label>
              <div className="flex items-center gap-2">
                <input
                  value={userId}
                  onChange={(e) => {
                    setUserId(e.target.value);
                    if (typeof window !== 'undefined') {
                      localStorage.setItem('gfs_user_id', e.target.value);
                    }
                  }}
                  className="flex-1 px-3 py-2 rounded-lg bg-white/5 border border-white/10 text-white text-sm focus:outline-none focus:ring-2 focus:ring-brand-deep/50"
                  placeholder="Enter your user ID..."
                />
              </div>
              <p className="text-xs text-gray-600">
                Each user ID gets a unique companion. Change this to switch companions.
              </p>
            </div>

            {/* Growth Info */}
            <div className="space-y-3">
              <label className="text-sm text-gray-400">Growth Stages</label>
              <div className="space-y-2">
                {MATURITY_LEVELS.map((ml) => (
                  <div key={ml.level} className="flex items-start gap-3 p-3 rounded-lg bg-white/[0.02] border border-white/5">
                    <span className="text-xl">{ml.icon}</span>
                    <div>
                      <div className="text-sm font-medium text-white">{ml.name} (Level {ml.level})</div>
                      <div className="text-xs text-gray-500">{ml.description}</div>
                      <div className="text-xs text-gray-600 mt-1">{ml.xpRequired} XP required</div>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
