import { Head, usePage } from '@inertiajs/react';
import { useState, useRef, useEffect } from 'react';
import { Sparkles, Send, TrendingUp, TrendingDown } from 'lucide-react';

type Artifact = {
    type: string; metric?: string; value?: number | null; unit?: string;
    period?: { start: string; end: string }; source?: string; freshness?: string;
    current?: number | null; previous?: number | null; change_percent?: number | null;
};
type Msg = { role: string; content: string; artifacts?: Artifact[] | null };

function fmt(v: number | null | undefined, unit = 'number') {
    if (v === null || v === undefined) return '—';
    if (unit === 'currency') return '$' + v.toLocaleString(undefined, { maximumFractionDigits: 0 });
    if (unit === 'percent') return v + '%';
    return v.toLocaleString();
}

export default function AiAnalyst() {
    const props = usePage().props as unknown as { conversation?: { id: number; messages: Msg[] } };
    const [messages, setMessages] = useState<Msg[]>(props.conversation?.messages ?? []);
    const [convId, setConvId] = useState<number | null>(props.conversation?.id ?? null);
    const [input, setInput] = useState('');
    const [busy, setBusy] = useState(false);
    const endRef = useRef<HTMLDivElement>(null);

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

    async function send() {
        const text = input.trim();
        if (!text || busy) return;
        setInput('');
        setMessages((m) => [...m, { role: 'user', content: text }]);
        setBusy(true);
        try {
            const res = await fetch('/ai/ask', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': (document.querySelector('meta[name=csrf-token]') as HTMLMetaElement)?.content ?? '',
                    'X-Requested-With': 'XMLHttpRequest',
                },
                body: JSON.stringify({ message: text, conversation_id: convId }),
            });
            if (res.status === 429) {
                setMessages((m) => [...m, { role: 'assistant', content: 'Your organization has reached its daily AI usage limit.' }]);
            } else {
                const data = await res.json();
                setConvId(data.conversation_id);
                setMessages((m) => [...m, { role: 'assistant', content: data.answer.content, artifacts: data.answer.artifacts }]);
            }
        } catch {
            setMessages((m) => [...m, { role: 'assistant', content: 'Something went wrong reaching the analyst. Please try again.' }]);
        } finally {
            setBusy(false);
        }
    }

    return (
        <>
            <Head title="AI Analyst" />
            <div className="mx-auto flex h-[calc(100dvh-4rem)] w-full max-w-3xl flex-col px-6">
                {messages.length === 0 ? (
                    <div className="flex flex-1 flex-col items-center justify-center text-center">
                        <span className="flex size-12 items-center justify-center rounded-xl bg-primary/10">
                            <Sparkles className="size-6 text-primary" />
                        </span>
                        <h1 className="mt-4 text-2xl font-semibold text-foreground">Ask your data anything</h1>
                        <p className="mt-2 max-w-md text-sm text-muted-foreground">
                            Answers come only from your governed metrics — with exact periods and sources, never guessed.
                        </p>
                    </div>
                ) : (
                    <div className="flex-1 space-y-4 overflow-y-auto py-6">
                        {messages.map((m, i) => (
                            <div key={i} className={m.role === 'user' ? 'flex justify-end' : 'flex justify-start'}>
                                <div className={`max-w-[85%] rounded-2xl px-4 py-2.5 text-sm ${m.role === 'user' ? 'bg-primary text-primary-foreground' : 'bg-muted text-foreground'}`}>
                                    <p className="whitespace-pre-wrap">{m.content}</p>
                                    {m.artifacts?.map((a, j) => <Artifact key={j} a={a} />)}
                                </div>
                            </div>
                        ))}
                        {busy && <div className="flex justify-start"><div className="rounded-2xl bg-muted px-4 py-2.5 text-sm text-muted-foreground">Analyzing…</div></div>}
                        <div ref={endRef} />
                    </div>
                )}

                <div className="border-t border-border py-4">
                    <div className="flex items-end gap-2 rounded-xl border border-border bg-background p-2">
                        <textarea
                            value={input} onChange={(e) => setInput(e.target.value)}
                            onKeyDown={(e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); } }}
                            placeholder="Ask about occupancy, rent collected, leads…" rows={1}
                            className="flex-1 resize-none bg-transparent px-2 py-1.5 text-sm outline-none" />
                        <button onClick={send} disabled={busy || !input.trim()}
                            className="flex size-9 items-center justify-center rounded-lg bg-primary text-primary-foreground hover:opacity-90 disabled:opacity-40">
                            <Send className="size-4" />
                        </button>
                    </div>
                </div>
            </div>
        </>
    );
}

function Artifact({ a }: { a: Artifact }) {
    if (a.type === 'metric') {
        return (
            <div className="mt-2 rounded-lg border border-border bg-card p-3">
                <p className="text-xs text-muted-foreground">{a.metric}</p>
                <p className="text-xl font-semibold text-foreground">{fmt(a.value, a.unit)}</p>
                {a.period && <p className="mt-1 text-[11px] text-muted-foreground">{a.period.start} → {a.period.end} · {a.source} · {a.freshness}</p>}
            </div>
        );
    }
    if (a.type === 'comparison') {
        const up = (a.change_percent ?? 0) >= 0;
        return (
            <div className="mt-2 rounded-lg border border-border bg-card p-3">
                <p className="text-xs text-muted-foreground">{a.metric}</p>
                <div className="flex items-baseline gap-2">
                    <p className="text-xl font-semibold text-foreground">{fmt(a.current, a.unit)}</p>
                    {a.change_percent !== null && (
                        <span className={`inline-flex items-center gap-0.5 text-xs font-medium ${up ? 'text-emerald-600' : 'text-destructive'}`}>
                            {up ? <TrendingUp className="size-3" /> : <TrendingDown className="size-3" />}
                            {Math.abs(a.change_percent ?? 0)}%
                        </span>
                    )}
                </div>
                <p className="mt-1 text-[11px] text-muted-foreground">vs {fmt(a.previous, a.unit)} previous period</p>
            </div>
        );
    }
    return null;
}
