import { useEffect, useRef, useState } from 'react';
import { Plus, Star, Send, Pencil, Trash2, Bot } from 'lucide-react';
import { api } from '../api';
import { Card, Badge, Btn, Field, inputCls, Modal, Spinner, ErrorBox } from '../components/ui';

const PROVIDER_TYPES = ['openrouter', 'openai', 'anthropic', 'deepseek', 'groq', 'ollama', 'azure', 'custom'];

const EMPTY_PROVIDER = {
  name: '', provider_type: 'openrouter', api_key: '', base_url: '',
  default_model: '', is_active: true, is_default: false
};

export default function Ai() {
  // Providers
  const [providers, setProviders] = useState(null);
  const [provError, setProvError] = useState(null);
  const [provModal, setProvModal] = useState(false);
  const [editProv, setEditProv] = useState(null);
  const [provForm, setProvForm] = useState(EMPTY_PROVIDER);
  const [saving, setSaving] = useState(false);
  const [saveError, setSaveError] = useState(null);

  // Chat
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState('');
  const [chatting, setChatting] = useState(false);
  const [chatError, setChatError] = useState(null);
  const [clients, setClients] = useState([]);
  const [clientId, setClientId] = useState('');
  const listRef = useRef(null);

  const loadProviders = () => {
    setProvError(null);
    api.get('/ai/providers').then(setProviders).catch(setProvError);
  };
  useEffect(loadProviders, []);
  useEffect(() => { api.get('/clients').then(setClients).catch(() => {}); }, []);

  useEffect(() => {
    if (listRef.current) listRef.current.scrollTop = listRef.current.scrollHeight;
  }, [messages, chatting]);

  // ---- Provider modal ----
  const openProvNew = () => {
    setEditProv(null);
    setProvForm(EMPTY_PROVIDER);
    setSaveError(null);
    setProvModal(true);
  };
  const openProvEdit = (p) => {
    setEditProv(p);
    setProvForm({
      name: p.name || '', provider_type: p.provider_type || 'openrouter', api_key: '',
      base_url: p.base_url || '', default_model: p.default_model || '',
      is_active: !!p.is_active, is_default: !!p.is_default
    });
    setSaveError(null);
    setProvModal(true);
  };
  const saveProv = async (e) => {
    e.preventDefault();
    setSaving(true);
    setSaveError(null);
    try {
      await api.post('/ai/providers', { ...provForm, id: editProv ? editProv.id : undefined });
      setProvModal(false);
      loadProviders();
    } catch (err) {
      setSaveError(err);
    } finally {
      setSaving(false);
    }
  };
  const deleteProv = async (p) => {
    if (!window.confirm(`Provider "${p.name}" verwijderen?`)) return;
    try {
      await api.del(`/ai/providers/${p.id}`);
      loadProviders();
    } catch (err) {
      alert(err.message || String(err));
    }
  };

  // ---- Chat ----
  const sendMessage = async (e) => {
    e?.preventDefault();
    const msg = input.trim();
    if (!msg || chatting) return;
    setInput('');
    setChatError(null);
    setMessages(prev => [...prev, { role: 'user', content: msg }]);
    setChatting(true);
    try {
      const res = await api.post('/ai/chat', { message: msg, client_id: clientId || undefined });
      setMessages(prev => [...prev, { role: 'assistant', content: res.content, model: res.model }]);
    } catch (err) {
      setChatError(err);
    } finally {
      setChatting(false);
    }
  };

  return (
    <div className="space-y-5 fade-in">
      <div>
        <h1 className="text-xl font-bold tracking-tight">AI</h1>
        <p className="text-[13px] text-muted mt-0.5">Providers beheren en chatten met AI</p>
      </div>

      <div className="grid grid-cols-1 xl:grid-cols-2 gap-4 items-start">
        {/* Providers */}
        <Card
          title="Providers"
          subtitle="Geconfigureerde AI-providers"
          actions={<Btn size="sm" onClick={openProvNew}><Plus className="w-3.5 h-3.5" /> Provider toevoegen</Btn>}
        >
          {provError ? <ErrorBox error={provError} onRetry={loadProviders} /> : !providers ? <Spinner /> : providers.length === 0 ? (
            <div className="text-muted text-[13px] py-6 text-center">Nog geen providers geconfigureerd</div>
          ) : (
            <div className="space-y-2">
              {providers.map(p => (
                <div key={p.id} className="flex items-center gap-3 bg-bg-soft border border-border-soft rounded-lg px-3 py-2.5">
                  <span className={`w-2 h-2 rounded-full shrink-0 ${p.is_active ? 'bg-green' : 'bg-muted/40'}`} title={p.is_active ? 'Actief' : 'Inactief'} />
                  <div className="min-w-0 flex-1">
                    <div className="flex items-center gap-2">
                      <span className="text-[13px] font-medium truncate">{p.name}</span>
                      <Badge color="blue">{p.provider_type}</Badge>
                      {!!p.is_default && <Star className="w-3.5 h-3.5 text-yellow fill-yellow shrink-0" />}
                    </div>
                    <div className="text-[11px] text-muted mt-0.5 truncate">
                      {p.default_model || 'geen model'} {p.api_key ? `· ${p.api_key}` : ''}
                    </div>
                  </div>
                  <button onClick={() => openProvEdit(p)} className="p-1.5 rounded-md text-muted hover:text-text hover:bg-card shrink-0" title="Bewerken">
                    <Pencil className="w-3.5 h-3.5" />
                  </button>
                  <button onClick={() => deleteProv(p)} className="p-1.5 rounded-md text-muted hover:text-red hover:bg-red/10 shrink-0" title="Verwijderen">
                    <Trash2 className="w-3.5 h-3.5" />
                  </button>
                </div>
              ))}
            </div>
          )}
        </Card>

        {/* AI Chat */}
        <Card title="AI Chat" subtitle="Stel een vraag aan de actieve provider" padding={false} className="flex flex-col">
          <div className="px-4 pt-3">
            <select className={inputCls} value={clientId} onChange={e => setClientId(e.target.value)}>
              <option value="">Geen cliënt-context</option>
              {clients.map(c => <option key={c.id} value={c.id}>Koppel aan: {c.name}</option>)}
            </select>
          </div>
          <div ref={listRef} className="flex-1 overflow-y-auto px-4 py-3 space-y-3 min-h-[320px] max-h-[480px]">
            {messages.length === 0 && !chatting && (
              <div className="h-full flex flex-col items-center justify-center text-muted py-12">
                <Bot className="w-8 h-8 mb-2" />
                <div className="text-[13px]">Start een gesprek met de AI</div>
              </div>
            )}
            {messages.map((m, i) => (
              m.role === 'user' ? (
                <div key={i} className="flex justify-end">
                  <div className="max-w-[80%] bg-accent text-bg rounded-2xl rounded-br-sm px-3.5 py-2 text-[13px] whitespace-pre-wrap">
                    {m.content}
                  </div>
                </div>
              ) : (
                <div key={i} className="flex justify-start">
                  <div className="max-w-[80%]">
                    <div className="bg-card border border-border-soft rounded-2xl rounded-bl-sm px-3.5 py-2 text-[13px] whitespace-pre-wrap">
                      {m.content}
                    </div>
                    {m.model && <div className="text-[10px] text-muted mt-1 ml-1">{m.model}</div>}
                  </div>
                </div>
              )
            ))}
            {chatting && (
              <div className="flex justify-start">
                <div className="bg-card border border-border-soft rounded-2xl rounded-bl-sm px-4 py-3 flex items-center gap-1.5">
                  <span className="w-1.5 h-1.5 rounded-full bg-muted animate-bounce" style={{ animationDelay: '0ms' }} />
                  <span className="w-1.5 h-1.5 rounded-full bg-muted animate-bounce" style={{ animationDelay: '150ms' }} />
                  <span className="w-1.5 h-1.5 rounded-full bg-muted animate-bounce" style={{ animationDelay: '300ms' }} />
                </div>
              </div>
            )}
          </div>
          {chatError && <div className="px-4 pb-2"><ErrorBox error={chatError} /></div>}
          <form onSubmit={sendMessage} className="flex items-center gap-2 p-3 border-t border-border-soft">
            <input
              className={inputCls}
              placeholder="Typ je bericht..."
              value={input}
              onChange={e => setInput(e.target.value)}
              disabled={chatting}
            />
            <Btn type="submit" loading={chatting} disabled={!input.trim()}>
              <Send className="w-4 h-4" /> Verstuur
            </Btn>
          </form>
        </Card>
      </div>

      {/* Provider-modal */}
      <Modal open={provModal} onClose={() => setProvModal(false)} title={editProv ? 'Provider bewerken' : 'Provider toevoegen'}>
        <form onSubmit={saveProv} className="space-y-3">
          {saveError && <ErrorBox error={saveError} />}
          <Field label="Naam *">
            <input className={inputCls} value={provForm.name} onChange={e => setProvForm({ ...provForm, name: e.target.value })} required />
          </Field>
          <Field label="Type">
            <select className={inputCls} value={provForm.provider_type} onChange={e => setProvForm({ ...provForm, provider_type: e.target.value })}>
              {PROVIDER_TYPES.map(t => <option key={t} value={t}>{t}</option>)}
            </select>
          </Field>
          <Field label="API-key">
            <input
              type="password"
              className={inputCls}
              value={provForm.api_key}
              onChange={e => setProvForm({ ...provForm, api_key: e.target.value })}
              placeholder={editProv ? 'Leeg laten om te behouden' : 'sk-...'}
            />
          </Field>
          <Field label="Base URL">
            <input className={inputCls} value={provForm.base_url} onChange={e => setProvForm({ ...provForm, base_url: e.target.value })} placeholder="https://..." />
          </Field>
          <Field label="Standaard model">
            <input className={inputCls} value={provForm.default_model} onChange={e => setProvForm({ ...provForm, default_model: e.target.value })} />
          </Field>
          <div className="flex items-center gap-5">
            <label className="flex items-center gap-2 text-[13px] cursor-pointer">
              <input type="checkbox" checked={provForm.is_active} onChange={e => setProvForm({ ...provForm, is_active: e.target.checked })} className="accent-[#00d4ff]" />
              Actief
            </label>
            <label className="flex items-center gap-2 text-[13px] cursor-pointer">
              <input type="checkbox" checked={provForm.is_default} onChange={e => setProvForm({ ...provForm, is_default: e.target.checked })} className="accent-[#00d4ff]" />
              Standaard provider
            </label>
          </div>
          <div className="flex justify-end gap-2 pt-1">
            <Btn variant="secondary" type="button" onClick={() => setProvModal(false)}>Annuleren</Btn>
            <Btn type="submit" loading={saving}>Opslaan</Btn>
          </div>
        </form>
      </Modal>
    </div>
  );
}
