import { useState, useRef, useEffect } from 'react';
import { MOCK_PROJECTS, MOCK_TASKS, MOCK_RISKS, MOCK_EVM } from '../../services/mockData';

// ── Build project context for the AI prompt ────────────────────────────────
function buildProjectContext() {
  const lines = ['Eres AR Assistant, el asistente de inteligencia artificial integrado en AR-ProjectManagement.'];
  lines.push('Tienes acceso en tiempo real a los siguientes datos del portafolio de proyectos:\n');

  MOCK_PROJECTS.forEach(p => {
    const tasks    = MOCK_TASKS[p.id] || [];
    const done     = tasks.filter(t => t.status === 'COMPLETADA').length;
    const blocked  = tasks.filter(t => t.status === 'BLOQUEADA').length;
    const overdue  = tasks.filter(t => t.dueDate && t.dueDate < '2026-06-26' && t.status !== 'COMPLETADA').length;
    const risks    = (MOCK_RISKS[p.id] || []).filter(r => r.status === 'ACTIVO');
    const critRisk = risks.filter(r => r.probability * r.impact >= 12).length;
    const evmData  = (MOCK_EVM[p.id] || []).filter(e => e.ev);
    const lastEVM  = evmData[evmData.length - 1];
    const cpi      = lastEVM && lastEVM.ac > 0 ? (lastEVM.ev / lastEVM.ac).toFixed(2) : 'N/D';
    const spi      = lastEVM && lastEVM.pv > 0 ? (lastEVM.ev / lastEVM.pv).toFixed(2) : 'N/D';
    const budgetUsedPct = p.budget > 0 ? Math.round(tasks.reduce((s,t)=>s+(t.actualCost||0),0) / p.budget * 100) : 0;

    lines.push(`PROYECTO: ${p.code} — ${p.name}`);
    lines.push(`  Estado: ${p.status} | RAG: ${p.ragStatus} | Metodología: ${p.methodology}`);
    lines.push(`  Progreso: ${p.progressPct}% | Presupuesto: $${(p.budget/1000).toFixed(0)}K USD | Ejecutado: ${budgetUsedPct}%`);
    lines.push(`  Fechas: ${p.startDate} → ${p.plannedEndDate}`);
    lines.push(`  Tareas: ${tasks.length} total | ${done} completadas | ${blocked} bloqueadas | ${overdue} vencidas`);
    lines.push(`  Riesgos activos: ${risks.length} (${critRisk} críticos)`);
    lines.push(`  EVM último período — CPI: ${cpi} | SPI: ${spi}`);
    if (p.description) lines.push(`  Descripción: ${p.description}`);
    lines.push('');
  });

  lines.push('INSTRUCCIONES:');
  lines.push('- Analiza los datos reales del portafolio y da recomendaciones concretas.');
  lines.push('- Si un CPI < 0.9, advierte de sobrecosto. Si SPI < 0.9, advierte de retraso.');
  lines.push('- Si hay tareas bloqueadas o vencidas, menciona el proyecto y sugiere acciones.');
  lines.push('- Si preguntan sobre un proyecto específico, usa los datos de ese proyecto.');
  lines.push('- Aprende del historial: proyectos con RAG ROJO suelen tener CPI < 0.85 y múltiples riesgos críticos.');
  lines.push('- Habla siempre en español. Sé conciso pero específico con números y nombres reales.');

  return lines.join('\n');
}

// ── AI call function ───────────────────────────────────────────────────────
async function callAI(userMessage, history) {
  const raw = localStorage.getItem('arpm_settings');
  const settings = raw ? JSON.parse(raw) : {};
  const provider = settings.aiProvider || 'none';
  const systemPrompt = buildProjectContext();

  if (provider === 'none') {
    return 'La IA no está configurada. Ve a **Configuración → Inteligencia IA** y selecciona un proveedor (Ollama local o API externa).';
  }

  // Convert chat history to messages array (last 10 messages for context)
  const historyMessages = history.slice(-10).map(m => ({
    role: m.role === 'ai' ? 'assistant' : 'user',
    content: m.text,
  }));

  // ── Ollama (local) ─────────────────────────────────────────────────────
  if (provider === 'ollama') {
    const baseUrl = (settings.aiLocalUrl || 'http://localhost:11434').replace(/\/$/, '');
    const model   = settings.aiLocalModel || 'llama3';

    const body = {
      model,
      messages: [
        { role: 'system', content: systemPrompt },
        ...historyMessages,
        { role: 'user', content: userMessage },
      ],
      stream: false,
    };

    const res = await fetch(`${baseUrl}/api/chat`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(body),
    });

    if (!res.ok) throw new Error(`Ollama error ${res.status}: ${await res.text()}`);
    const data = await res.json();
    return data.message?.content || data.response || 'Sin respuesta del modelo.';
  }

  // ── Claude (Anthropic) ─────────────────────────────────────────────────
  if (provider === 'claude') {
    const apiKey = settings.claudeApiKey || '';
    const model  = settings.claudeModel  || 'claude-sonnet-4-6';

    if (!apiKey) return 'Falta la API key de Anthropic. Configúrala en Ajustes → Inteligencia IA.';

    const res = await fetch('https://api.anthropic.com/v1/messages', {
      method: 'POST',
      headers: {
        'x-api-key': apiKey,
        'anthropic-version': '2023-06-01',
        'content-type': 'application/json',
        'anthropic-dangerous-direct-browser-calls': 'true',
      },
      body: JSON.stringify({
        model,
        max_tokens: 1024,
        system: systemPrompt,
        messages: [
          ...historyMessages,
          { role: 'user', content: userMessage },
        ],
      }),
    });

    if (!res.ok) throw new Error(`Claude API error ${res.status}: ${await res.text()}`);
    const data = await res.json();
    return data.content?.[0]?.text || 'Sin respuesta.';
  }

  // ── OpenAI ─────────────────────────────────────────────────────────────
  if (provider === 'openai') {
    const apiKey = settings.openaiApiKey || '';
    const model  = settings.openaiModel  || 'gpt-4o';

    if (!apiKey) return 'Falta la API key de OpenAI. Configúrala en Ajustes → Inteligencia IA.';

    const res = await fetch('https://api.openai.com/v1/chat/completions', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${apiKey}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        model,
        max_tokens: 1024,
        messages: [
          { role: 'system', content: systemPrompt },
          ...historyMessages,
          { role: 'user', content: userMessage },
        ],
      }),
    });

    if (!res.ok) throw new Error(`OpenAI error ${res.status}: ${await res.text()}`);
    const data = await res.json();
    return data.choices?.[0]?.message?.content || 'Sin respuesta.';
  }

  return 'Proveedor de IA no reconocido. Revisa la configuración.';
}

// ── UI Components ──────────────────────────────────────────────────────────
const QUICK_PROMPTS = [
  '¿Qué proyecto tiene mayor riesgo?',
  'Resumen del portafolio',
  '¿Hay tareas vencidas o bloqueadas?',
  '¿Qué proyectos tienen sobrecosto?',
];

function TypingIndicator() {
  return (
    <div className="flex items-end gap-2 mb-4">
      <div className="w-7 h-7 rounded-full bg-gradient-to-br from-blue-600 to-purple-600 flex items-center justify-center flex-shrink-0">
        <span className="text-white text-xs font-bold">AR</span>
      </div>
      <div className="bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-2xl rounded-bl-sm px-4 py-3">
        <div className="flex gap-1 items-center h-4">
          <span className="w-2 h-2 bg-slate-400 rounded-full animate-bounce" style={{ animationDelay: '0ms' }} />
          <span className="w-2 h-2 bg-slate-400 rounded-full animate-bounce" style={{ animationDelay: '150ms' }} />
          <span className="w-2 h-2 bg-slate-400 rounded-full animate-bounce" style={{ animationDelay: '300ms' }} />
        </div>
      </div>
    </div>
  );
}

function MessageBubble({ msg }) {
  const isUser = msg.role === 'user';
  return (
    <div className={`flex items-end gap-2 mb-4 ${isUser ? 'flex-row-reverse' : ''}`}>
      {!isUser && (
        <div className="w-7 h-7 rounded-full bg-gradient-to-br from-blue-600 to-purple-600 flex items-center justify-center flex-shrink-0">
          <span className="text-white text-xs font-bold">AR</span>
        </div>
      )}
      <div className={`max-w-[78%] ${isUser ? 'items-end' : 'items-start'} flex flex-col gap-1`}>
        <div className={`px-4 py-2.5 text-sm leading-relaxed whitespace-pre-wrap ${
          isUser
            ? 'bg-blue-600 text-white rounded-2xl rounded-br-sm'
            : msg.isError
              ? 'bg-red-50 dark:bg-red-500/10 border border-red-200 dark:border-red-500/30 text-red-700 dark:text-red-300 rounded-2xl rounded-bl-sm'
              : 'bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-slate-800 dark:text-slate-100 rounded-2xl rounded-bl-sm'
        }`}>
          {msg.text}
        </div>
        <span className="text-xs text-slate-400 px-1">{msg.time}</span>
      </div>
    </div>
  );
}

function getProviderLabel() {
  const raw = localStorage.getItem('arpm_settings');
  const s = raw ? JSON.parse(raw) : {};
  const p = s.aiProvider || 'none';
  if (p === 'ollama') return `Ollama · ${s.aiLocalModel || 'llama3'}`;
  if (p === 'claude') return `Claude · ${(s.claudeModel || 'sonnet').split('-').slice(1,3).join(' ')}`;
  if (p === 'openai') return `OpenAI · ${s.openaiModel || 'gpt-4o'}`;
  return 'Sin configurar';
}

// ── Main component ─────────────────────────────────────────────────────────
export default function AIChat() {
  const initMsg = {
    id: 'init',
    role: 'ai',
    text: '¡Hola! Soy AR Assistant. Tengo acceso en tiempo real a todos tus proyectos — presupuestos, riesgos, EVM, tareas y más. ¿En qué te ayudo hoy?',
    time: new Date().toLocaleTimeString('es-ES', { hour: '2-digit', minute: '2-digit' }),
  };

  const [isOpen, setIsOpen]     = useState(false);
  const [messages, setMessages] = useState([initMsg]);
  const [input, setInput]       = useState('');
  const [isTyping, setIsTyping] = useState(false);
  const [hasUnread, setHasUnread] = useState(true);
  const [hasOpened, setHasOpened] = useState(false);
  const messagesEndRef = useRef(null);
  const inputRef       = useRef(null);

  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages, isTyping]);

  useEffect(() => {
    if (isOpen) {
      setHasUnread(false);
      setHasOpened(true);
      setTimeout(() => inputRef.current?.focus(), 100);
    }
  }, [isOpen]);

  function now() {
    return new Date().toLocaleTimeString('es-ES', { hour: '2-digit', minute: '2-digit' });
  }

  async function sendMessage(text) {
    const trimmed = (text || input).trim();
    if (!trimmed || isTyping) return;

    const userMsg = { id: `u-${Date.now()}`, role: 'user', text: trimmed, time: now() };
    const nextHistory = [...messages, userMsg];
    setMessages(nextHistory);
    setInput('');
    setIsTyping(true);

    try {
      const response = await callAI(trimmed, messages);
      setMessages(prev => [...prev, { id: `a-${Date.now()}`, role: 'ai', text: response, time: now() }]);
    } catch (err) {
      const errText = err.message.includes('Failed to fetch')
        ? 'No se pudo conectar con el servicio de IA. Verifica que Ollama esté corriendo o que la API key sea válida.'
        : `Error: ${err.message}`;
      setMessages(prev => [...prev, { id: `a-${Date.now()}`, role: 'ai', text: errText, time: now(), isError: true }]);
    } finally {
      setIsTyping(false);
      if (!isOpen) setHasUnread(true);
    }
  }

  function handleKeyDown(e) {
    if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendMessage(); }
  }

  const providerLabel = getProviderLabel();

  return (
    <>
      {isOpen && (
        <div className="fixed bottom-24 right-6 z-50 flex flex-col" style={{ width: 380, height: 540 }}>
          <div className="flex flex-col h-full rounded-2xl shadow-2xl border border-slate-200 dark:border-slate-700 overflow-hidden bg-slate-50 dark:bg-slate-950">

            {/* Header */}
            <div className="bg-gradient-to-r from-blue-600 to-purple-600 px-4 py-3 flex items-center gap-3 flex-shrink-0">
              <div className="w-9 h-9 rounded-full bg-white/20 flex items-center justify-center">
                <svg className="w-5 h-5 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z" />
                </svg>
              </div>
              <div className="flex-1 min-w-0">
                <p className="text-white font-bold text-sm leading-tight">AR Assistant</p>
                <p className="text-blue-100 text-xs truncate">{providerLabel}</p>
              </div>
              <button onClick={() => setIsOpen(false)}
                className="w-8 h-8 rounded-full bg-white/20 hover:bg-white/30 flex items-center justify-center transition-colors flex-shrink-0">
                <svg className="w-4 h-4 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            </div>

            {/* Messages */}
            <div className="flex-1 overflow-y-auto px-4 py-4">
              {messages.map(msg => <MessageBubble key={msg.id} msg={msg} />)}
              {isTyping && <TypingIndicator />}
              <div ref={messagesEndRef} />
            </div>

            {/* Quick prompts */}
            <div className="px-4 pb-2 flex flex-wrap gap-1.5 flex-shrink-0">
              {QUICK_PROMPTS.map(p => (
                <button key={p} onClick={() => sendMessage(p)} disabled={isTyping}
                  className="text-xs bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700 text-slate-600 dark:text-slate-300 rounded-full px-2.5 py-1 hover:bg-blue-50 dark:hover:bg-slate-700 hover:border-blue-300 hover:text-blue-600 transition-colors disabled:opacity-40 cursor-pointer">
                  {p}
                </button>
              ))}
            </div>

            {/* Input */}
            <div className="px-4 pb-4 pt-1 flex-shrink-0">
              <div className="flex items-center gap-2 bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-xl px-3 py-2">
                <input ref={inputRef} type="text" value={input}
                  onChange={e => setInput(e.target.value)} onKeyDown={handleKeyDown}
                  placeholder="Consulta sobre tus proyectos..."
                  disabled={isTyping}
                  className="flex-1 text-sm bg-transparent text-slate-800 dark:text-slate-100 placeholder-slate-400 outline-none disabled:opacity-50" />
                <button onClick={() => sendMessage()} disabled={!input.trim() || isTyping}
                  className="w-8 h-8 rounded-lg bg-blue-600 hover:bg-blue-700 disabled:bg-slate-200 dark:disabled:bg-slate-700 disabled:cursor-not-allowed flex items-center justify-center transition-colors flex-shrink-0">
                  <svg className="w-4 h-4 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8" />
                  </svg>
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Floating button */}
      <button onClick={() => setIsOpen(v => !v)}
        className={`fixed bottom-6 right-6 z-50 w-14 h-14 rounded-full bg-gradient-to-br from-blue-600 to-purple-600 shadow-lg hover:shadow-xl hover:scale-105 active:scale-95 transition-all duration-200 flex items-center justify-center ${!hasOpened ? 'animate-pulse' : ''}`}
        aria-label="Abrir AR Assistant">
        {isOpen
          ? <svg className="w-6 h-6 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7"/></svg>
          : <svg className="w-6 h-6 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"/></svg>
        }
        {hasUnread && !isOpen && (
          <span className="absolute -top-1 -right-1 w-4 h-4 bg-amber-400 rounded-full border-2 border-white dark:border-slate-950" />
        )}
      </button>
    </>
  );
}
