import { useState, useRef, useEffect } from 'react';
import { useChat } from '@ai-sdk/react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faPaperPlaneTop, faSparkles, faChevronDown, faChevronUp } from '@fortawesome/pro-duotone-svg-icons';
import type { PriorityConfig } from '@/lib/scoring';
import { cx } from '@/utils/cx';

const API_URL = import.meta.env.VITE_API_URL ?? 'http://localhost:4100';

interface RulesAiAssistantProps {
    config: PriorityConfig;
}

const QUICK_ACTIONS = [
    { label: 'Explain scoring', prompt: 'How does the priority scoring formula work?' },
    { label: 'Optimize weights', prompt: 'What would you recommend changing to better prioritize urgent cases?' },
    { label: 'SLA best practices', prompt: 'What SLA thresholds are recommended for a hospital call center?' },
    { label: 'Campaign strategy', prompt: 'How should I weight campaigns for IVF vs general health checkups?' },
];

export const RulesAiAssistant = ({ config }: RulesAiAssistantProps) => {
    const [expanded, setExpanded] = useState(false);
    const messagesEndRef = useRef<HTMLDivElement>(null);
    const token = localStorage.getItem('helix_access_token') ?? '';

    const { messages, input, handleSubmit, handleInputChange, isLoading, append } = useChat({
        api: `${API_URL}/api/ai/stream`,
        streamProtocol: 'text',
        headers: {
            'Authorization': `Bearer ${token}`,
        },
        body: {
            context: {
                type: 'rules-engine',
                currentConfig: config,
            },
        },
    });

    // Auto-expand when messages arrive
    useEffect(() => {
        if (messages.length > 0) setExpanded(true);
    }, [messages.length]);

    useEffect(() => {
        const el = messagesEndRef.current;
        if (el?.parentElement) {
            el.parentElement.scrollTop = el.parentElement.scrollHeight;
        }
    }, [messages]);

    return (
        <div className={cx('flex flex-col border-t border-secondary', expanded ? 'flex-1 min-h-0' : '')}>
            {/* Collapsible header */}
            <button
                onClick={() => setExpanded(!expanded)}
                className="flex items-center justify-between px-4 py-3 hover:bg-primary_hover transition duration-100 ease-linear"
            >
                <div className="flex items-center gap-2">
                    <FontAwesomeIcon icon={faSparkles} className="size-3.5 text-fg-brand-primary" />
                    <span className="text-sm font-semibold text-primary">AI Assistant</span>
                    {messages.length > 0 && (
                        <span className="rounded-full bg-brand-primary px-1.5 py-0.5 text-[10px] font-medium text-brand-secondary">
                            {messages.length}
                        </span>
                    )}
                </div>
                <FontAwesomeIcon
                    icon={expanded ? faChevronDown : faChevronUp}
                    className="size-3 text-fg-quaternary"
                />
            </button>

            {/* Expandable content */}
            {expanded && (
                <div className="flex flex-1 flex-col min-h-0 px-4 pb-3">
                    {/* Messages */}
                    <div className="flex-1 overflow-y-auto min-h-0 space-y-2 mb-3">
                        {messages.length === 0 && (
                            <div className="text-center py-3">
                                <p className="text-[11px] text-tertiary mb-2">
                                    Ask about rule configuration, scoring, or best practices.
                                </p>
                                <div className="flex flex-wrap justify-center gap-1">
                                    {QUICK_ACTIONS.map((action) => (
                                        <button
                                            key={action.label}
                                            onClick={() => append({ role: 'user', content: action.prompt })}
                                            disabled={isLoading}
                                            className="rounded-md border border-secondary bg-primary px-2 py-1 text-[10px] font-medium text-secondary transition duration-100 ease-linear hover:bg-secondary hover:text-primary disabled:opacity-50"
                                        >
                                            {action.label}
                                        </button>
                                    ))}
                                </div>
                            </div>
                        )}
                        {messages.map((msg) => (
                            <div
                                key={msg.id}
                                className={msg.role === 'user'
                                    ? 'ml-8 rounded-lg bg-brand-solid px-2.5 py-1.5 text-[11px] text-white'
                                    : 'mr-4 rounded-lg bg-primary px-2.5 py-1.5 text-[11px] text-primary leading-relaxed'
                                }
                            >
                                <div className="whitespace-pre-wrap">{msg.content}</div>
                            </div>
                        ))}
                        {isLoading && (
                            <div className="mr-4 rounded-lg bg-primary px-2.5 py-1.5">
                                <div className="flex gap-1">
                                    <span className="size-1.5 rounded-full bg-tertiary animate-bounce" style={{ animationDelay: '0ms' }} />
                                    <span className="size-1.5 rounded-full bg-tertiary animate-bounce" style={{ animationDelay: '150ms' }} />
                                    <span className="size-1.5 rounded-full bg-tertiary animate-bounce" style={{ animationDelay: '300ms' }} />
                                </div>
                            </div>
                        )}
                        <div ref={messagesEndRef} />
                    </div>

                    {/* Input */}
                    <form onSubmit={handleSubmit} className="flex items-center gap-2 shrink-0">
                        <input
                            value={input}
                            onChange={handleInputChange}
                            placeholder="Ask about rules..."
                            disabled={isLoading}
                            className="flex-1 rounded-lg border border-secondary bg-primary px-3 py-2 text-xs text-primary placeholder:text-placeholder focus:border-brand focus:outline-none disabled:opacity-50"
                        />
                        <button
                            type="submit"
                            disabled={isLoading || !input.trim()}
                            className="flex size-8 items-center justify-center rounded-lg bg-brand-solid text-white transition duration-100 ease-linear hover:bg-brand-solid_hover disabled:opacity-50"
                        >
                            <FontAwesomeIcon icon={faPaperPlaneTop} className="size-3.5" />
                        </button>
                    </form>
                </div>
            )}
        </div>
    );
};
