// frontend/src/pages/Compliance/FindingChatDrawer.tsx
import { useEffect, useRef, useState } from 'react';
import { X, Send } from 'lucide-react';
import { useLanguage } from '../../contexts/LanguageContext';

const TOKEN_KEY = 'auth_token';
function authHeader(): Record<string, string> {
  const t = localStorage.getItem(TOKEN_KEY);
  return t ? { Authorization: `Bearer ${t}` } : {};
}

interface Message {
  id: string;
  role: 'user' | 'assistant';
  content: string;
}

interface FindingInfo {
  title: string;
  desc: string;
  status: string;
  clause_ref?: string;
}

interface Props {
  analysisId: string;
  findingId: string;
  finding: FindingInfo;
  onClose: () => void;
}

export function FindingChatDrawer({ analysisId, findingId, finding, onClose }: Props) {
  const [messages, setMessages] = useState<Message[]>([]);
  const [suggestions, setSuggestions] = useState<string[]>([]);
  const [input, setInput] = useState('');
  const [loading, setLoading] = useState(false);
  const [loadingHistory, setLoadingHistory] = useState(true);
  const abortRef = useRef<AbortController | null>(null);
  const bottomRef = useRef<HTMLDivElement>(null);
  const { t } = useLanguage();

  // Load history + suggestions on open
  useEffect(() => {
    setLoadingHistory(true);
    fetch(`/api/v1/compliance/analyses/${analysisId}/findings/${findingId}/chat`, {
      headers: authHeader(),
    })
      .then(r => r.json())
      .then((data: Message[]) => {
        setMessages(Array.isArray(data) ? data.map(m => ({ id: m.id, role: m.role, content: m.content })) : []);
        setLoadingHistory(false);
        if (!data.length) {
          fetch(
            `/api/v1/compliance/analyses/${analysisId}/findings/${findingId}/suggestions`,
            { method: 'POST', headers: authHeader() }
          )
            .then(r => r.json())
            .then(d => { if (Array.isArray(d?.questions)) setSuggestions(d.questions); })
            .catch(() => {});
        }
      })
      .catch(() => setLoadingHistory(false));

    return () => { abortRef.current?.abort(); };
  }, [analysisId, findingId]);

  // Auto-scroll to bottom
  useEffect(() => {
    bottomRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages]);

  async function send(text?: string) {
    const q = (text ?? input).trim();
    if (!q || loading) return;
    setInput('');
    setSuggestions([]); // hide chips after first message

    const assistantId = `ast-${Date.now()}`;
    setMessages(prev => [
      ...prev,
      { id: `usr-${Date.now()}`, role: 'user', content: q },
      { id: assistantId, role: 'assistant', content: '' },
    ]);
    setLoading(true);

    const ctrl = new AbortController();
    abortRef.current = ctrl;

    try {
      const res = await fetch(
        `/api/v1/compliance/analyses/${analysisId}/findings/${findingId}/chat`,
        {
          method: 'POST',
          headers: { 'Content-Type': 'application/json', ...authHeader() },
          body: JSON.stringify({ query: q }),
          signal: ctrl.signal,
        }
      );
      if (!res.body) { setLoading(false); return; }
      const reader = res.body.getReader();
      const dec = new TextDecoder();
      let buf = '';

      while (true) {
        const { done, value } = await reader.read();
        if (done) break;
        buf += dec.decode(value, { stream: true });
        const blocks = buf.split('\n\n');
        buf = blocks.pop() ?? '';
        for (const block of blocks) {
          const dl = block.split('\n').find(l => l.startsWith('data: '));
          if (!dl) continue;
          try {
            const j = JSON.parse(dl.slice(6));
            if (j.type === 'chunk' && j.text) {
              setMessages(prev =>
                prev.map(m => m.id === assistantId ? { ...m, content: m.content + (j.text as string) } : m)
              );
            }
          } catch { /* skip */ }
        }
      }
    } catch (e: unknown) {
      if (e instanceof Error && e.name !== 'AbortError') {
        setMessages(prev =>
          prev.map(m => m.id === assistantId ? { ...m, content: 'Error reaching server.' } : m)
        );
      }
    } finally {
      setLoading(false);
    }
  }

  const STATUS_COLOR: Record<string, string> = {
    risk: 'var(--danger, #dc143c)',
    warn: 'var(--warning, #ff8c00)',
    ok: 'var(--success, #228b22)',
  };

  return (
    <div
      style={{
        position: 'fixed', right: 0, top: 0, bottom: 0, width: 420,
        background: 'var(--surface)', borderLeft: '1px solid var(--border)',
        display: 'flex', flexDirection: 'column', zIndex: 200,
        boxShadow: '-4px 0 16px rgba(0,0,0,0.12)',
      }}
    >
      {/* Header */}
      <div style={{
        padding: '14px 16px', borderBottom: '1px solid var(--border)',
        display: 'flex', alignItems: 'flex-start', gap: 10,
      }}>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 11, color: STATUS_COLOR[finding.status] ?? 'var(--muted)', fontWeight: 600, marginBottom: 2 }}>
            {finding.status.toUpperCase()}
            {finding.clause_ref && (
              <span style={{ fontWeight: 400, marginLeft: 6, color: 'var(--muted)' }}>
                {finding.clause_ref}
              </span>
            )}
          </div>
          <div style={{ fontSize: 13, fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
            {finding.title}
          </div>
          <div style={{ fontSize: 11, color: 'var(--muted)', marginTop: 2, lineHeight: 1.4 }}>
            {finding.desc.length > 100 ? finding.desc.slice(0, 100) + '…' : finding.desc}
          </div>
        </div>
        <button className="btn icon-btn" onClick={onClose} style={{ flexShrink: 0 }} title={t.compliance.drawerClose}>
          <X size={14} />
        </button>
      </div>

      {/* Suggestion chips */}
      {suggestions.length > 0 && (
        <div style={{ padding: '10px 16px', borderBottom: '1px solid var(--border)' }}>
          <div style={{ fontSize: 11, color: 'var(--muted)', marginBottom: 6 }}>{t.compliance.drawerSuggestionsHeader}</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            {suggestions.map((q, i) => (
              <button
                key={i}
                className="chip"
                style={{ textAlign: 'left', whiteSpace: 'normal', height: 'auto', padding: '6px 10px' }}
                onClick={() => send(q)}
              >
                {q}
              </button>
            ))}
          </div>
        </div>
      )}

      {/* Messages */}
      <div style={{ flex: 1, overflowY: 'auto', padding: '12px 16px', display: 'flex', flexDirection: 'column', gap: 10 }}>
        {loadingHistory && (
          <p style={{ fontSize: 12, color: 'var(--muted)', textAlign: 'center' }}>Loading history…</p>
        )}
        {!loadingHistory && messages.length === 0 && (
          <p style={{ fontSize: 12, color: 'var(--muted)', textAlign: 'center' }}>{t.compliance.drawerChatEmpty}</p>
        )}
        {messages.map(msg => (
          <div key={msg.id} className={`message msg-${msg.role}`} style={{ maxWidth: '100%' }}>
            {msg.role === 'assistant' && <div className="msg-avatar">AI</div>}
            <div className="msg-bubble" style={{ fontSize: 13, whiteSpace: 'pre-wrap' }}>
              {msg.content || (loading ? '…' : '')}
            </div>
            {msg.role === 'user' && <div className="msg-avatar user-av">You</div>}
          </div>
        ))}
        <div ref={bottomRef} />
      </div>

      {/* Composer */}
      <div style={{ padding: '10px 16px', borderTop: '1px solid var(--border)', display: 'flex', gap: 8 }}>
        <textarea
          className="composer-input"
          placeholder={t.compliance.chatPlaceholder}
          value={input}
          rows={2}
          style={{ flex: 1, fontSize: 13 }}
          onChange={e => setInput(e.target.value)}
          onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); void send(); } }}
        />
        <button
          className="btn primary"
          disabled={!input.trim() || loading}
          onClick={() => void send()}
          style={{ alignSelf: 'flex-end' }}
          title={t.compliance.sendBtn}
        >
          <Send size={14} />
        </button>
      </div>
    </div>
  );
}
