import React, { useState, useEffect } from "react";
import { Send } from "lucide-react";
import { Modal } from "@/components/ui/modal";
import { Input } from "@/components/ui/input";
import apis, { BUCKET_ROOT } from "@/utils/apis";
import { useRouter } from "next/navigation";
import { currency } from "@/lib/utils";

interface ChatbotModalProps {
    isOpen: boolean;
    onClose: () => void;
}

const ChatbotModal: React.FC<ChatbotModalProps> = ({ isOpen, onClose }) => {

    const router = useRouter();

    const [userMessage, setUserMessage] = useState<string>("");
    const [chatMessages, setChatMessages] = useState<any[]>([]);
    const [chatId, setChatId] = useState<string | null>(null);
    const [botTyping, setBotTyping] = useState<boolean>(false);
    const [isFirstMessage, setIsFirstMessage] = useState<boolean>(true);

    const handleSendMessage = async () => {
        if (userMessage.trim()) {
            const newMessage = { sender: "user", message: userMessage };
            setChatMessages((prevMessages) => [...prevMessages, newMessage]);
            setUserMessage("");

            const payload = chatId
                ? { chatId, query: userMessage }
                : { query: userMessage };

            try {
                const response = await apis.chatBot.sendMessage(payload);

                if (!chatId && response?.chatId) {
                    setChatId(response.chatId);
                }

                setBotTyping(true);
                setTimeout(async () => {
                    if (response?.chatId) {
                        const botResponse = await apis.chatBot.getMessage(response.chatId);

                        if (botResponse && Array.isArray(botResponse) && botResponse[0]?.bot_reply) {
                            const data = botResponse[0];

                            const botMessage = {
                                sender: "bot",
                                message: data?.bot_reply,
                                matched_food_items: data?.matched_food_items || [],
                                matched_restaurants: data?.matched_restaurants || [],
                            };

                            setChatMessages((prevMessages) => [...prevMessages, botMessage]);
                            setBotTyping(false);
                        } else {
                            console.error("Bot reply not found in the response");
                            setBotTyping(false);
                        }
                    }
                }, 1000);
            } catch (error) {
                console.error("Error sending message:", error);
                setBotTyping(false);
            }
        }
    };

    useEffect(() => {
        if (isOpen && isFirstMessage) {
            const sendHelloMessage = async () => {
                const payload = chatId ? { chatId, query: "hello" } : { query: "hello" };

                try {
                    const response = await apis.chatBot.sendMessage(payload);

                    if (!chatId && response?.chatId) {
                        setChatId(response.chatId);
                    }

                    setBotTyping(true);
                    setTimeout(async () => {
                        if (response?.chatId) {
                            const botResponse = await apis.chatBot.getMessage(response.chatId);

                            if (botResponse && Array.isArray(botResponse) && botResponse[0]?.bot_reply) {
                                const data = botResponse[0];

                                const botMessage = {
                                    sender: "bot",
                                    message: data?.bot_reply,
                                    matched_food_items: data?.matched_food_items || [],
                                    matched_restaurants: data?.matched_restaurants || [],
                                };

                                setChatMessages((prevMessages) => [...prevMessages, botMessage]);
                                setBotTyping(false);
                            } else {
                                console.error("Bot reply not found in the response");
                                setBotTyping(false);
                            }
                        }
                    }, 1000);
                } catch (error) {
                    console.error("Error sending 'hello' message:", error);
                    setBotTyping(false);
                }
            };

            sendHelloMessage();
            setIsFirstMessage(false);
        }
    }, [isOpen, isFirstMessage, chatId]);

    return (
        <Modal isOpen={isOpen} onClose={onClose} title="Chatbot" description="Ask me anything" disableOverflow={true}>
            <div className="flex flex-col h-[500px] sm:w-full md:w-[400px] lg:w-[350px] xl:w-[400px] p-4 bg-white shadow-lg rounded-lg">
                <div className="flex-1 overflow-y-auto space-y-4 p-4">
                    {chatMessages.map((msg, idx) => (
                        <div key={idx} className={`flex flex-col ${msg.sender === "user" ? "items-end" : "items-start"}`}>
                            <div className={`relative max-w-[80%] rounded-2xl px-4 py-2 mb-2 ${msg.sender === "user" ? 'bg-primary text-white' : 'bg-[#F5F5F5] text-gray-800'}`}>
                                <p className="text-sm">{msg.message}</p>
                            </div>
                            {msg.sender === "bot" && (
                                <div className="w-full max-w-[80%] space-y-2 mt-1">
                                    {/* Restaurants */}
                                    {msg.matched_restaurants?.map((restaurant: any, rIdx: number) => (
                                        <div
                                            key={`r-${rIdx}`}
                                            className="flex items-center p-3 bg-white rounded-lg border border-gray-200 shadow-sm cursor-pointer hover:shadow transition-all duration-200"
                                            onClick={() => router.push(`/restaurant?id=${restaurant._id}`)}
                                        >
                                            <div className="w-12 h-12 bg-gray-200 rounded-md overflow-hidden flex-shrink-0">
                                                {restaurant.image && (
                                                    <img
                                                        src={`${BUCKET_ROOT}${restaurant.image}`}
                                                        alt={restaurant.restaurant_name}
                                                        className="w-full h-full object-cover"
                                                        onError={(e) => {
                                                            (e.target as HTMLImageElement).style.display = 'none';
                                                            const parent = (e.target as HTMLElement).parentElement;
                                                            if (parent) {
                                                                parent.classList.add('bg-gray-200');
                                                            }
                                                        }}
                                                    />
                                                )}
                                            </div>
                                            <div className="ml-3 min-w-0">
                                                <h4 className="text-sm font-medium text-gray-900 truncate">
                                                    {restaurant.restaurant_name}
                                                </h4>
                                                <p className="text-xs text-gray-500 truncate">
                                                    {restaurant.address?.area || 'Restaurant'}
                                                </p>
                                                <div className="flex items-center mt-1">
                                                    {restaurant.rating > 0 && (
                                                        <>
                                                            <span className="text-xs font-medium text-yellow-600">
                                                                {restaurant.rating.toFixed(1)} ★
                                                            </span>
                                                            <span className="mx-1 text-gray-300">•</span>
                                                        </>
                                                    )}
                                                    <span className="text-xs text-gray-500">
                                                        {restaurant.average_preparing_time || '30'} min
                                                    </span>
                                                    {restaurant.food_type?.length > 0 && (
                                                        <>
                                                            <span className="mx-1 text-gray-300">•</span>
                                                            <span className="text-xs text-gray-500 capitalize">
                                                                {restaurant.food_type[0]}
                                                            </span>
                                                        </>
                                                    )}
                                                </div>
                                            </div>
                                        </div>
                                    ))}

                                    {/* Food Items */}
                                    {msg.matched_food_items?.map((foodItem: any, fIdx: number) => (
                                        <div
                                            key={`f-${fIdx}`}
                                            className="flex items-center p-3 bg-white rounded-lg border border-gray-200 shadow-sm cursor-pointer hover:shadow transition-all duration-200"
                                            onClick={() => foodItem.restaurant_id && router.push(`/restaurant?id=${foodItem.restaurant_id}`)}
                                        >
                                            <div className="w-12 h-12 bg-gray-200 rounded-md overflow-hidden flex-shrink-0">
                                                {foodItem.image && (
                                                    <img
                                                        src={`${BUCKET_ROOT}${foodItem.image}`}
                                                        alt={foodItem.name}
                                                        className="w-full h-full object-cover"
                                                        onError={(e) => {
                                                            (e.target as HTMLImageElement).style.display = 'none';
                                                            const parent = (e.target as HTMLElement).parentElement;
                                                            if (parent) {
                                                                parent.classList.add('bg-gray-200');
                                                            }
                                                        }}
                                                    />
                                                )}
                                            </div>
                                            <div className="ml-3 min-w-0">
                                                <h4 className="text-sm font-medium text-gray-900 truncate">
                                                    {foodItem.name}
                                                </h4>
                                                <p className="text-xs text-gray-500 truncate">
                                                    {foodItem.description || foodItem.category}
                                                </p>
                                                <div className="flex items-center justify-between mt-1">
                                                    <span className="text-sm font-medium text-gray-900">
                                                        {currency}{foodItem.price?.toFixed(2) || '0.00'}
                                                    </span>
                                                    {foodItem.is_veg !== undefined && (
                                                        <span className={`inline-flex items-center justify-center w-4 h-4 rounded-full ${foodItem.is_veg ? 'bg-green-500' : 'bg-red-500'} ml-2`}>
                                                            <span className="sr-only">
                                                                {foodItem.is_veg ? 'Veg' : 'Non-Veg'}
                                                            </span>
                                                        </span>
                                                    )}
                                                </div>
                                            </div>
                                        </div>
                                    ))}
                                </div>
                            )}
                        </div>
                    ))}
                    {botTyping && (
                        <div className="flex justify-start">
                            <div className="bg-[#F5F5F5] px-4 py-2 rounded-2xl">
                                <div className="flex items-center space-x-1">
                                    <div className="w-2 h-2 bg-gray-400 rounded-full animate-pulse" />
                                    <div className="w-2 h-2 bg-gray-400 rounded-full animate-pulse delay-100" />
                                    <div className="w-2 h-2 bg-gray-400 rounded-full animate-pulse delay-200" />
                                </div>
                            </div>
                        </div>
                    )}
                </div>

                <div className="flex items-center mt-4 w-full bg-white border-t pt-3">
                    <Input
                        type="text"
                        placeholder="Type a message..."
                        className="flex-1 p-3 border border-gray-300 rounded-full shadow-sm focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
                        value={userMessage}
                        onChange={(e) => setUserMessage(e.target.value)}
                        onKeyPress={(e) => e.key === 'Enter' && handleSendMessage()}
                    />
                    <button
                        className="ml-2 p-2 bg-primary text-white rounded-full hover:bg-brand-400 transition duration-200 flex-shrink-0"
                        onClick={handleSendMessage}
                    >
                        <Send size={20} />
                    </button>
                </div>
            </div>
        </Modal>
    );
};

export default ChatbotModal;


