import { useState, useRef, useEffect, useCallback } from "react";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { parse } from "marked";

// ─── Tipos ─────────────────────────────────────────────────────────────────────
type ChatMessage = {
    id?: number;
    role: "user" | "assistant";
    text: string;
    time: string;
};

type Conversation = {
    id: string;
    title: string;
    messages: ChatMessage[];
    startedAt: string;
};

// ─── Ícones ────────────────────────────────────────────────────────────────────
function ExpandIcon({ expanded }: { expanded: boolean }) {
    return (
        <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24"
             fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            {expanded ? (
                <>
                    <polyline points="15 18 9 12 15 6" />
                    <polyline points="9 18 3 12 9 6" transform="scale(-1,1) translate(-24,0)" />
                </>
            ) : (
                <>
                    <polyline points="13 17 18 12 13 7" />
                    <polyline points="11 17 6 12 11 7" />
                </>
            )}
        </svg>
    );
}

function PlusIcon() {
    return (
        <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24"
             fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
            <line x1="12" y1="5" x2="12" y2="19" /><line x1="5" y1="12" x2="19" y2="12" />
        </svg>
    );
}

function HistoryIcon() {
    return (
        <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24"
             fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <polyline points="1 4 1 10 7 10" />
            <path d="M3.51 15a9 9 0 1 0 .49-4.95" />
        </svg>
    );
}

function SpinnerIcon() {
    return (
        <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24"
             fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"
             className="animate-spin">
            <path d="M21 12a9 9 0 1 1-6.219-8.56" />
        </svg>
    );
}

function TrashIcon() {
    return (
        <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24"
             fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <polyline points="3 6 5 6 21 6" />
            <path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6" />
            <path d="M10 11v6" />
            <path d="M14 11v6" />
            <path d="M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2" />
        </svg>
    );
}

// ─── Header ────────────────────────────────────────────────────────────────────
function ChatHeader({
                        toggleId, expanded, onToggleExpand, onNewChat, hasActiveConversation,
                    }: {
    toggleId: string; expanded: boolean;
    onToggleExpand: () => void; onNewChat: () => void; hasActiveConversation: boolean;
}) {
    return (
        <header className="flex items-center justify-between border-b border-slate-200 bg-white/90 px-5 py-4 backdrop-blur shrink-0">
            <div className="flex items-center gap-3">
                <div className="relative">
                    <Avatar className="h-10 w-10 overflow-hidden rounded-full ring-2 ring-emerald-100">
                        <AvatarImage src="/laura.png" alt="Laura" />
                        <AvatarFallback className="bg-neutral-200 text-black text-sm font-semibold">LP</AvatarFallback>
                    </Avatar>
                    <span className="absolute bottom-0 right-0 h-2.5 w-2.5 rounded-full bg-emerald-400 ring-2 ring-white" />
                </div>
                <div>
                    <div className="flex items-center gap-1.5">
                        <h2 className="text-sm font-semibold text-slate-900 leading-tight">Laura</h2>
                        <span className="rounded-full bg-amber-100 px-1.5 py-0.5 text-[9px] font-bold uppercase tracking-wide text-amber-600">
                            beta
                        </span>
                    </div>
                    <p className="text-xs text-emerald-500 font-medium">Online agora</p>
                </div>
            </div>
            <div className="flex items-center gap-2">
                {hasActiveConversation && (
                    <button type="button" onClick={onNewChat}
                            className="cursor-pointer rounded-full border border-slate-200 px-3 py-1.5 text-xs font-medium text-slate-500 transition hover:border-slate-300 hover:text-slate-900 hover:bg-slate-50 flex items-center gap-1.5">
                        <PlusIcon /> Nova
                    </button>
                )}
                <button type="button" onClick={onToggleExpand}
                        className="cursor-pointer rounded-full border border-slate-200 px-3 py-1.5 text-xs font-medium text-slate-500 transition hover:border-slate-300 hover:text-slate-900 hover:bg-slate-50 flex items-center gap-1.5">
                    <ExpandIcon expanded={expanded} />
                    {expanded ? "Recolher" : "Expandir"}
                </button>
                <label htmlFor={toggleId}
                       className="cursor-pointer rounded-full border border-slate-200 px-3 py-1.5 text-xs font-medium text-slate-500 transition hover:border-slate-300 hover:text-slate-900 hover:bg-slate-50">
                    Fechar
                </label>
            </div>
        </header>
    );
}

// ─── Lista de conversas recentes ───────────────────────────────────────────────
function RecentConversations({
                                 conversations, loading, onSelect, onNewChat, onDelete,
                             }: {
    conversations: Conversation[];
    loading: boolean;
    onSelect: (conv: Conversation) => void;
    onNewChat: () => void;
    onDelete: (id: string) => void;
}) {
    return (
        <div className="flex flex-col h-full">
            <div className="flex items-center gap-2 px-5 pt-5 pb-3">
                <HistoryIcon />
                <span className="text-xs font-semibold uppercase tracking-widest text-slate-400">
                    Conversas recentes
                </span>
            </div>

            <div className="flex-1 overflow-y-auto px-3 pb-3 space-y-1">
                {loading ? (
                    <div className="flex items-center gap-2 px-2 py-4 text-xs text-slate-400">
                        <SpinnerIcon /> Carregando...
                    </div>
                ) : conversations.length === 0 ? (
                    <p className="text-xs text-slate-400 px-2 py-2">Nenhuma conversa ainda.</p>
                ) : (
                    conversations.map((conv) => (
                        <div key={conv.id} className="group flex items-center gap-1 rounded-xl px-2 hover:bg-white hover:shadow-sm transition">
                            {/* Linha clicável */}
                            <button type="button" onClick={() => onSelect(conv)}
                                    className="flex-1 text-left flex items-start gap-3 py-3 px-2 min-w-0">
                                <div className="mt-0.5 h-7 w-7 shrink-0 rounded-full bg-slate-100 flex items-center justify-center text-slate-400 group-hover:bg-emerald-50 group-hover:text-emerald-500 transition">
                                    <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24"
                                         fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                                        <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />
                                    </svg>
                                </div>
                                <div className="min-w-0">
                                    <p className="text-sm font-medium text-slate-700 truncate leading-tight">{conv.title}</p>
                                    <p className="text-xs text-slate-400 mt-0.5">{conv.startedAt}</p>
                                </div>
                            </button>

                            {/* Botão deletar — aparece no hover */}
                            <button
                                type="button"
                                onClick={(e) => { e.stopPropagation(); onDelete(conv.id); }}
                                title="Deletar conversa"
                                className="shrink-0 p-1.5 rounded-lg text-slate-300 opacity-0 group-hover:opacity-100 hover:text-red-500 hover:bg-red-50 transition-all duration-150"
                            >
                                <TrashIcon />
                            </button>
                        </div>
                    ))
                )}
            </div>

            <div className="px-5 pb-5 pt-2 border-t border-slate-100">
                <button type="button" onClick={onNewChat}
                        className="w-full flex items-center justify-center gap-2 rounded-2xl bg-slate-900 py-2.5 text-sm font-semibold text-white transition hover:bg-slate-700">
                    <PlusIcon /> Nova conversa
                </button>
            </div>
        </div>
    );
}

// ─── Typing indicator ──────────────────────────────────────────────────────────
function TypingIndicator() {
    return (
        <div className="mr-auto w-fit">
            <div className="rounded-2xl rounded-tl-sm bg-white px-4 py-3 shadow flex items-center gap-1">
                {[0, 150, 300].map((delay) => (
                    <span key={delay} className="inline-block h-2 w-2 rounded-full bg-slate-400 animate-bounce"
                          style={{ animationDelay: `${delay}ms` }} />
                ))}
            </div>
        </div>
    );
}

// ─── Bolha ─────────────────────────────────────────────────────────────────────
function ChatBubble({ message }: { message: ChatMessage }) {
    const isUser = message.role === "user";
    const messageHtml = parse(message?.text) as string;

    return (
        <div className={`flex flex-col w-full ${isUser ? "items-end" : "items-start"}`}
             style={{ animation: "fadeSlideIn 0.2s ease-out forwards" }}>
            <div className={isUser
                ? "rounded-2xl rounded-tr-sm bg-slate-900 px-4 py-2.5 text-sm text-white shadow max-w-[80%] break-words"
                : "rounded-2xl rounded-tl-sm bg-white px-4 py-3 text-sm text-slate-700 shadow w-full box-border overflow-hidden"
            }>
                <div
                    className={isUser ? "leading-relaxed" : [
                        "prose prose-sm max-w-none leading-relaxed",
                        "[&_h1]:text-base [&_h1]:font-bold [&_h1]:mt-3 [&_h1]:mb-1",
                        "[&_h2]:text-sm [&_h2]:font-bold [&_h2]:mt-3 [&_h2]:mb-1",
                        "[&_h3]:text-sm [&_h3]:font-semibold [&_h3]:mt-2 [&_h3]:mb-1",
                        "[&_p]:my-1 [&_p]:leading-relaxed",
                        "[&_ul]:my-1 [&_ul]:pl-4 [&_ul]:list-disc",
                        "[&_ol]:my-1 [&_ol]:pl-4 [&_ol]:list-decimal",
                        "[&_li]:my-0.5",
                        "[&_code]:bg-slate-100 [&_code]:text-slate-800 [&_code]:px-1 [&_code]:py-0.5 [&_code]:rounded [&_code]:text-xs [&_code]:font-mono",
                        "[&_pre]:bg-slate-100 [&_pre]:rounded-lg [&_pre]:p-3 [&_pre]:overflow-x-auto [&_pre]:my-2",
                        "[&_pre_code]:bg-transparent [&_pre_code]:p-0",
                        "[&_strong]:font-semibold",
                        "[&_a]:text-blue-600 [&_a]:underline",
                    ].join(" ")}
                    dangerouslySetInnerHTML={{ __html: messageHtml }}
                    style={isUser ? { color: "white" } : {}}
                />
            </div>
            <p className="mt-1 text-xs text-slate-400 px-1">{message.time}</p>
        </div>
    );
}

function EmptyState() {
    return (
        <div className="flex flex-col items-center justify-center h-full py-8 gap-3 text-center">
            <div className="h-12 w-12 rounded-full bg-slate-100 flex items-center justify-center text-2xl">👋</div>
            <div>
                <p className="text-sm font-medium text-slate-700">Olá! Sou a Laura.</p>
                <p className="text-xs text-slate-400 mt-1">Como posso te ajudar hoje?</p>
            </div>
        </div>
    );
}

// ─── CSRF helpers ─────────────────────────────────────────────────────────────
function getCsrfToken(): string {
    const cookie = document.cookie.match(/(?:^|;\s*)XSRF-TOKEN=([^;]+)/);
    if (cookie) return decodeURIComponent(cookie[1]);
    return document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") ?? "";
}

async function refreshCsrfToken(): Promise<void> {
    await fetch("/sanctum/csrf-cookie", { credentials: "same-origin" });
}

async function fetchWithCsrf(url: string, init: RequestInit, retry = true): Promise<Response> {
    const res = await fetch(url, {
        ...init,
        credentials: "same-origin",
        headers: { ...(init.headers as Record<string, string>), "X-XSRF-TOKEN": getCsrfToken() },
    });
    if (res.status === 419 && retry) {
        await refreshCsrfToken();
        return fetchWithCsrf(url, init, false);
    }
    return res;
}

// ─── Componente principal ──────────────────────────────────────────────────────
export default function ChatWindow() {
    const toggleId = "chat-toggle";
    const [message, setMessage] = useState("");
    const [isLoading, setIsLoading] = useState(false);
    const [expanded, setExpanded] = useState(true);

    // Conversa ativa
    const [activeConvId, setActiveConvId] = useState<string | null>(null);
    const [activeMessages, setActiveMessages] = useState<ChatMessage[]>([]);

    // Histórico vindo do backend
    const [history, setHistory] = useState<Conversation[]>([]);
    const [historyLoading, setHistoryLoading] = useState(false);

    // Tela: "history" | "chat"
    const [screen, setScreen] = useState<"history" | "chat">("history");

    const messagesEndRef = useRef<HTMLDivElement>(null);
    const textareaRef = useRef<HTMLTextAreaElement>(null);

    // Busca as últimas 5 conversas do backend
    const fetchHistory = useCallback(async () => {
        setHistoryLoading(true);
        try {
            const res = await fetch("/agent/conversations");
            const data: Conversation[] = await res.json();
            setHistory(data);
        } catch {
            // silencia — histórico não crítico
        } finally {
            setHistoryLoading(false);
        }
    }, []);

    // Carrega histórico quando o chat é aberto (checkbox marcado)
    // Usamos um MutationObserver não é necessário — recarrega sempre que "history" aparece
    useEffect(() => {
        if (screen === "history") fetchHistory();
    }, [screen, fetchHistory]);

    useEffect(() => {
        messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
    }, [activeMessages, isLoading]);

    useEffect(() => {
        const textarea = textareaRef.current;
        if (!textarea) return;
        textarea.style.height = "auto";
        textarea.style.height = `${Math.min(textarea.scrollHeight, 120)}px`;
    }, [message]);

    function handleNewChat() {
        setActiveConvId(null);
        setActiveMessages([]);
        setScreen("chat");
    }

    function handleSelectConversation(conv: Conversation) {
        setActiveConvId(conv.id);
        setActiveMessages(conv.messages);
        setScreen("chat");
    }

    async function handleDeleteConversation(id: string) {
        // Remove optimisticamente da lista
        setHistory((prev) => prev.filter((c) => c.id !== id));
        // Se era a conversa ativa, limpa
        if (activeConvId === id) {
            setActiveConvId(null);
            setActiveMessages([]);
        }
        try {
            await fetchWithCsrf(`/agent/conversations/${id}`, { method: "DELETE" });
        } catch {
            // Re-busca em caso de erro para manter consistência
            fetchHistory();
        }
    }

    const sendToAgent = useCallback(async (text: string) => {
        const userMessage: ChatMessage = {
            id: Date.now(),
            role: "user",
            text,
            time: new Date().toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }),
        };
        setActiveMessages((prev) => [...prev, userMessage]);
        setIsLoading(true);

        try {
            const res = await fetchWithCsrf("/invoke-agent", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ message: text, conversation_id: activeConvId }),
            });

            const contentType = res.headers.get("content-type") ?? "";
            if (!contentType.includes("application/json")) {
                throw new Error(`Erro ${res.status}: resposta inesperada do servidor.`);
            }

            const data = await res.json();

            if (!res.ok) {
                const errMsg = data?.message ?? data?.error ?? `Erro ${res.status}`;
                throw new Error(errMsg);
            }

            if (data.conversation_id) setActiveConvId(data.conversation_id);
            setActiveMessages((prev) => [
                ...prev,
                {
                    id: prev.length + 1,
                    role: "assistant",
                    text: data.reply,
                    time: new Date().toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }),
                },
            ]);
        } catch (err: any) {
            setActiveMessages((prev) => [
                ...prev,
                {
                    id: prev.length + 1,
                    role: "assistant",
                    text: `⚠️ ${err?.message ?? "Erro ao conectar com a Laura. Tente novamente."}`,
                    time: new Date().toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }),
                },
            ]);
        } finally {
            setIsLoading(false);
        }
    }, [activeConvId]);

    useEffect(() => {
        function onLauraSendMessage(e: Event) {
            const { message: text } = (e as CustomEvent<{ message: string }>).detail;
            const toggleEl = document.getElementById('chat-toggle') as HTMLInputElement;
            if (toggleEl && !toggleEl.checked) toggleEl.checked = true;
            setScreen("chat");
            sendToAgent(text);
        }
        window.addEventListener('laura:send-message', onLauraSendMessage);
        return () => window.removeEventListener('laura:send-message', onLauraSendMessage);
    }, [sendToAgent]);

    async function handleSend() {
        if (!message.trim() || isLoading) return;
        const text = message;
        setMessage("");
        await sendToAgent(text);
    }

    function handleKeyDown(e: React.KeyboardEvent<HTMLTextAreaElement>) {
        if (e.key === "Enter" && !e.shiftKey) {
            e.preventDefault();
            handleSend();
        }
    }

    const hasMessages = activeMessages.length > 0;

    return (
        <>
            <style>{`
                @keyframes fadeSlideIn {
                    from { opacity: 0; transform: translateY(6px); }
                    to   { opacity: 1; transform: translateY(0); }
                }
            `}</style>

            <div className="relative">
                <input id={toggleId} type="checkbox" className="peer sr-only"
                       onChange={(e) => { if (e.target.checked) setScreen("history"); }} />

                {/* Botão flutuante */}
                <label htmlFor={toggleId}
                       className="fixed bottom-6 right-6 z-40 inline-flex h-12 items-center gap-2 rounded-full bg-slate-900 px-4 text-sm font-semibold text-white shadow-lg transition hover:bg-slate-800 cursor-pointer select-none">
                    <Avatar className="h-8 w-8 overflow-hidden rounded-full">
                        <AvatarImage src="/laura.png" alt="Laura" />
                        <AvatarFallback className="bg-neutral-200 text-black text-xs font-semibold">LP</AvatarFallback>
                    </Avatar>
                    Laura
                    <span className="rounded-full bg-amber-400 px-1.5 py-0.5 text-[10px] font-bold uppercase tracking-wide text-amber-900">
                        beta
                    </span>
                    <span className="inline-flex h-2 w-2 rounded-full bg-emerald-400" />
                </label>

                {/* Chat Window */}
                <section
                    className="fixed bottom-24 right-6 z-40 hidden max-w-[92vw] flex-col overflow-hidden rounded-2xl border border-slate-200 bg-gradient-to-br from-slate-50 via-white to-amber-50 shadow-2xl peer-checked:flex"
                    style={{
                        width: expanded ? "min(1100px, 92vw)" : "min(720px, 92vw)",
                        minHeight: screen === "chat" && hasMessages ? "420px" : "280px",
                        maxHeight: "min(680px, calc(100vh - 120px))",
                        transition: "width 0.3s cubic-bezier(0.4,0,0.2,1), min-height 0.3s ease",
                    }}
                >
                    <ChatHeader
                        toggleId={toggleId}
                        expanded={expanded}
                        onToggleExpand={() => setExpanded((v) => !v)}
                        onNewChat={handleNewChat}
                        hasActiveConversation={hasMessages}
                    />

                    {/* ── Tela: histórico ── */}
                    {screen === "history" && (
                        <div className="flex-1 overflow-hidden flex flex-col">
                            <RecentConversations
                                conversations={history}
                                loading={historyLoading}
                                onSelect={handleSelectConversation}
                                onNewChat={handleNewChat}
                                onDelete={handleDeleteConversation}
                            />
                        </div>
                    )}

                    {/* ── Tela: chat ── */}
                    {screen === "chat" && (
                        <>
                            <button type="button"
                                    onClick={() => setScreen("history")}
                                    className="flex items-center gap-1.5 px-5 py-2 text-xs text-slate-400 hover:text-slate-700 transition border-b border-slate-100 bg-white/60 shrink-0">
                                <svg xmlns="http://www.w3.org/2000/svg" width="11" height="11" viewBox="0 0 24 24"
                                     fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                                    <polyline points="15 18 9 12 15 6" />
                                </svg>
                                Conversas recentes
                            </button>

                            <div className="flex-1 overflow-y-auto px-5 py-4 space-y-3 scroll-smooth">
                                {!hasMessages && !isLoading ? (
                                    <EmptyState />
                                ) : (
                                    activeMessages.map((msg) => <ChatBubble key={msg.id} message={msg} />)
                                )}
                                {isLoading && <TypingIndicator />}
                                <div ref={messagesEndRef} />
                            </div>

                            <div className="border-t border-slate-200 bg-white/80 backdrop-blur px-4 py-3 shrink-0">
                                <div className="flex items-end gap-2">
                                    <textarea
                                        ref={textareaRef}
                                        value={message}
                                        onChange={(e) => setMessage(e.target.value)}
                                        onKeyDown={handleKeyDown}
                                        placeholder="Pergunta qualquer coisa… (Enter para enviar)"
                                        rows={1}
                                        disabled={isLoading}
                                        className="flex-1 resize-none rounded-2xl border border-slate-200 bg-slate-50 px-4 py-2.5 text-sm text-slate-700 outline-none focus:border-slate-400 focus:bg-white transition placeholder:text-slate-400 disabled:opacity-50 leading-relaxed"
                                        style={{ minHeight: "40px", maxHeight: "120px" }}
                                    />
                                    <button onClick={handleSend} disabled={!message.trim() || isLoading} type="button"
                                            className="shrink-0 rounded-full bg-slate-900 px-4 py-2.5 text-sm font-semibold text-white transition hover:bg-slate-700 disabled:opacity-40 disabled:cursor-not-allowed">
                                        Enviar
                                    </button>
                                </div>
                                <p className="mt-1.5 text-center text-xs text-slate-300">Shift+Enter para nova linha</p>
                            </div>
                        </>
                    )}
                </section>
            </div>
        </>
    );
}
