import React, { useState, useEffect, useRef } from 'react';
import { Button } from './ui/button';
import { Card, CardContent, CardHeader, CardTitle } from './ui/card';
import { Badge } from './ui/badge';
import { 
  MessageCircle, 
  X, 
  Send, 
  Bot, 
  User,
  Minimize2,
  Maximize2
} from 'lucide-react';
import { Input } from './ui/input';
import { ScrollArea } from './ui/scroll-area';

interface Message {
  id: string;
  type: 'user' | 'bot';
  content: string;
  timestamp: Date;
  suggestions?: string[];
}

const initialMessage: Message = {
  id: '1',
  type: 'bot',
  content: "Hi! I'm here to help you explore KLC's leadership programs and facilities. What are you looking for today?",
  timestamp: new Date(),
  suggestions: [
    "Show me leadership programs",
    "Book a facility tour",
    "Upcoming webinars",
    "Contact information"
  ]
};

const botResponses: Record<string, { content: string; suggestions?: string[] }> = {
  "programs": {
    content: "Great! We offer various leadership development programs including Executive Leadership, Strategic Management, and Team Building workshops. Would you like to explore specific programs or see our full catalog?",
    suggestions: ["View all programs", "Executive programs", "Team building", "Custom corporate training"]
  },
  "leadership": {
    content: "Our leadership programs are designed to transform leaders at every level. We offer Executive Leadership Development, Strategic Leadership, Team Leadership, and Management Excellence programs.",
    suggestions: ["Executive Leadership", "Strategic Leadership", "Team Leadership", "Management Excellence"]
  },
  "facilities": {
    content: "Our state-of-the-art facilities include modern conference rooms, training halls, and collaboration spaces. You can take a virtual tour or book a facility for your event.",
    suggestions: ["Virtual tour", "Book conference room", "Training halls", "Facility pricing"]
  },
  "facility": {
    content: "Our learning facility features cutting-edge technology, flexible meeting spaces, and comfortable learning environments. We can accommodate groups from 10 to 500 participants.",
    suggestions: ["Book now", "View amenities", "Check availability", "Pricing information"]
  },
  "tour": {
    content: "I'd be happy to arrange a facility tour for you! Our tours showcase our modern classrooms, breakout spaces, and technology capabilities. Would you like to schedule one?",
    suggestions: ["Schedule tour", "Virtual tour", "Facility features", "Contact tour guide"]
  },
  "webinars": {
    content: "We host regular webinars on leadership topics. You can view upcoming sessions, register for live events, or access our library of recorded sessions.",
    suggestions: ["Upcoming webinars", "Recorded sessions", "Register for webinar", "Webinar schedule"]
  },
  "webinar": {
    content: "Our webinars cover essential leadership topics like Strategic Thinking, Team Management, Change Leadership, and Executive Presence. Most are free to attend!",
    suggestions: ["View schedule", "Register now", "Past recordings", "Webinar topics"]
  },
  "contact": {
    content: "You can reach us at info@klc.edu.in or call +91 11 4567 8900. Our team is available Monday to Friday, 9 AM to 6 PM IST. You can also schedule a consultation.",
    suggestions: ["Schedule consultation", "Email us", "Office locations", "Support hours"]
  },
  "executive": {
    content: "Our Executive Leadership programs are designed for senior leaders and C-suite executives. These intensive programs focus on strategic thinking, organizational transformation, and executive presence.",
    suggestions: ["Program details", "Enrollment", "Schedule", "Executive coaching"]
  },
  "strategic": {
    content: "Strategic Leadership development helps leaders think systematically about complex challenges, make better decisions, and drive organizational change effectively.",
    suggestions: ["Learn more", "Case studies", "Program schedule", "Apply now"]
  },
  "team": {
    content: "Team Leadership programs focus on building high-performing teams, improving collaboration, and developing emotional intelligence for team leaders.",
    suggestions: ["Team programs", "Workshop format", "Group discounts", "Custom training"]
  },
  "management": {
    content: "Management Excellence programs cover essential management skills including performance management, delegation, communication, and conflict resolution.",
    suggestions: ["Management training", "Skills assessment", "Corporate packages", "Schedule consultation"]
  },
  "pricing": {
    content: "Our pricing varies by program type and group size. Individual programs start from ₹15,000, while corporate packages offer significant discounts for bulk enrollments.",
    suggestions: ["Individual pricing", "Corporate packages", "Group discounts", "Payment options"]
  },
  "schedule": {
    content: "We offer programs throughout the year with flexible scheduling options. Most programs are available in weekend, weekday, and intensive formats.",
    suggestions: ["View calendar", "Weekend programs", "Weekday options", "Custom scheduling"]
  },
  "enrollment": {
    content: "Enrollment is simple! You can register online, call us directly, or schedule a consultation to discuss the best program for your needs.",
    suggestions: ["Register online", "Call us", "Schedule consultation", "Application process"]
  },
  "corporate": {
    content: "Our corporate solutions include custom leadership development programs, executive coaching, and organizational development services tailored to your company's needs.",
    suggestions: ["Custom programs", "Executive coaching", "Organizational development", "Corporate pricing"]
  },
  "coaching": {
    content: "We offer one-on-one executive coaching with certified leadership coaches. Our coaching programs are customized to address specific leadership challenges and goals.",
    suggestions: ["Coach profiles", "Coaching process", "Pricing", "Schedule session"]
  },
  "default": {
    content: "I can help you with information about our programs, facilities, webinars, and more. What would you like to know?",
    suggestions: ["Leadership programs", "Facility booking", "Webinars", "Contact us"]
  }
};

export function AIChatbot() {
  const [isVisible, setIsVisible] = useState(false);
  const [isOpen, setIsOpen] = useState(false);
  const [isMinimized, setIsMinimized] = useState(false);
  const [messages, setMessages] = useState<Message[]>([initialMessage]);
  const [inputValue, setInputValue] = useState('');
  const [isTyping, setIsTyping] = useState(false);
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const inactivityTimerRef = useRef<NodeJS.Timeout | null>(null);

  // Show chatbot after user activity
  useEffect(() => {
    const resetTimer = () => {
      if (inactivityTimerRef.current) {
        clearTimeout(inactivityTimerRef.current);
      }
      
      inactivityTimerRef.current = setTimeout(() => {
        if (!isOpen) {
          setIsVisible(true);
        }
      }, 8000); // Show after 8 seconds of activity
    };

    const events = ['mousedown', 'mousemove', 'keypress', 'scroll', 'touchstart'];
    
    const addEventListeners = () => {
      events.forEach(event => {
        document.addEventListener(event, resetTimer, true);
      });
    };

    const removeEventListeners = () => {
      events.forEach(event => {
        document.removeEventListener(event, resetTimer, true);
      });
    };

    addEventListeners();
    resetTimer();

    return () => {
      removeEventListeners();
      if (inactivityTimerRef.current) {
        clearTimeout(inactivityTimerRef.current);
      }
    };
  }, [isOpen]);

  // Auto-scroll to bottom of messages
  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages]);

  const getBotResponse = (userMessage: string): { content: string; suggestions?: string[] } => {
    const message = userMessage.toLowerCase();
    
    // Enhanced keyword matching
    if (message.includes('leadership') && (message.includes('program') || message.includes('course') || message.includes('training'))) {
      return botResponses.leadership;
    } else if (message.includes('executive') || message.includes('senior') || message.includes('c-suite')) {
      return botResponses.executive;
    } else if (message.includes('strategic') || message.includes('strategy')) {
      return botResponses.strategic;
    } else if (message.includes('team') || message.includes('collaboration')) {
      return botResponses.team;
    } else if (message.includes('management') || message.includes('manager')) {
      return botResponses.management;
    } else if (message.includes('program') || message.includes('course') || message.includes('training')) {
      return botResponses.programs;
    } else if (message.includes('facility') || message.includes('space') || message.includes('room')) {
      return botResponses.facility;
    } else if (message.includes('tour') || message.includes('visit')) {
      return botResponses.tour;
    } else if (message.includes('book') || message.includes('reserve') || message.includes('schedule')) {
      return botResponses.facilities;
    } else if (message.includes('webinar') || message.includes('session') || message.includes('online')) {
      return botResponses.webinar;
    } else if (message.includes('contact') || message.includes('phone') || message.includes('email') || message.includes('reach')) {
      return botResponses.contact;
    } else if (message.includes('price') || message.includes('cost') || message.includes('fee')) {
      return botResponses.pricing;
    } else if (message.includes('schedule') || message.includes('timing') || message.includes('when')) {
      return botResponses.schedule;
    } else if (message.includes('enroll') || message.includes('register') || message.includes('apply')) {
      return botResponses.enrollment;
    } else if (message.includes('corporate') || message.includes('company') || message.includes('organization')) {
      return botResponses.corporate;
    } else if (message.includes('coach') || message.includes('mentor') || message.includes('personal')) {
      return botResponses.coaching;
    } else {
      return botResponses.default;
    }
  };

  const handleSendMessage = async (content: string) => {
    if (!content.trim()) return;

    // Add user message
    const userMessage: Message = {
      id: Date.now().toString(),
      type: 'user',
      content: content.trim(),
      timestamp: new Date()
    };

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

    // Simulate typing delay with realistic timing
    setTimeout(() => {
      const response = getBotResponse(content);
      const botMessage: Message = {
        id: (Date.now() + 1).toString(),
        type: 'bot',
        content: response.content,
        timestamp: new Date(),
        suggestions: response.suggestions
      };

      setMessages(prev => [...prev, botMessage]);
      setIsTyping(false);
    }, 800 + Math.random() * 600); // 800ms to 1.4s delay
  };

  const handleSuggestionClick = (suggestion: string) => {
    handleSendMessage(suggestion);
  };

  const formatTime = (date: Date) => {
    return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  };

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

  if (!isVisible) return null;

  return (
    <>
      {/* Chatbot Toggle Button */}
      {!isOpen && (
        <Button
          onClick={() => setIsOpen(true)}
          className="fixed bottom-6 right-6 w-16 h-16 rounded-full shadow-xl z-50 transition-all duration-300 hover:scale-110 chatbot-button"
          style={{
            backgroundColor: 'var(--color-primary)',
            border: 'none'
          }}
          size="lg"
          aria-label="Open KLC Assistant chat"
        >
          <MessageCircle className="w-6 h-6 text-white" />
        </Button>
      )}

      {/* Chat Window */}
      {isOpen && (
        <Card className={`fixed bottom-6 right-6 w-80 md:w-96 shadow-2xl z-50 transition-all duration-300 border-0 ${
          isMinimized ? 'h-16' : 'h-[500px]'
        }`}>
          {/* Header */}
          <CardHeader 
            className="flex flex-row items-center justify-between space-y-0 pb-3 rounded-t-lg"
            style={{ backgroundColor: 'var(--color-primary)' }}
          >
            <div className="flex items-center gap-3">
              <div 
                className="w-10 h-10 rounded-full flex items-center justify-center"
                style={{ backgroundColor: 'rgba(255, 255, 255, 0.2)' }}
              >
                <Bot className="w-5 h-5 text-white" />
              </div>
              <div>
                <CardTitle className="text-base font-medium text-white" style={{ fontFamily: 'var(--font-family-base)' }}>
                  KLC Assistant
                </CardTitle>
                <div className="flex items-center gap-2 text-sm text-white opacity-90">
                  <div className="w-2 h-2 bg-green-400 rounded-full animate-pulse"></div>
                  <span style={{ fontFamily: 'var(--font-family-base)' }}>Online & Ready to Help</span>
                </div>
              </div>
            </div>
            <div className="flex items-center gap-1">
              <Button
                variant="ghost"
                size="sm"
                onClick={() => setIsMinimized(!isMinimized)}
                className="w-8 h-8 p-0 hover:bg-white/20 text-white"
                aria-label={isMinimized ? "Maximize chat" : "Minimize chat"}
              >
                {isMinimized ? (
                  <Maximize2 className="w-4 h-4" />
                ) : (
                  <Minimize2 className="w-4 h-4" />
                )}
              </Button>
              <Button
                variant="ghost"
                size="sm"
                onClick={() => setIsOpen(false)}
                className="w-8 h-8 p-0 hover:bg-white/20 text-white"
                aria-label="Close chat"
              >
                <X className="w-4 h-4" />
              </Button>
            </div>
          </CardHeader>

          {/* Chat Content */}
          {!isMinimized && (
            <CardContent className="p-0 flex flex-col h-[420px] overflow-y-auto">
              {/* Messages */}
              <ScrollArea className="flex-1 p-4">
                <div className="space-y-4">
                  {messages.map((message) => (
                    <div key={message.id} className={`flex ${message.type === 'user' ? 'justify-end' : 'justify-start'}`}>
                      <div className={`flex items-start gap-3 max-w-[85%] ${message.type === 'user' ? 'flex-row-reverse' : ''}`}>
                        <div className={`w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 ${
                          message.type === 'user' 
                            ? 'text-white' 
                            : 'bg-gray-100 text-gray-600'
                        }`}
                        style={message.type === 'user' ? { backgroundColor: 'var(--color-primary)' } : {}}
                        >
                          {message.type === 'user' ? (
                            <User className="w-4 h-4" />
                          ) : (
                            <Bot className="w-4 h-4" />
                          )}
                        </div>
                        <div className="space-y-2">
                          <div className={`p-3 rounded-lg ${
                            message.type === 'user'
                              ? 'text-white'
                              : 'bg-gray-50 text-gray-800'
                          }`}
                          style={message.type === 'user' ? { backgroundColor: 'var(--color-primary)' } : {}}
                          >
                            <p 
                              className="text-sm leading-relaxed"
                              style={{ fontFamily: 'var(--font-family-base)' }}
                            >
                              {message.content}
                            </p>
                          </div>
                          {message.suggestions && (
                            <div className="flex flex-wrap gap-2">
                              {message.suggestions.map((suggestion, index) => (
                                <Badge
                                  key={index}
                                  variant="outline"
                                  className="cursor-pointer transition-colors text-xs py-1 px-3 rounded-full font-normal border-gray-300 text-gray-700 hover:text-white"
                                  style={{ 
                                    fontFamily: 'var(--font-family-base)',
                                    borderColor: 'var(--color-primary)'
                                  }}
                                  onClick={() => handleSuggestionClick(suggestion)}
                                  onMouseEnter={(e:React.MouseEvent<HTMLButtonElement>) => {
                                    e.currentTarget.style.backgroundColor = 'var(--color-primary)';
                                    e.currentTarget.style.borderColor = 'var(--color-primary)';
                                  }}
                                  onMouseLeave={(e:React.MouseEvent<HTMLButtonElement>) => {
                                    e.currentTarget.style.backgroundColor = 'transparent';
                                    e.currentTarget.style.borderColor = 'var(--color-primary)';
                                  }}
                                >
                                  {suggestion}
                                </Badge>
                              ))}
                            </div>
                          )}
                          <p 
                            className="text-xs text-gray-500 px-1"
                            style={{ fontFamily: 'var(--font-family-base)' }}
                          >
                            {formatTime(message.timestamp)}
                          </p>
                        </div>
                      </div>
                    </div>
                  ))}
                  
                  {isTyping && (
                    <div className="flex justify-start">
                      <div className="flex items-start gap-3">
                        <div className="w-8 h-8 bg-gray-100 rounded-full flex items-center justify-center">
                          <Bot className="w-4 h-4 text-gray-600" />
                        </div>
                        <div className="bg-gray-50 p-3 rounded-lg">
                          <div className="flex gap-1">
                            <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce"></div>
                            <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style={{ animationDelay: '0.1s' }}></div>
                            <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style={{ animationDelay: '0.2s' }}></div>
                          </div>
                        </div>
                      </div>
                    </div>
                  )}
                  <div ref={messagesEndRef} />
                </div>
              </ScrollArea>

              {/* Input */}
              <div className="border-t p-4 bg-white">
                <form
                  onSubmit={(e) => {
                    e.preventDefault();
                    handleSendMessage(inputValue);
                  }}
                  className="flex gap-2"
                  role="form"
                  aria-label="Chat message form"
                >
                  <Input
                    value={inputValue}
                    onChange={(e) => setInputValue(e.target.value)}
                    onKeyPress={handleKeyPress}
                    placeholder="Type your message..."
                    className="flex-1 min-h-[44px] border-gray-200 focus:border-blue-500 focus:ring-blue-500"
                    style={{ 
                      fontSize: 'var(--font-body)',
                      fontFamily: 'var(--font-family-base)'
                    }}
                    disabled={isTyping}
                    aria-label="Chat message input"
                  />
                  <Button 
                    type="submit" 
                    size="sm" 
                    disabled={!inputValue.trim() || isTyping}
                    className="min-h-[44px] min-w-[44px] text-white transition-all duration-200"
                    style={{ 
                      backgroundColor: 'var(--color-primary)',
                      fontSize: 'var(--font-body)',
                      fontFamily: 'var(--font-family-base)'
                    }}
                    onMouseEnter={(e:React.MouseEvent<HTMLButtonElement>) => {
                      if (!e.currentTarget.disabled) {
                        e.currentTarget.style.backgroundColor = '#030359';
                      }
                    }}
                    onMouseLeave={(e:React.MouseEvent<HTMLButtonElement>) => {
                      if (!e.currentTarget.disabled) {
                        e.currentTarget.style.backgroundColor = 'var(--color-primary)';
                      }
                    }}
                  >
                    <Send className="w-4 h-4" />
                    <span className="sr-only">Send message</span>
                  </Button>
                </form>
                
                {/* Quick Help Text */}
                <p 
                  className="text-xs text-gray-500 mt-2 text-center"
                  style={{ fontFamily: 'var(--font-family-base)' }}
                >
                  Ask me about programs, facilities, or upcoming events
                </p>
              </div>
            </CardContent>
          )}
        </Card>
      )}
    </>
  );
}