import React, { useState, useRef, useEffect } from 'react';
import { Button } from "@/Components/ui/button";
import { Sparkles } from 'lucide-react';
import { toast } from 'sonner';
import axios from 'axios';
import { useTranslation } from '@/hooks/useTranslation';

import AiAssistantHeader from './AiAssistantHeader';
import AiAssistantMessageList from './AiAssistantMessageList';
import AiAssistantInputArea from './AiAssistantInputArea';

export default function AiAssistantWindow({ 
    apiEndpoint, 
    contextData, 
    onDataUpdate,
    categories = [], 
    currencies = [], 
    slashCommands = [], 
    title = "AI Co-Pilot", 
    placeholder = "Type '/' for commands..." 
}) {
    const { t } = useTranslation();
    const [isOpen, setIsOpen] = useState(false);
    const [isMinimized, setIsMinimized] = useState(false);
    const [history, setHistory] = useState([
        { role: 'assistant', content: t("Hi! I can update categories, currencies, variations, and extract data from uploaded files. Type '/' to quickly select a section to focus on.") }
    ]);
    const [input, setInput] = useState('');
    const [isThinking, setIsThinking] = useState(false);
    
    // Default Suggestions when chat is empty
    const [suggestions, setSuggestions] = useState([
        t("Write a catchy product description"),
        t("Add Size variations (S, M, L)"),
        t("Set price to $99 with 10% discount")
    ]);
    
    const [attachedFile, setAttachedFile] = useState(null);
    const [showSlashMenu, setShowSlashMenu] = useState(false);
    const [slashQuery, setSlashQuery] = useState('');
    const [slashIndex, setSlashIndex] = useState(0);

    const scrollRef = useRef(null);
    const fileInputRef = useRef(null);

    useEffect(() => {
        if (scrollRef.current) {
            scrollRef.current.scrollTo({ top: scrollRef.current.scrollHeight, behavior: 'smooth' });
        }
    }, [history, isThinking, isOpen, isMinimized, attachedFile, suggestions]);

    const handleFileChange = (e) => {
        const file = e.target.files[0];
        if (!file) return;

        if (file.size > 500 * 1024) {
            toast.error(t('File is too large. Please upload a text/csv file under 500KB.'));
            e.target.value = '';
            return;
        }

        const reader = new FileReader();
        reader.onload = (event) => setAttachedFile({ name: file.name, content: event.target.result });
        reader.readAsText(file);
        e.target.value = ''; 
    };

    const filteredCommands = slashCommands?.filter(c => c.label.toLowerCase().includes(slashQuery)) || [];

    const handleInputChange = (e) => {
        const val = e.target.value;
        setInput(val);

        const match = val.match(/(?:^|\s)\/([a-zA-Z0-9_-]*)$/);
        if (match && slashCommands && slashCommands.length > 0) {
            setShowSlashMenu(true);
            setSlashQuery(match[1].toLowerCase());
            setSlashIndex(0);
        } else {
            setShowSlashMenu(false);
        }
    };

    const handleKeyDown = (e) => {
        if (!showSlashMenu) return;

        if (e.key === 'ArrowDown') {
            e.preventDefault();
            setSlashIndex(prev => (prev + 1) % filteredCommands.length);
        } else if (e.key === 'ArrowUp') {
            e.preventDefault();
            setSlashIndex(prev => (prev - 1 + filteredCommands.length) % filteredCommands.length);
        } else if (e.key === 'Enter') {
            e.preventDefault();
            if (filteredCommands[slashIndex]) applySlashCommand(filteredCommands[slashIndex]);
        } else if (e.key === 'Escape') {
            setShowSlashMenu(false);
        }
    };

    const applySlashCommand = (cmd) => {
        const newVal = input.replace(/(?:^|\s)\/[a-zA-Z0-9_-]*$/, ` Focus on ${cmd.label}: `);
        setInput(newVal);
        setShowSlashMenu(false);
        
        if (cmd.id) {
            document.getElementById(`section-${cmd.id}`)?.scrollIntoView({ behavior: 'smooth', block: 'center' });
            const sectionEl = document.getElementById(`section-${cmd.id}`);
            if (sectionEl) {
                sectionEl.classList.add('ring-2', 'ring-primary', 'ring-offset-4', 'rounded-xl', 'transition-all');
                setTimeout(() => sectionEl.classList.remove('ring-2', 'ring-primary', 'ring-offset-4', 'rounded-xl', 'transition-all'), 1500);
            }
        }
    };

    // --- INSTANT SUGGESTION CLICK HANDLER ---
    const handleSuggestionClick = (suggestionText) => {
        if (isThinking) return;
        submitMessageToApi(suggestionText);
    };

    const handleSend = (e) => {
        e?.preventDefault();
        if (showSlashMenu && filteredCommands.length > 0) return;
        const userMessage = input.trim();
        if (!userMessage && !attachedFile) return;
        if (isThinking) return;

        submitMessageToApi(userMessage);
    };

    const submitMessageToApi = async (userMessage) => {
        const newMessage = { 
            role: 'user', 
            content: userMessage || t("Please process this attached file."),
            fileName: attachedFile?.name,
            fileContent: attachedFile?.content
        };
        
        const newHistory = [...history, newMessage];
        setHistory(newHistory);
        setInput('');
        setShowSlashMenu(false);
        setAttachedFile(null); 
        setSuggestions([]); // Clear suggestions while thinking
        setIsThinking(true);

        const apiHistory = newHistory.map(msg => ({
            role: msg.role,
            content: msg.fileContent ? `${msg.content}\n\n--- ATTACHED DOCUMENT: ${msg.fileName} ---\n${msg.fileContent}` : msg.content
        }));

        const referenceData = {
            categories: categories.map(c => ({ id: c.id, name: c.name, subcategories: c.subcategories?.map(s => ({ id: s.id, name: s.name })) || [] })),
            currencies: currencies.map(c => ({ code: c.code, name: c.name }))
        };

        try {
            const res = await axios.post(apiEndpoint, {
                history: apiHistory,
                current_data: contextData, 
                reference_data: referenceData 
            });

            // Extract the new suggestions from the backend response
            const { reply, updates, suggestions: newSuggestions } = res.data;
            
            setHistory(prev => [...prev, { role: 'assistant', content: reply, updates }]);
            
            if (newSuggestions && newSuggestions.length > 0) {
                setSuggestions(newSuggestions.slice(0, 5)); // Enforce Max 5
            }

            if (updates && Object.keys(updates).length > 0) {
                onDataUpdate(updates);
                toast.success(t('AI updated the form successfully.'), { id: 'ai-update' });
            }

        } catch (error) {
            toast.error(error.response?.data?.message || t('AI encountered an error.'), { id: 'ai-error' });
            setHistory(prev => [...prev, { role: 'assistant', content: t("Sorry, I encountered an error processing that request.") }]);
        } finally {
            setIsThinking(false);
        }
    };

    const clearChat = () => {
        setHistory([{ role: 'assistant', content: t("Chat cleared. How can I help you now?") }]);
        setAttachedFile(null);
        setSuggestions([
            t("Write a catchy product description"),
            t("Add Size variations (S, M, L)"),
            t("Set price to $99 with 10% discount")
        ]);
    };

    if (!isOpen) {
        return (
            <Button 
                onClick={() => { setIsOpen(true); setIsMinimized(false); }}
                className="fixed bottom-24 sm:bottom-6 right-4 sm:right-6 h-14 w-14 rounded-full shadow-2xl bg-primary hover:bg-primary/90 text-primary-foreground z-50 p-0 transition-transform hover:scale-105"
            >
                <Sparkles className="w-6 h-6" />
            </Button>
        );
    }

    return (
        <div className={`fixed right-4 sm:right-6 z-50 flex flex-col bg-card border shadow-2xl rounded-2xl overflow-visible transition-all duration-300 ease-in-out ${
            isMinimized ? 'bottom-24 sm:bottom-6 w-[280px] h-[60px]' : 'bottom-24 sm:bottom-6 w-[90vw] sm:w-[400px] h-[600px] max-h-[80vh]'
        }`}>
            <AiAssistantHeader 
                title={title} 
                isMinimized={isMinimized} 
                setIsMinimized={setIsMinimized} 
                setIsOpen={setIsOpen} 
                clearChat={clearChat} 
            />

            {!isMinimized && (
                <>
                    <AiAssistantMessageList 
                        scrollRef={scrollRef} 
                        history={history} 
                        isThinking={isThinking} 
                    />

                    <AiAssistantInputArea 
                        input={input} 
                        handleInputChange={handleInputChange} 
                        handleKeyDown={handleKeyDown} 
                        handleSend={handleSend} 
                        isThinking={isThinking}
                        attachedFile={attachedFile} 
                        setAttachedFile={setAttachedFile} 
                        fileInputRef={fileInputRef} 
                        handleFileChange={handleFileChange}
                        showSlashMenu={showSlashMenu} 
                        filteredCommands={filteredCommands} 
                        slashIndex={slashIndex} 
                        applySlashCommand={applySlashCommand} 
                        placeholder={placeholder}
                        suggestions={suggestions} // <-- PASS SUGGESTIONS
                        handleSuggestionClick={handleSuggestionClick} // <-- PASS HANDLER
                    />
                </>
            )}
        </div>
    );
}