import { useEffect, useRef, useState } from 'react';
import { Bot, Send, ShieldCheck, User } from 'lucide-react';
import { shire } from '@/api/shireClient';

const welcome = {
  role: 'assistant',
  text: 'I’m SHIRE Merchant—the local business brain for SHIRE 3D. I can analyse products and orders, prepare listing copy, identify profit opportunities and coordinate Etsy now, with eBay and shire3d.com adapters next. Any public or financial action remains approval-gated for Ray.',
};

export default function Assistant() {
  const [messages, setMessages] = useState([welcome]);
  const [input, setInput] = useState('');
  const [loading, setLoading] = useState(false);
  const [mode, setMode] = useState('local');
  const end = useRef(null);

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

  const send = async (event) => {
    event?.preventDefault();
    const message = input.trim();
    if (!message || loading) return;
    setInput('');
    setMessages(current => [...current, { role: 'user', text: message }]);
    setLoading(true);
    try {
      const reply = await shire.assistant.chat(message);
      setMode(reply.mode || 'local');
      setMessages(current => [...current, { role: 'assistant', text: reply.message }]);
    } catch (error) {
      setMessages(current => [...current, { role: 'assistant', text: `I couldn’t complete that analysis: ${error.message}` }]);
    } finally { setLoading(false); }
  };

  return (
    <div className="min-h-[calc(100vh-4rem)] p-4 md:p-6" style={{ background: '#0d0d1a' }}>
      <div className="max-w-4xl mx-auto h-[calc(100vh-7rem)] flex flex-col rounded-2xl overflow-hidden border border-purple-500/30" style={{ background: '#141425' }}>
        <header className="p-4 border-b border-white/10 flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-xl flex items-center justify-center bg-purple-600"><Bot className="text-white" size={22} /></div>
            <div><h1 className="text-white font-bold">SHIRE Merchant</h1><p className="text-xs text-purple-200/60">Big brain for SHIRE 3D</p></div>
          </div>
          <div className="flex items-center gap-2 text-xs text-emerald-300"><ShieldCheck size={15} /> Local · {mode === 'ollama' ? 'Ollama AI' : 'offline-safe'}</div>
        </header>
        <main className="flex-1 overflow-y-auto p-4 md:p-6 space-y-4">
          {messages.map((message, index) => (
            <div key={index} className={`flex gap-3 ${message.role === 'user' ? 'justify-end' : ''}`}>
              {message.role === 'assistant' && <Bot size={20} className="text-purple-400 mt-2 shrink-0" />}
              <div className={`max-w-[85%] whitespace-pre-wrap rounded-2xl px-4 py-3 text-sm leading-relaxed ${message.role === 'user' ? 'bg-orange-500 text-white' : 'bg-white/5 text-purple-50 border border-white/10'}`}>{message.text}</div>
              {message.role === 'user' && <User size={20} className="text-orange-300 mt-2 shrink-0" />}
            </div>
          ))}
          {loading && <div className="text-sm text-purple-300 animate-pulse">SHIRE is thinking…</div>}
          <div ref={end} />
        </main>
        <form onSubmit={send} className="p-4 border-t border-white/10 flex gap-2">
          <input value={input} onChange={event => setInput(event.target.value)} placeholder="Ask SHIRE to analyse products, orders or the next best move…" className="flex-1 rounded-xl bg-black/20 border border-white/10 px-4 py-3 text-sm text-white placeholder:text-white/30 focus:outline-none focus:border-purple-500" />
          <button disabled={loading || !input.trim()} className="rounded-xl px-4 bg-purple-600 text-white disabled:opacity-40" aria-label="Send"><Send size={19} /></button>
        </form>
      </div>
    </div>
  );
}
