import { Head, usePage } from '@inertiajs/react';
import { useState, useRef, useEffect } from 'react';
import { Sparkles, Send, TrendingUp, TrendingDown, Lightbulb } 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 };
type Suggestion = { label: string; prompt: string };

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[] };
        suggestions?: Suggestion[];
    };
    const suggestions = props.suggestions ?? [];

    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(text?: string) {
        const message = (text ?? input).trim();
        if (!message || busy) return;
        setInput('');
        setMessages((m) => [...m, { role: 'user', content: message }]);
        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, conversation_id: convId }),
            });
            if (res.status === 429) {
                setMessages((m) => [...m, { role: 'assistant', content: 'Your organization has reached its daily AI usage limit.' }]);
            } else if (!res.ok) {
                setMessages((m) => [...m, { role: 'assistant', content: 'The analyst is unavailable. Check that an AI key is set in Integration Settings.' }]);
            } 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">
                        <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-center text-sm text-muted-foreground">
                            Answers come only from your governed metrics — with exact periods and sources, never guessed.
                        </p>

                        {suggestions.length > 0 && (
                            <div className="mt-8 w-full max-w-xl">
                                <p className="mb-3 flex items-center justify-center gap-1.5 text-xs font-medium text-muted-foreground">
                                    <Lightbulb className="size-3.5" /> Try one of these
                                </p>
                                <div className="grid gap-2 sm:grid-cols-2">
                                    {suggestions.map((s) => (
                                        <button key={s.prompt} onClick={() => send(s.prompt)}
                                            className="rounded-xl border border-border bg-card p-3 text-left transition hover:border-primary/40 hover:shadow-sm">
                                            <span className="block text-sm font-medium text-foreground">{s.label}</span>
                                            <span className="mt-0.5 block text-xs text-muted-foreground">{s.prompt}</span>
                                        </button>
                                    ))}
                                </div>
                            </div>
                        )}
                    </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) => <ArtifactCard 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">
                    {messages.length > 0 && suggestions.length > 0 && (
                        <div className="mb-2 flex flex-wrap gap-1.5">
                            {suggestions.slice(0, 4).map((s) => (
                                <button key={s.prompt} onClick={() => send(s.prompt)} disabled={busy}
                                    className="rounded-full border border-border px-2.5 py-1 text-xs text-muted-foreground transition hover:border-primary/40 hover:text-foreground disabled:opacity-50">
                                    {s.label}
                                </button>
                            ))}
                        </div>
                    )}
                    <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, vacancies, rent roll…" 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 ArtifactCard({ 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 && a.change_percent !== undefined && (
                        <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)}%
                        </span>
                    )}
                </div>
                <p className="mt-1 text-[11px] text-muted-foreground">vs {fmt(a.previous, a.unit)} previous period</p>
            </div>
        );
    }
    return null;
}
