import { ArrowUp, Bot, Loader2, SquarePen, Sparkles, Sun } from 'lucide-react';
import { useEffect, useRef, useState } from 'react';

import { apiFetch } from '@/lib/loading/api-fetch';
import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';

import { BlockRenderer } from './blocks';
import { renderRichText } from './format';
import type { ChatbotBlock } from './types';
import { useChatbot } from './use-chatbot';

interface BriefingInsight {
    severity?: string;
    title: string;
    detail?: string | null;
    question: string;
}

/**
 * Starter questions on the empty state — the highest-"wow" prompts, each producing
 * a rich, clickable render (dashboard / pie / bar / daily line). The month is derived
 * from today's date so the suggestions stay current instead of naming a fixed month.
 */
function starterQuestions(): string[] {
    const mois = new Date().toLocaleDateString('fr-FR', { month: 'long', year: 'numeric' });
    return [
        `Fais le point sur ${mois}`,
        `Revenu par canal en ${mois}`,
        'Top 5 des logements par revenu cette année',
        `Évolution du revenu jour par jour en ${mois}`,
    ];
}

/** Gather up to 4 follow-up questions from a message's blocks (their drill hints). */
function collectFollowups(blocks: ChatbotBlock[]): string[] {
    const out: string[] = [];
    const push = (s?: string | null) => {
        if (s && !out.includes(s) && out.length < 4) out.push(s);
    };
    const walk = (bs: ChatbotBlock[]) => {
        for (const b of bs) {
            if (b.type === 'chart') b.data.forEach((d) => push(d.drill));
            else if (b.type === 'properties') b.items.forEach((p) => push(p.drill));
            else if (b.type === 'reservations') b.rows.forEach((r) => push(r.drill));
            else if (b.type === 'table') b.rowDrills?.forEach(push);
            else if (b.type === 'stat') push(b.drill);
            else if (b.type === 'dashboard') walk(b.blocks);
            else if (b.type === 'profile' && b.blocks) walk(b.blocks);
        }
    };
    walk(blocks);
    return out;
}

/** Shared conversation surface used by both the floating widget and the full page. */
export function ChatbotConversation({ className }: { className?: string }) {
    const { messages, loading, send, reset } = useChatbot();
    const [input, setInput] = useState('');
    const endRef = useRef<HTMLDivElement>(null);

    const lastAssistant = [...messages].reverse().find((m) => m.role === 'assistant' && !m.error);
    const followups = lastAssistant?.blocks ? collectFollowups(lastAssistant.blocks) : [];
    const suggestions = starterQuestions();

    const [briefing, setBriefing] = useState<BriefingInsight[]>([]);
    useEffect(() => {
        let alive = true;
        apiFetch('/chatbot/briefing/today')
            .then((r) => (r.ok ? r.json() : { insights: [] }))
            .then((d) => {
                if (alive && Array.isArray(d.insights)) setBriefing(d.insights);
            })
            .catch(() => {});
        return () => {
            alive = false;
        };
    }, []);

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

    const submit = () => {
        if (!input.trim() || loading) {
            return;
        }
        send(input);
        setInput('');
    };

    const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            submit();
        }
    };

    const handleChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
        setInput(e.target.value);
        const el = e.target;
        el.style.height = 'auto';
        el.style.height = `${Math.min(el.scrollHeight, 128)}px`;
    };

    return (
        <div className={cn('flex h-full flex-col', className)}>
            {messages.length > 0 && (
                <div className="flex justify-end border-b border-border/60 px-3 py-1.5">
                    <button
                        type="button"
                        onClick={reset}
                        disabled={loading}
                        className="inline-flex items-center gap-1.5 rounded-md px-2 py-1 text-xs text-muted-foreground transition hover:bg-accent hover:text-foreground disabled:opacity-50"
                    >
                        <SquarePen className="size-3.5" /> Nouvelle conversation
                    </button>
                </div>
            )}
            <div className="flex-1 space-y-4 overflow-y-auto p-4">
                {messages.length === 0 && (
                    <div className="flex h-full flex-col items-center justify-center gap-4 text-center">
                        <div className="flex size-12 items-center justify-center rounded-2xl bg-gradient-to-br from-primary to-secondary text-primary-foreground shadow-md">
                            <Sparkles className="size-6" />
                        </div>
                        <div>
                            <div className="font-semibold">Assistant d'analyse</div>
                            <p className="mt-1 max-w-xs text-sm text-muted-foreground">
                                Posez une question sur vos logements, réservations, prix ou revenus.
                            </p>
                        </div>
                        {briefing.length > 0 && (
                            <div className="w-full max-w-md rounded-2xl border border-secondary/30 bg-secondary/5 p-3 text-left">
                                <div className="mb-2 flex items-center gap-1.5 text-xs font-semibold text-primary">
                                    <Sun className="size-3.5" /> À regarder aujourd'hui
                                </div>
                                <div className="space-y-1.5">
                                    {briefing.map((b, i) => (
                                        <button
                                            key={i}
                                            type="button"
                                            onClick={() => send(b.question)}
                                            className="flex w-full items-start gap-2 rounded-lg border border-border bg-card px-2.5 py-1.5 text-left text-xs transition hover:border-secondary"
                                        >
                                            <span
                                                className={cn(
                                                    'mt-1 size-1.5 shrink-0 rounded-full',
                                                    b.severity === 'high'
                                                        ? 'bg-red-500'
                                                        : b.severity === 'medium'
                                                          ? 'bg-amber-500'
                                                          : 'bg-secondary',
                                                )}
                                            />
                                            <span>
                                                <span className="font-medium text-foreground">{b.title}</span>
                                                {b.detail && <span className="block text-muted-foreground">{b.detail}</span>}
                                            </span>
                                        </button>
                                    ))}
                                </div>
                            </div>
                        )}

                        <div className="flex flex-wrap justify-center gap-2">
                            {suggestions.map((s) => (
                                <button
                                    key={s}
                                    type="button"
                                    onClick={() => send(s)}
                                    className="rounded-full border border-border bg-card px-3 py-1.5 text-xs text-muted-foreground transition hover:border-secondary hover:text-foreground"
                                >
                                    {s}
                                </button>
                            ))}
                        </div>
                    </div>
                )}

                {messages.map((m) => (
                    <div key={m.id} className={cn('flex gap-2', m.role === 'user' ? 'justify-end' : 'justify-start')}>
                        {m.role === 'assistant' && (
                            <div className="mt-0.5 flex size-7 shrink-0 items-center justify-center rounded-lg bg-primary text-primary-foreground">
                                <Bot className="size-4" />
                            </div>
                        )}
                        <div
                            className={cn(
                                'space-y-3',
                                m.role === 'user' ? 'max-w-[85%]' : 'min-w-0 flex-1',
                            )}
                        >
                            {m.content &&
                                (m.role === 'assistant' && !m.error ? (
                                    <div
                                        className="chatbot-prose w-fit max-w-full space-y-1.5 rounded-2xl bg-muted px-3.5 py-2 text-sm leading-relaxed text-foreground"
                                        dangerouslySetInnerHTML={{ __html: renderRichText(m.content) }}
                                    />
                                ) : (
                                    <div
                                        className={cn(
                                            'rounded-2xl px-3.5 py-2 text-sm leading-relaxed whitespace-pre-wrap',
                                            m.role === 'user'
                                                ? 'bg-primary text-primary-foreground'
                                                : 'bg-destructive/10 text-destructive',
                                        )}
                                    >
                                        {m.content}
                                    </div>
                                ))}
                            {m.blocks && m.blocks.length > 0 && (
                                <div className="space-y-3">
                                    {m.blocks.map((b, i) => (
                                        <BlockRenderer key={i} block={b} onDrill={send} />
                                    ))}
                                </div>
                            )}
                            {m.id === lastAssistant?.id && followups.length > 0 && !loading && (
                                <div className="flex flex-wrap gap-2 pt-1">
                                    {followups.map((f) => (
                                        <button
                                            key={f}
                                            type="button"
                                            onClick={() => send(f)}
                                            className="rounded-full border border-border bg-card px-2.5 py-1 text-xs text-muted-foreground transition hover:border-secondary hover:text-foreground"
                                        >
                                            {f}
                                        </button>
                                    ))}
                                </div>
                            )}
                        </div>
                    </div>
                ))}

                {loading && (
                    <div className="flex items-center gap-2">
                        <div className="flex size-7 shrink-0 items-center justify-center rounded-lg bg-primary text-primary-foreground">
                            <Bot className="size-4" />
                        </div>
                        <span className="inline-flex items-center gap-2 rounded-2xl bg-muted px-3.5 py-2 text-sm text-muted-foreground">
                            <Loader2 className="size-4 animate-spin" /> Analyse en cours…
                        </span>
                    </div>
                )}
                <div ref={endRef} />
            </div>

            <div className="border-t border-border p-3">
                <div className="flex items-end gap-2 rounded-2xl border border-border bg-card p-1.5 focus-within:border-secondary">
                    <textarea
                        value={input}
                        onChange={handleChange}
                        onKeyDown={handleKeyDown}
                        rows={1}
                        placeholder="Posez votre question…"
                        className="max-h-32 flex-1 resize-none bg-transparent px-2 py-1.5 text-sm outline-none"
                    />
                    <Button
                        size="icon"
                        onClick={submit}
                        disabled={loading || !input.trim()}
                        className="size-8 shrink-0 rounded-xl"
                        aria-label="Envoyer"
                    >
                        {loading ? <Loader2 className="size-4 animate-spin" /> : <ArrowUp className="size-4" />}
                    </Button>
                </div>
                <p className="mt-1.5 px-1 text-[10px] text-muted-foreground">
                    Les réponses sont générées par IA — vérifiez les chiffres importants.
                </p>
            </div>
        </div>
    );
}
