import React, { useState, useRef, useEffect } from 'react';
import type { Locale, LangCode } from './i18n';
import { jsonHeaders } from './csrf';

const OWL_SRC = '/assets/owl.png';
const CHAT_STORE = 'fo_chat_v1';

type ChatRole = 'user' | 'assistant';
interface ChatMessage {
    role: ChatRole;
    text: string;
}

async function sendToBackend(messages: ChatMessage[], lang: LangCode): Promise<string> {
    const res = await fetch('/api/chat', {
        method: 'POST',
        headers: jsonHeaders(),
        body: JSON.stringify({
            lang,
            messages: messages.map((m) => ({ role: m.role, content: m.text })),
        }),
    });
    if (!res.ok) throw new Error('chat backend error');
    const data = (await res.json()) as { reply?: string };
    return (data.reply ?? '').trim();
}

export function Chatbot({ t, lang }: { t: Locale; lang: LangCode }) {
    const c = t.chat;
    const [open, setOpen] = useState(false);
    const [msgs, setMsgs] = useState<ChatMessage[]>(() => {
        try {
            const s = JSON.parse(localStorage.getItem(CHAT_STORE) ?? 'null');
            if (Array.isArray(s) && s.length) return s as ChatMessage[];
        } catch {
            // ignore
        }
        return [];
    });
    const [input, setInput] = useState('');
    const [busy, setBusy] = useState(false);
    const [unread, setUnread] = useState(false);
    const scrollRef = useRef<HTMLDivElement | null>(null);
    const inputRef = useRef<HTMLInputElement | null>(null);

    useEffect(() => {
        try {
            localStorage.setItem(CHAT_STORE, JSON.stringify(msgs));
        } catch {
            // ignore
        }
    }, [msgs]);

    useEffect(() => {
        if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
    }, [msgs, busy, open]);

    useEffect(() => {
        if (open) {
            setUnread(false);
            setTimeout(() => inputRef.current?.focus(), 250);
        }
    }, [open]);

    const send = async (text: string) => {
        const clean = (text || '').trim();
        if (!clean || busy) return;
        const next: ChatMessage[] = [...msgs, { role: 'user', text: clean }];
        setMsgs(next);
        setInput('');
        setBusy(true);
        try {
            const reply = await sendToBackend(next, lang);
            setMsgs((m) => [...m, { role: 'assistant', text: reply || c.error }]);
            if (!open) setUnread(true);
        } catch {
            setMsgs((m) => [...m, { role: 'assistant', text: c.error }]);
        } finally {
            setBusy(false);
        }
    };

    const onSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        send(input);
    };
    const reset = () => {
        setMsgs([]);
        try {
            localStorage.removeItem(CHAT_STORE);
        } catch {
            // ignore
        }
    };

    const showQuick = msgs.length === 0;

    return (
        <div className={'chat' + (open ? ' open' : '')}>
            <button className="chat-launch" onClick={() => setOpen((o) => !o)} aria-label={c.launch}>
                <span className="chat-launch-icon" aria-hidden="true">
                    {open ? (
                        <svg viewBox="0 0 24 24" width="22" height="22">
                            <path d="M6 6l12 12M18 6L6 18" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" />
                        </svg>
                    ) : (
                        <img src={OWL_SRC} alt="" />
                    )}
                </span>
                {!open && <span className="chat-launch-label">{c.launch}</span>}
                {!open && unread && <span className="chat-dot" />}
            </button>

            <div className="chat-panel" role="dialog" aria-label={c.title} aria-hidden={!open}>
                <header className="chat-head">
                    <span className="chat-avatar"><img src={OWL_SRC} alt="" /></span>
                    <div className="chat-id">
                        <strong>{c.title}</strong>
                        <span>
                            <i className="chat-online" />
                            {c.subtitle} · {c.status}
                        </span>
                    </div>
                    <div className="chat-head-actions">
                        {msgs.length > 0 && (
                            <button className="chat-reset" onClick={reset} title={c.reset} aria-label={c.reset}>
                                <svg viewBox="0 0 24 24" width="16" height="16">
                                    <path d="M4 7h16M9 7V5h6v2M7 7l1 13h8l1-13" stroke="currentColor" strokeWidth="1.7" fill="none" strokeLinecap="round" strokeLinejoin="round" />
                                </svg>
                            </button>
                        )}
                        <button className="chat-close" onClick={() => setOpen(false)} aria-label="Close">
                            <svg viewBox="0 0 24 24" width="18" height="18">
                                <path d="M6 6l12 12M18 6L6 18" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" />
                            </svg>
                        </button>
                    </div>
                </header>

                <div className="chat-body" ref={scrollRef}>
                    <div className="chat-msg bot">
                        <span className="chat-msg-av"><img src={OWL_SRC} alt="" /></span>
                        <div className="chat-bubble">{c.greeting}</div>
                    </div>
                    {msgs.map((m, i) => (
                        <div className={'chat-msg ' + (m.role === 'user' ? 'user' : 'bot')} key={i}>
                            {m.role === 'assistant' ? (
                                <span className="chat-msg-av"><img src={OWL_SRC} alt="" /></span>
                            ) : null}
                            <div className="chat-bubble">{m.text}</div>
                        </div>
                    ))}
                    {busy && (
                        <div className="chat-msg bot">
                            <span className="chat-msg-av"><img src={OWL_SRC} alt="" /></span>
                            <div className="chat-bubble chat-typing">
                                <span />
                                <span />
                                <span />
                            </div>
                        </div>
                    )}
                    {showQuick && !busy && (
                        <div className="chat-quick">
                            {c.quick.map((q) => (
                                <button key={q} onClick={() => send(q)}>{q}</button>
                            ))}
                        </div>
                    )}
                </div>

                <form className="chat-input" onSubmit={onSubmit}>
                    <input
                        ref={inputRef}
                        type="text"
                        value={input}
                        placeholder={c.placeholder}
                        onChange={(e) => setInput(e.target.value)}
                        aria-label={c.placeholder}
                    />
                    <button type="submit" disabled={busy || !input.trim()} aria-label="Send">
                        <svg viewBox="0 0 24 24" width="20" height="20">
                            <path d="M4 12l16-8-6 16-3-6-7-2z" fill="currentColor" />
                        </svg>
                    </button>
                </form>
                <div className="chat-foot">{c.disclaimer}</div>
            </div>
        </div>
    );
}
