
'use client';

import { useState, useEffect, useRef, type FormEvent } from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardFooter, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Bot, X, SendHorizontal, Loader2, MessageSquarePlus, ExternalLink } from 'lucide-react';
import { assistantChat, type AssistantChatInput, type AssistantChatOutput } from '@/ai/flows/assistant-chat-flow';
import { cn } from '@/lib/utils';
import { APP_NAME, CONTACT_INFO } from '@/constants';
import Link from 'next/link';

interface Message {
  id: string;
  role: 'user' | 'ai' | 'error';
  content: string;
}

interface WhatsAppEscalationDetails {
  summary: string;
  buttonText: string;
}

const initialGreetingContent = `Hello! I'm the AI assistant for ${APP_NAME}. How can I help you today?`;

export function FloatingAssistant() {
  const [isOpen, setIsOpen] = useState(false);
  const [messages, setMessages] = useState<Message[]>([]);
  const [inputValue, setInputValue] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [suggestedReplies, setSuggestedReplies] = useState<string[]>([]);
  const [whatsAppEscalation, setWhatsAppEscalation] = useState<WhatsAppEscalationDetails | null>(null);
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };

  useEffect(scrollToBottom, [messages]);

  const fetchInitialGreeting = async () => {
    setIsLoading(true);
    setMessages([]); 
    setSuggestedReplies([]);
    setWhatsAppEscalation(null);
    try {
      const result: AssistantChatOutput = await assistantChat({ userInput: '', isInitialGreeting: true });
      const greetingMessage: Message = {
        id: crypto.randomUUID(),
        role: 'ai',
        content: result.aiResponse || initialGreetingContent,
      };
      setMessages([greetingMessage]);
      if (result.suggestedReplies && result.suggestedReplies.length > 0) {
        setSuggestedReplies(result.suggestedReplies);
      } else {
         setSuggestedReplies(["What services do you offer?", "Tell me about your projects", "How can I contact you?"]);
      }
    } catch (error) {
      console.error('Error fetching initial greeting:', error);
      const errorMessage: Message = {
        id: crypto.randomUUID(),
        role: 'ai', 
        content: initialGreetingContent,
      };
      setMessages([errorMessage]);
      setSuggestedReplies(["Services?", "Projects?", "Contact info?"]); 
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    if (isOpen && messages.length === 0) {
      fetchInitialGreeting();
    }
    if (isOpen) {
      setTimeout(() => inputRef.current?.focus(), 100); // Delay focus slightly for sheet animation
    }
  }, [isOpen]);


  const toggleChat = () => {
    setIsOpen(!isOpen);
  };

  const submitMessage = async (messageContent: string) => {
    if (!messageContent.trim() || isLoading) return;

    const userMsg: Message = {
      id: crypto.randomUUID(),
      role: 'user',
      content: messageContent.trim(),
    };
    
    const currentMessages = [...messages, userMsg];
    setMessages(currentMessages);
    setInputValue('');
    setIsLoading(true);
    setSuggestedReplies([]); 
    setWhatsAppEscalation(null);


    try {
      const chatHistoryForAI = messages.map(msg => ({role: msg.role === 'error' ? 'ai' : msg.role, content: msg.content}));
      
      const input: AssistantChatInput = { 
        userInput: userMsg.content,
        chatHistory: chatHistoryForAI 
      };
      const result: AssistantChatOutput = await assistantChat(input);
      const aiMsg: Message = {
        id: crypto.randomUUID(),
        role: 'ai',
        content: result.aiResponse,
      };
      setMessages((prevMessages) => [...prevMessages, aiMsg]);
      if (result.suggestedReplies && result.suggestedReplies.length > 0) {
        setSuggestedReplies(result.suggestedReplies);
      }
      if (result.whatsAppEscalation) {
        setWhatsAppEscalation(result.whatsAppEscalation);
      }
    } catch (error) {
      console.error('Error fetching AI response:', error);
      const errorMsg: Message = {
        id: crypto.randomUUID(),
        role: 'error',
        content: 'Sorry, I encountered an error. Please try again.',
      };
      setMessages((prevMessages) => [...prevMessages, errorMsg]);
    } finally {
      setIsLoading(false);
      inputRef.current?.focus();
    }
  };
  
  const handleFormSubmit = async (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    submitMessage(inputValue);
  };

  const handleSuggestedReplyClick = (reply: string) => {
    submitMessage(reply);
  };

  const whatsAppPhoneNumber = CONTACT_INFO.mainPhone.replace(/\s/g, "");

  return (
    <>
      <Button
        onClick={toggleChat}
        className="fixed bottom-6 right-6 z-50 h-16 w-16 rounded-full p-0 shadow-xl hover:scale-105 transition-transform"
        aria-label={isOpen ? 'Close AI assistant chat' : 'Open AI assistant chat'}
        variant="primary"
      >
        {isOpen ? <X className="h-8 w-8" /> : <MessageSquarePlus className="h-8 w-8" />}
      </Button>

      {isOpen && (
        <Card className="fixed bottom-24 right-6 z-50 w-[calc(100vw-3rem)] max-w-sm sm:max-w-md h-[75vh] max-h-[600px] flex flex-col shadow-2xl border-2 border-primary/20 rounded-xl">
          <CardHeader className="flex flex-row items-center justify-between p-4 border-b bg-primary/5 rounded-t-xl">
            <div className="flex items-center gap-2">
              <Bot className="h-7 w-7 text-primary" />
              <CardTitle className="text-lg font-semibold text-primary text-shadow-primary">{APP_NAME} Assistant</CardTitle>
            </div>
            <Button variant="ghost" size="icon" onClick={toggleChat} aria-label="Close chat" className="text-muted-foreground hover:text-primary">
              <X className="h-5 w-5" />
            </Button>
          </CardHeader>

          <CardContent className="flex-grow overflow-hidden p-2 flex flex-col bg-background">
            <ScrollArea className="flex-grow p-4 space-y-1">
              {messages.map((msg) => (
                <div
                  key={msg.id}
                  className={cn(
                    'flex flex-col mb-3 py-2 px-3.5 rounded-xl shadow-sm max-w-[85%] break-words text-sm leading-relaxed',
                    msg.role === 'user' ? 'ml-auto bg-primary text-primary-foreground rounded-br-none items-end' 
                                        : 'mr-auto bg-muted text-foreground rounded-bl-none items-start mb-1', // Added mb-1 for AI/error messages
                    msg.role === 'error' && 'bg-destructive text-destructive-foreground rounded-bl-none items-start mb-1'
                  )}
                >
                  <span>{msg.content}</span>
                </div>
              ))}
              {isLoading && messages.length > 0 && ( 
                <div className="flex items-center space-x-2 p-2 mr-auto bg-muted rounded-xl shadow-sm max-w-max">
                  <Loader2 className="h-4 w-4 animate-spin text-primary" />
                  <span className="text-xs text-muted-foreground">Assistant is thinking...</span>
                </div>
              )}
              <div ref={messagesEndRef} />
            </ScrollArea>
            
            {(suggestedReplies.length > 0 || whatsAppEscalation) && !isLoading && (
              <div className="px-3 py-2 border-t flex flex-col gap-2 justify-start bg-background/70 backdrop-blur-sm">
                {suggestedReplies.length > 0 && (
                  <div className="flex flex-wrap gap-2">
                    {suggestedReplies.map((reply, index) => (
                      <Button
                        key={`sugg-${index}`}
                        variant="outline"
                        size="sm"
                        className="rounded-full text-xs h-auto py-1.5 px-3 shadow-sm hover:bg-primary/10 border-primary/30 text-primary"
                        onClick={() => handleSuggestedReplyClick(reply)}
                      >
                        {reply}
                      </Button>
                    ))}
                  </div>
                )}
                {whatsAppEscalation && (
                  <Button
                    variant="default"
                    size="sm"
                    className="w-full mt-1 py-2 text-xs h-auto"
                    asChild
                  >
                    <Link 
                      href={`https://wa.me/${whatsAppPhoneNumber}?text=${encodeURIComponent(whatsAppEscalation.summary)}`}
                      target="_blank"
                      rel="noopener noreferrer"
                    >
                      {whatsAppEscalation.buttonText} <ExternalLink className="ml-2 h-3 w-3" />
                    </Link>
                  </Button>
                )}
              </div>
            )}
          </CardContent>
          
          <CardFooter className="p-3 border-t bg-primary/5 rounded-b-xl">
            <form onSubmit={handleFormSubmit} className="flex w-full items-center space-x-2">
              <Input
                ref={inputRef}
                type="text"
                placeholder="Ask something..."
                value={inputValue}
                onChange={(e) => setInputValue(e.target.value)}
                disabled={isLoading}
                className="flex-1 h-10 text-sm rounded-lg focus-visible:ring-primary/50"
                aria-label="Chat message input"
              />
              <Button type="submit" size="icon" disabled={isLoading || !inputValue.trim()} aria-label="Send message" className="rounded-lg h-10 w-10">
                {isLoading ? <Loader2 className="h-5 w-5 animate-spin" /> : <SendHorizontal className="h-5 w-5" />}
              </Button>
            </form>
          </CardFooter>
        </Card>
      )}
    </>
  );
}
