import type { ReactNode } from 'react';
import { useCallback, useEffect, useRef, useState } from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faPaperPlaneTop, faRobot, faSparkles, faUserHeadset } from '@fortawesome/pro-duotone-svg-icons';
import { apiClient } from '@/lib/api-client';

type ChatMessage = {
    id: string;
    role: 'user' | 'assistant';
    content: string;
    timestamp: Date;
};

type CallerContext = {
    callerPhone?: string;
    leadId?: string;
    leadName?: string;
};

interface AiChatPanelProps {
    callerContext?: CallerContext;
    role?: 'cc-agent' | 'admin' | 'executive';
}

const QUICK_ASK_AGENT = [
    { label: 'Doctor availability', template: 'What are the visiting hours for all doctors?' },
    { label: 'Clinic timings', template: 'What are the clinic locations and timings?' },
    { label: 'Patient history', template: 'Can you summarize this patient\'s history?' },
    { label: 'Treatment packages', template: 'What treatment packages are available?' },
];

const QUICK_ASK_MANAGER = [
    { label: 'Agent performance', template: 'Which agents have the highest appointment conversion rates this week?' },
    { label: 'Missed call risks', template: 'Which missed calls have been waiting the longest without a callback?' },
    { label: 'Pending leads', template: 'How many leads are still pending first contact?' },
    { label: 'Weekly summary', template: 'Give me a summary of this week\'s team performance — total calls, conversions, missed calls.' },
];

export const AiChatPanel = ({ callerContext, role = 'cc-agent' }: AiChatPanelProps) => {
    const quickButtons = role === 'admin' ? QUICK_ASK_MANAGER : QUICK_ASK_AGENT;
    const [messages, setMessages] = useState<ChatMessage[]>([]);
    const [input, setInput] = useState('');
    const [isLoading, setIsLoading] = useState(false);
    const messagesEndRef = useRef<HTMLDivElement>(null);
    const inputRef = useRef<HTMLInputElement>(null);

    const scrollToBottom = useCallback(() => {
        // Scroll within the messages container only — don't scroll the parent panel
        const el = messagesEndRef.current;
        if (el?.parentElement) {
            el.parentElement.scrollTop = el.parentElement.scrollHeight;
        }
    }, []);

    useEffect(() => {
        scrollToBottom();
    }, [messages, scrollToBottom]);

    const sendMessage = useCallback(async (text?: string) => {
        const messageText = (text ?? input).trim();
        if (messageText.length === 0 || isLoading) return;

        const userMessage: ChatMessage = {
            id: `user-${Date.now()}`,
            role: 'user',
            content: messageText,
            timestamp: new Date(),
        };

        setMessages((prev) => [...prev, userMessage]);
        setInput('');
        setIsLoading(true);

        try {
            const data = await apiClient.post<{ reply: string; sources?: string[] }>('/api/ai/chat', {
                message: messageText,
                context: callerContext,
            });

            const assistantMessage: ChatMessage = {
                id: `assistant-${Date.now()}`,
                role: 'assistant',
                content: data.reply ?? 'Sorry, I could not process that request.',
                timestamp: new Date(),
            };

            setMessages((prev) => [...prev, assistantMessage]);
        } catch {
            const errorMessage: ChatMessage = {
                id: `error-${Date.now()}`,
                role: 'assistant',
                content: 'Sorry, I\'m having trouble connecting to the AI service. Please try again.',
                timestamp: new Date(),
            };
            setMessages((prev) => [...prev, errorMessage]);
        } finally {
            setIsLoading(false);
            inputRef.current?.focus();
        }
    }, [input, isLoading, callerContext]);

    const handleKeyDown = useCallback((e: React.KeyboardEvent) => {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            sendMessage();
        }
    }, [sendMessage]);

    const handleQuickAsk = useCallback((template: string) => {
        sendMessage(template);
    }, [sendMessage]);

    return (
        <div className="flex h-full flex-col">
            {/* Caller context banner */}
            {callerContext?.leadName && (
                <div className="mb-3 rounded-lg bg-brand-primary px-3 py-2">
                    <span className="text-xs text-brand-secondary">
                        Talking to: <span className="font-semibold">{callerContext.leadName}</span>
                        {callerContext.callerPhone ? ` (${callerContext.callerPhone})` : ''}
                    </span>
                </div>
            )}

            {/* Quick ask buttons */}
            {messages.length === 0 && (
                <div className="mb-3 flex flex-wrap gap-1.5">
                    {quickButtons.map((btn) => (
                        <button
                            key={btn.label}
                            onClick={() => handleQuickAsk(btn.template)}
                            disabled={isLoading}
                            className="rounded-lg border border-secondary bg-primary px-2.5 py-1.5 text-xs font-medium text-secondary transition duration-100 ease-linear hover:bg-secondary hover:text-primary disabled:cursor-not-allowed disabled:opacity-50"
                        >
                            {btn.label}
                        </button>
                    ))}
                </div>
            )}

            {/* Messages area */}
            <div className="flex-1 space-y-3 overflow-y-auto">
                {messages.length === 0 && (
                    <div className="flex flex-col items-center justify-center py-8 text-center">
                        <FontAwesomeIcon icon={faRobot} className="mb-3 size-8 text-fg-quaternary" />
                        <p className="text-sm text-tertiary">
                            Ask me about doctors, clinics, packages, or patient info.
                        </p>
                    </div>
                )}

                {messages.map((msg) => (
                    <div
                        key={msg.id}
                        className={`flex ${msg.role === 'user' ? 'justify-end' : 'justify-start'}`}
                    >
                        <div
                            className={`max-w-[90%] rounded-xl px-3 py-2 text-xs leading-relaxed ${
                                msg.role === 'user'
                                    ? 'bg-brand-solid text-white'
                                    : 'bg-secondary text-primary'
                            }`}
                        >
                            {msg.role === 'assistant' && (
                                <div className="mb-1 flex items-center gap-1">
                                    <FontAwesomeIcon icon={faSparkles} className="size-2.5 text-fg-brand-primary" />
                                    <span className="text-[10px] font-semibold uppercase tracking-wider text-brand-secondary">AI</span>
                                </div>
                            )}
                            <MessageContent content={msg.content} />
                        </div>
                    </div>
                ))}

                {isLoading && (
                    <div className="flex justify-start">
                        <div className="rounded-xl bg-secondary px-3 py-2">
                            <div className="flex items-center gap-1">
                                <span className="size-1.5 animate-bounce rounded-full bg-fg-quaternary [animation-delay:0ms]" />
                                <span className="size-1.5 animate-bounce rounded-full bg-fg-quaternary [animation-delay:150ms]" />
                                <span className="size-1.5 animate-bounce rounded-full bg-fg-quaternary [animation-delay:300ms]" />
                            </div>
                        </div>
                    </div>
                )}

                <div ref={messagesEndRef} />
            </div>

            {/* Input area */}
            <div className="mt-3 flex items-center gap-2">
                <div className="flex flex-1 items-center rounded-lg border border-secondary bg-primary shadow-xs transition duration-100 ease-linear focus-within:border-brand focus-within:ring-4 focus-within:ring-brand-100">
                    <FontAwesomeIcon
                        icon={faUserHeadset}
                        className="ml-2.5 size-3.5 text-fg-quaternary"
                    />
                    <input
                        ref={inputRef}
                        type="text"
                        value={input}
                        onChange={(e) => setInput(e.target.value)}
                        onKeyDown={handleKeyDown}
                        placeholder="Ask the AI assistant..."
                        disabled={isLoading}
                        className="flex-1 bg-transparent px-2 py-2 text-xs text-primary placeholder:text-placeholder outline-none disabled:cursor-not-allowed"
                    />
                </div>
                <button
                    onClick={() => sendMessage()}
                    disabled={isLoading || input.trim().length === 0}
                    className="flex size-8 shrink-0 items-center justify-center rounded-lg bg-brand-solid text-white transition duration-100 ease-linear hover:bg-brand-solid_hover disabled:cursor-not-allowed disabled:bg-disabled"
                >
                    <FontAwesomeIcon icon={faPaperPlaneTop} className="size-3.5" />
                </button>
            </div>
        </div>
    );
};

// Parse simple markdown-like text into React nodes (safe, no innerHTML)
const parseLine = (text: string): ReactNode[] => {
    const parts: ReactNode[] = [];
    const boldPattern = /\*\*(.+?)\*\*/g;
    let lastIndex = 0;
    let match: RegExpExecArray | null;

    while ((match = boldPattern.exec(text)) !== null) {
        if (match.index > lastIndex) {
            parts.push(text.slice(lastIndex, match.index));
        }
        parts.push(
            <strong key={match.index} className="font-semibold">
                {match[1]}
            </strong>,
        );
        lastIndex = boldPattern.lastIndex;
    }

    if (lastIndex < text.length) {
        parts.push(text.slice(lastIndex));
    }

    return parts.length > 0 ? parts : [text];
};

const MessageContent = ({ content }: { content: string }) => {
    const lines = content.split('\n');

    return (
        <div className="space-y-1">
            {lines.map((line, i) => {
                if (line.trim().length === 0) return <div key={i} className="h-1" />;

                // Bullet points
                if (line.trimStart().startsWith('- ')) {
                    return (
                        <div key={i} className="flex gap-1.5 pl-1">
                            <span className="mt-1.5 size-1 shrink-0 rounded-full bg-fg-quaternary" />
                            <span>{parseLine(line.replace(/^\s*-\s*/, ''))}</span>
                        </div>
                    );
                }

                return <p key={i}>{parseLine(line)}</p>;
            })}
        </div>
    );
};
