import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Card } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { cn } from '@/lib/utils';
import { useLaravelReactI18n } from 'laravel-react-i18n';
import { 
    Send, 
    X, 
    Minimize2, 
    Maximize2,
    Bot,
    Sparkles
} from 'lucide-react';

interface Message {
    id: string;
    text: string;
    isUser: boolean;
    timestamp: Date;
}

interface AiTouristGuideProps {
    pointOfInterestName?: string;
    className?: string;
}

export default function AiTouristGuide({ pointOfInterestName, className }: AiTouristGuideProps) {
    const [isOpen, setIsOpen] = useState(false);
    const [isMinimized, setIsMinimized] = useState(false);
    const [messages, setMessages] = useState<Message[]>([
        {
            id: '1',
            text: pointOfInterestName 
                ? `Hello! I'm your AI Tourist Guide. I can help you learn more about ${pointOfInterestName} and answer any questions you might have about this amazing destination!`
                : 'Hello! I\'m your AI Tourist Guide. How can I help you explore this destination today?',
            isUser: false,
            timestamp: new Date()
        }
    ]);
    const [inputText, setInputText] = useState('');
    const [isTyping, setIsTyping] = useState(false);
    
    const { t } = useLaravelReactI18n();

    const handleSendMessage = async () => {
        if (!inputText.trim()) return;

        const userMessage: Message = {
            id: Date.now().toString(),
            text: inputText.trim(),
            isUser: true,
            timestamp: new Date()
        };

        setMessages(prev => [...prev, userMessage]);
        setInputText('');
        setIsTyping(true);

        // Simulate AI response
        setTimeout(() => {
            const botMessage: Message = {
                id: (Date.now() + 1).toString(),
                text: `I'd be happy to help you with that! Based on your question about "${inputText.trim()}", I can share some insights about this location. This is a simulated response - the AI integration will be implemented soon.`,
                isUser: false,
                timestamp: new Date()
            };
            setMessages(prev => [...prev, botMessage]);
            setIsTyping(false);
        }, 2000);
    };

    const handleKeyDown = (e: React.KeyboardEvent) => {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            handleSendMessage();
        }
    };

    const formatTime = (date: Date) => {
        return date.toLocaleTimeString('en-US', { 
            hour: '2-digit', 
            minute: '2-digit',
            hour12: false
        });
    };

    // Floating chat button when closed
    if (!isOpen) {
        return (
            <div className={cn("fixed bottom-4 right-4 z-50 lg:bottom-4", "pb-14 lg:pb-0", className)}>
                <Button
                    onClick={() => setIsOpen(true)}
                    size="lg"
                    className="h-14 w-14 rounded-full shadow-lg hover:shadow-xl transition-all duration-300 bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700 group"
                >
                    <div className="relative">
                        <Bot className="h-6 w-6 text-white" />
                        <Sparkles className="absolute -top-1 -right-1 h-3 w-3 text-yellow-300 animate-pulse" />
                    </div>
                </Button>
                
                {/* Tooltip */}
                <div className="absolute bottom-full right-0 mb-2 opacity-0 group-hover:opacity-100 transition-opacity duration-200">
                    <div className="bg-gray-900 text-white text-sm px-3 py-2 rounded-lg whitespace-nowrap shadow-lg">
                        {t('Ask AI Tourist Guide')}
                        <div className="absolute top-full right-4 w-0 h-0 border-l-4 border-l-transparent border-r-4 border-r-transparent border-t-4 border-t-gray-900" />
                    </div>
                </div>
            </div>
        );
    }

    return (
        <div className={cn("fixed bottom-4 right-4 z-50 lg:bottom-4", "pb-12 lg:pb-0", className)}>
            <Card className={cn(
                "w-80 sm:w-96 shadow-xl border-0 overflow-hidden transition-all duration-300",
                isMinimized ? "h-16" : "h-96"
            )}>
                {/* Header */}
                <div className="bg-gradient-to-r from-blue-600 to-purple-600 p-4 text-white">
                    <div className="flex items-center justify-between">
                        <div className="flex items-center gap-3">
                            <div className="relative">
                                <Bot className="h-6 w-6" />
                                <div className="absolute -bottom-0.5 -right-0.5 w-3 h-3 bg-green-400 rounded-full border-2 border-white" />
                            </div>
                            <div>
                                <h3 className="font-semibold text-sm">{t('AI Tourist Guide')}</h3>
                                <p className="text-xs opacity-90">{t('Online')}</p>
                            </div>
                        </div>
                        <div className="flex items-center gap-2">
                            <Button
                                variant="ghost"
                                size="sm"
                                onClick={() => setIsMinimized(!isMinimized)}
                                className="h-8 w-8 p-0 text-white hover:bg-white/10"
                            >
                                {isMinimized ? (
                                    <Maximize2 className="h-4 w-4" />
                                ) : (
                                    <Minimize2 className="h-4 w-4" />
                                )}
                            </Button>
                            <Button
                                variant="ghost"
                                size="sm"
                                onClick={() => setIsOpen(false)}
                                className="h-8 w-8 p-0 text-white hover:bg-white/10"
                            >
                                <X className="h-4 w-4" />
                            </Button>
                        </div>
                    </div>
                </div>

                {!isMinimized && (
                    <>
                        {/* Messages */}
                        <div className="flex-1 overflow-y-auto p-4 space-y-4 h-64 bg-gray-50/50">
                            {messages.map((message) => (
                                <div
                                    key={message.id}
                                    className={cn(
                                        "flex",
                                        message.isUser ? "justify-end" : "justify-start"
                                    )}
                                >
                                    <div
                                        className={cn(
                                            "max-w-[80%] rounded-2xl px-4 py-2 text-sm",
                                            message.isUser
                                                ? "bg-blue-600 text-white rounded-br-md"
                                                : "bg-white border shadow-sm rounded-bl-md"
                                        )}
                                    >
                                        <p className="leading-relaxed">{message.text}</p>
                                        <p
                                            className={cn(
                                                "text-xs mt-1 opacity-70",
                                                message.isUser ? "text-blue-100" : "text-gray-500"
                                            )}
                                        >
                                            {formatTime(message.timestamp)}
                                        </p>
                                    </div>
                                </div>
                            ))}
                            
                            {isTyping && (
                                <div className="flex justify-start">
                                    <div className="bg-white border shadow-sm rounded-2xl rounded-bl-md px-4 py-3">
                                        <div className="flex space-x-1">
                                            <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce [animation-delay:-0.3s]" />
                                            <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce [animation-delay:-0.15s]" />
                                            <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce" />
                                        </div>
                                    </div>
                                </div>
                            )}
                        </div>

                        {/* Input */}
                        <div className="p-4 border-t bg-white">
                            <div className="flex items-end gap-2">
                                <div className="flex-1">
                                    <textarea
                                        value={inputText}
                                        onChange={(e) => setInputText(e.target.value)}
                                        onKeyDown={handleKeyDown}
                                        placeholder={t('Ask me anything about this place...')}
                                        className="w-full resize-none border rounded-xl px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent max-h-20"
                                        rows={1}
                                        disabled={isTyping}
                                    />
                                </div>
                                <Button
                                    onClick={handleSendMessage}
                                    disabled={!inputText.trim() || isTyping}
                                    size="sm"
                                    className="h-10 w-10 rounded-xl bg-blue-600 hover:bg-blue-700"
                                >
                                    <Send className="h-4 w-4" />
                                </Button>
                            </div>
                            
                            <div className="flex flex-wrap gap-2 mt-2">
                                {['Opening hours', 'How to get there', 'Best time to visit'].map((suggestion) => (
                                    <Badge
                                        key={suggestion}
                                        variant="secondary"
                                        className="cursor-pointer hover:bg-blue-100 text-xs px-2 py-1"
                                        onClick={() => setInputText(suggestion)}
                                    >
                                        {t(suggestion)}
                                    </Badge>
                                ))}
                            </div>
                        </div>
                    </>
                )}
            </Card>
        </div>
    );
}