import { csrfToken } from '@frontend/lib/csrf';
import { Link } from '@inertiajs/react';
import { Check, ChevronDown, ChevronRight, Copy, Maximize2, Minimize2, RefreshCw, Send, User } from 'lucide-react';
import { useEffect, useRef, useState } from 'react';

type Suggestion = {
    id: string;
    label: string;
    query: string;
};

type AssistantLink = {
    label: string;
    href: string;
};

type Message = {
    id: number;
    type: 'user' | 'bot';
    text: string;
    time: string;
    suggestions?: Suggestion[];
    links?: AssistantLink[];
    image?: string | null;
    imageAlt?: string | null;
    copied?: boolean;
};

const WELCOME =
    'Welcome to Chato Beach Resort. I am the Chato assistant. I can help you book a room, compare rates, or tell you about Chato.';

const QUICK_ACTIONS: Suggestion[] = [
    { id: 'book', label: 'Book a room', query: 'I want to book a room' },
    { id: 'rooms', label: 'Room types', query: 'What rooms do you have?' },
    { id: 'rates', label: 'Rates', query: 'What are the nightly rates?' },
    { id: 'dining', label: 'Dining', query: 'What is on the menu?' },
    { id: 'about', label: 'About Chato', query: 'Tell me about Chato' },
];

function timeNow(): string {
    return new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
}

function welcomeMessage(): Message {
    return {
        id: 1,
        type: 'bot',
        text: WELCOME,
        time: timeNow(),
    };
}

function AssistantMark({ className }: { className?: string }) {
    return (
        <svg className={className} viewBox="0 0 64 64" aria-hidden="true">
            <g fill="currentColor">
                <circle cx="22" cy="18" r="9" />
                <circle cx="34" cy="13" r="11" />
                <circle cx="46" cy="18" r="9" />
                <path d="M12 24h40c0 4.2-2.6 8-7 8H19c-4.4 0-7-3.8-7-8z" />
                <rect x="17" y="36" width="2.6" height="8" rx="1.2" />
                <rect x="21.6" y="36" width="2.6" height="10" rx="1.2" />
                <rect x="26.2" y="36" width="2.6" height="8" rx="1.2" />
                <rect x="21.6" y="44.5" width="2.6" height="13" rx="1.2" />
                <ellipse cx="46" cy="42" rx="6" ry="7" />
                <rect x="44.3" y="48" width="3.4" height="11" rx="1.5" />
            </g>
        </svg>
    );
}

function safeHref(href: string): string | null {
    if (href.startsWith('/') && !href.startsWith('//')) {
        return href;
    }

    if (/^(https?:|tel:|mailto:)/i.test(href)) {
        return href;
    }

    return null;
}

function isAppLink(href: string): boolean {
    if (href.startsWith('/')) {
        return true;
    }

    try {
        return new URL(href).origin === window.location.origin;
    } catch {
        return false;
    }
}

function safeImage(src: string): string | null {
    if (src.startsWith('/') && !src.startsWith('//')) {
        return src;
    }

    if (/^https?:\/\//i.test(src)) {
        return src;
    }

    return null;
}

export function ResortAssistant() {
    const [isOpen, setIsOpen] = useState(false);
    const [expanded, setExpanded] = useState(false);
    const [messages, setMessages] = useState<Message[]>(() => [welcomeMessage()]);
    const [input, setInput] = useState('');
    const [pending, setPending] = useState(false);
    const [room, setRoom] = useState<string | null>(null);
    const idRef = useRef(1);
    const requestRef = useRef(0);
    const scrollerRef = useRef<HTMLDivElement>(null);
    const inputRef = useRef<HTMLInputElement>(null);

    useEffect(() => {
        const scroller = scrollerRef.current;
        if (scroller) {
            scroller.scrollTo({ top: scroller.scrollHeight, behavior: 'smooth' });
        }
    }, [messages, pending, isOpen]);

    useEffect(() => {
        if (isOpen) {
            inputRef.current?.focus();
        }
    }, [isOpen]);

    useEffect(() => {
        if (!isOpen) {
            return;
        }

        const onKey = (event: KeyboardEvent) => {
            if (event.key !== 'Escape') {
                return;
            }

            if (expanded) {
                setExpanded(false);

                return;
            }

            setIsOpen(false);
        };

        window.addEventListener('keydown', onKey);

        return () => window.removeEventListener('keydown', onKey);
    }, [isOpen, expanded]);

    useEffect(() => {
        if (!isOpen || !expanded) {
            return;
        }

        const previous = document.body.style.overflow;
        document.body.style.overflow = 'hidden';

        return () => {
            document.body.style.overflow = previous;
        };
    }, [isOpen, expanded]);

    const latestBotId = [...messages].reverse().find((message) => message.type === 'bot')?.id;

    const resetChat = () => {
        requestRef.current += 1;
        idRef.current = 1;
        setPending(false);
        setRoom(null);
        setInput('');
        setMessages([welcomeMessage()]);
    };

    const send = async (text?: string) => {
        const messageText = (text ?? input).trim();
        if (messageText === '' || pending) {
            return;
        }

        const request = ++requestRef.current;
        const contextRoom = room;

        setMessages((current) => [
            ...current,
            {
                id: ++idRef.current,
                type: 'user',
                text: messageText,
                time: timeNow(),
            },
        ]);
        setInput('');
        setPending(true);

        try {
            const response = await fetch(route('assistant'), {
                method: 'POST',
                headers: {
                    Accept: 'application/json',
                    'Content-Type': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest',
                    'X-XSRF-TOKEN': csrfToken(),
                },
                body: JSON.stringify({
                    message: messageText,
                    room: contextRoom,
                }),
            });

            const body = (await response.json()) as {
                text?: string;
                links?: AssistantLink[];
                suggestions?: Suggestion[];
                room?: string | null;
                image?: string | null;
                imageAlt?: string | null;
                message?: string;
            };

            if (request !== requestRef.current) {
                return;
            }

            if (!response.ok || typeof body.text !== 'string' || body.text.trim() === '') {
                const busy = response.status === 429;
                throw new Error(busy ? 'busy' : 'failed');
            }

            setRoom(typeof body.room === 'string' && body.room !== '' ? body.room : null);
            setMessages((current) => [
                ...current,
                {
                    id: ++idRef.current,
                    type: 'bot',
                    text: body.text ?? '',
                    time: timeNow(),
                    suggestions: Array.isArray(body.suggestions) ? body.suggestions : [],
                    links: Array.isArray(body.links) ? body.links : [],
                    image: typeof body.image === 'string' ? body.image : null,
                    imageAlt: typeof body.imageAlt === 'string' ? body.imageAlt : null,
                },
            ]);
        } catch (error: unknown) {
            if (request !== requestRef.current) {
                return;
            }

            const busy = error instanceof Error && error.message === 'busy';
            setMessages((current) => [
                ...current,
                {
                    id: ++idRef.current,
                    type: 'bot',
                    text: busy
                        ? 'I need a moment. Please try again shortly.'
                        : 'I could not reach the desk just now. Please try again, or continue on the booking form.',
                    time: timeNow(),
                    links: busy ? [] : [{ label: 'Book a room', href: '/book' }],
                    suggestions: QUICK_ACTIONS,
                },
            ]);
        } finally {
            if (request === requestRef.current) {
                setPending(false);
            }
        }
    };

    const copyMessage = async (message: Message) => {
        try {
            await navigator.clipboard.writeText(message.text);
        } catch {
            return;
        }

        setMessages((current) => current.map((item) => (item.id === message.id ? { ...item, copied: true } : item)));
        window.setTimeout(() => {
            setMessages((current) => current.map((item) => (item.id === message.id ? { ...item, copied: false } : item)));
        }, 2000);
    };

    return (
        <div className={['resort-assistant', isOpen ? 'is-open' : '', isOpen && expanded ? 'is-expanded' : ''].filter(Boolean).join(' ')}>
            {isOpen ? (
                <section
                    className="resort-assistant__panel"
                    role="dialog"
                    aria-label="Chato assistant"
                >
                    <header className="resort-assistant__header">
                        <span className="resort-assistant__avatar" aria-hidden="true">
                            <AssistantMark className="resort-assistant__mark" />
                        </span>
                        <div className="resort-assistant__identity">
                            <p className="resort-assistant__title">Chato assistant</p>
                            <p className="resort-assistant__status">Online · rooms & resort</p>
                        </div>
                        <div className="resort-assistant__actions">
                            <button type="button" className="resort-assistant__icon-button" onClick={resetChat} aria-label="New chat">
                                <RefreshCw size={16} strokeWidth={2} />
                            </button>
                            <button
                                type="button"
                                className="resort-assistant__icon-button"
                                onClick={() => setExpanded((current) => !current)}
                                aria-label={expanded ? 'Exit full screen' : 'Full screen'}
                                aria-pressed={expanded}
                            >
                                {expanded ? <Minimize2 size={16} strokeWidth={2} /> : <Maximize2 size={16} strokeWidth={2} />}
                            </button>
                            <button
                                type="button"
                                className="resort-assistant__icon-button"
                                onClick={() => {
                                    setExpanded(false);
                                    setIsOpen(false);
                                }}
                                aria-label="Minimize chat"
                            >
                                <ChevronDown size={18} strokeWidth={2} />
                            </button>
                        </div>
                    </header>

                    <div className="resort-assistant__log" ref={scrollerRef} aria-live="polite">
                        {messages.length === 1 && <span className="resort-assistant__day">Today · {messages[0]?.time}</span>}

                        {messages.map((message) => {
                            const image = message.image ? safeImage(message.image) : null;

                            return (
                                <div
                                    key={message.id}
                                    className={message.type === 'user' ? 'resort-assistant__row is-user' : 'resort-assistant__row'}
                                >
                                    <span className="resort-assistant__avatar" aria-hidden="true">
                                        {message.type === 'bot' ? (
                                            <AssistantMark className="resort-assistant__mark" />
                                        ) : (
                                            <User size={14} strokeWidth={2} />
                                        )}
                                    </span>
                                    <div className="resort-assistant__body">
                                        <div
                                            className={
                                                message.type === 'user'
                                                    ? 'resort-assistant__bubble is-user'
                                                    : image
                                                      ? 'resort-assistant__bubble has-photo'
                                                      : 'resort-assistant__bubble'
                                            }
                                        >
                                            {message.type === 'bot' && (
                                                <button
                                                    type="button"
                                                    className="resort-assistant__copy"
                                                    onClick={() => void copyMessage(message)}
                                                    aria-label={message.copied ? 'Copied' : 'Copy message'}
                                                >
                                                    {message.copied ? <Check size={13} /> : <Copy size={13} />}
                                                </button>
                                            )}
                                            {image && <img className="resort-assistant__photo" src={image} alt={message.imageAlt ?? ''} />}
                                            <p>{message.text}</p>
                                        </div>
                                        {message.links && message.links.length > 0 && (
                                            <div className="resort-assistant__links">
                                                {message.links.map((link) => {
                                                    const href = safeHref(link.href);
                                                    if (href === null) {
                                                        return null;
                                                    }

                                                    if (isAppLink(href)) {
                                                        return (
                                                            <Link
                                                                key={link.href + link.label}
                                                                href={href}
                                                                className="resort-assistant__link"
                                                                onClick={() => setIsOpen(false)}
                                                            >
                                                                {link.label}
                                                            </Link>
                                                        );
                                                    }

                                                    const external = href.startsWith('http');

                                                    return (
                                                        <a
                                                            key={link.href + link.label}
                                                            href={href}
                                                            className="resort-assistant__link"
                                                            target={external ? '_blank' : undefined}
                                                            rel={external ? 'noreferrer' : undefined}
                                                        >
                                                            {link.label}
                                                        </a>
                                                    );
                                                })}
                                            </div>
                                        )}
                                        {message.suggestions && message.id === latestBotId && !pending && message.suggestions.length > 0 && (
                                            <div className="resort-assistant__chips">
                                                {message.suggestions.map((suggestion) => (
                                                    <button
                                                        key={suggestion.id}
                                                        type="button"
                                                        className="resort-assistant__chip"
                                                        onClick={() => void send(suggestion.query)}
                                                    >
                                                        {suggestion.label}
                                                    </button>
                                                ))}
                                            </div>
                                        )}
                                        <span className="resort-assistant__time">{message.time}</span>
                                    </div>
                                </div>
                            );
                        })}

                        {messages.length === 1 && !pending && (
                            <nav className="resort-assistant__quick" aria-label="Quick actions">
                                <p className="resort-assistant__quick-label">Quick actions</p>
                                <div className="resort-assistant__quick-list">
                                    {QUICK_ACTIONS.map((action) => (
                                        <button
                                            key={action.id}
                                            type="button"
                                            className="resort-assistant__quick-action"
                                            onClick={() => void send(action.query)}
                                        >
                                            <span>{action.label}</span>
                                            <ChevronRight size={16} strokeWidth={2} aria-hidden="true" />
                                        </button>
                                    ))}
                                </div>
                            </nav>
                        )}

                        {pending && (
                            <div className="resort-assistant__row">
                                <span className="resort-assistant__avatar" aria-hidden="true">
                                    <AssistantMark className="resort-assistant__mark" />
                                </span>
                                <div className="resort-assistant__bubble resort-assistant__typing" aria-label="Chato assistant is typing">
                                    <span />
                                    <span />
                                    <span />
                                </div>
                            </div>
                        )}
                    </div>

                    <form
                        className="resort-assistant__composer"
                        onSubmit={(event) => {
                            event.preventDefault();
                            void send();
                        }}
                    >
                        <div className="resort-assistant__field">
                            <input
                                ref={inputRef}
                                className="resort-assistant__input"
                                type="text"
                                value={input}
                                maxLength={500}
                                placeholder="Ask about a room…"
                                autoComplete="off"
                                aria-label="Message"
                                onChange={(event) => setInput(event.target.value)}
                            />
                            <button
                                type="submit"
                                className="resort-assistant__send"
                                disabled={pending || input.trim() === ''}
                                aria-label="Send"
                            >
                                <Send size={15} strokeWidth={2} />
                            </button>
                        </div>
                    </form>
                </section>
            ) : (
                <button type="button" className="resort-assistant__launch" onClick={() => setIsOpen(true)} aria-label="Open Chato assistant">
                    <AssistantMark className="resort-assistant__launch-mark" />
                    <span className="resort-assistant__dot" aria-hidden="true" />
                </button>
            )}
        </div>
    );
}
