'use client';

import React, { useState, useRef, useEffect } from 'react';
import Link from 'next/link';
import {
  MessageSquare,
  X,
  Send,
  Sparkles,
  Bot,
  User,
  BookOpen,
  ShoppingBag,
  RotateCcw,
  Minimize2,
  Maximize2,
  ChevronRight,
} from 'lucide-react';
import api from '@/lib/api';

interface Message {
  id: string;
  role: 'user' | 'assistant';
  content: string;
  suggestedBooks?: Array<{
    id: string;
    title: string;
    slug: string;
    price: number;
    discountPrice?: number | null;
    coverImage?: string | null;
    authorName?: string;
    format?: string;
  }>;
}

export function AIChatWidget() {
  const [isOpen, setIsOpen] = useState(false);
  const [isExpanded, setIsExpanded] = useState(false);
  const [input, setInput] = useState('');
  const [loading, setLoading] = useState(false);
  const [messages, setMessages] = useState<Message[]>([
    {
      id: '1',
      role: 'assistant',
      content:
        'Namaste! I am Saraswati AI, your personal scholar and literary guide at Indian Books Worldwide. How may I help you explore our sacred texts, classical Sanskrit commentaries, and rare Indian publications today?',
    },
  ]);

  const messagesEndRef = useRef<HTMLDivElement>(null);

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

  useEffect(() => {
    if (isOpen) {
      scrollToBottom();
    }
  }, [messages, isOpen]);

  const quickPrompts = [
    'Recommend best Gita commentaries for scholars',
    'Find English translations of Upanishads',
    'Do you ship to USA and UK?',
    'What rare Ayurveda manuscripts are available?',
  ];

  const handleSendMessage = async (textToSend?: string) => {
    const text = textToSend || input;
    if (!text.trim() || loading) return;

    const userMessage: Message = {
      id: Date.now().toString(),
      role: 'user',
      content: text.trim(),
    };

    setMessages((prev) => [...prev, userMessage]);
    if (!textToSend) setInput('');
    setLoading(true);

    try {
      const chatHistory = [...messages, userMessage].map((m) => ({
        role: m.role,
        content: m.content,
      }));

      const res = await api.post('/ai/chat', { messages: chatHistory });
      const { reply, suggestedBooks } = res.data.data;

      const aiResponse: Message = {
        id: (Date.now() + 1).toString(),
        role: 'assistant',
        content: reply,
        suggestedBooks: suggestedBooks || [],
      };

      setMessages((prev) => [...prev, aiResponse]);
    } catch (err: any) {
      setMessages((prev) => [
        ...prev,
        {
          id: (Date.now() + 1).toString(),
          role: 'assistant',
          content:
            'I am currently experiencing a high volume of inquiries. Please browse our online store catalog or email support@indianbooksworldwide.com for personalized research assistance.',
        },
      ]);
    } finally {
      setLoading(false);
    }
  };

  const handleClearChat = () => {
    setMessages([
      {
        id: '1',
        role: 'assistant',
        content:
          'Namaste! How may I assist you with your exploration of Indian literature and philosophical treatises today?',
      },
    ]);
  };

  return (
    <div className="fixed bottom-6 right-6 z-50">
      {/* Floating Launcher Button */}
      {!isOpen && (
        <button
          onClick={() => setIsOpen(true)}
          className="group relative flex items-center gap-3 px-5 py-3.5 rounded-full bg-gradient-to-r from-[#701a08] to-[#9c240c] text-white shadow-2xl hover:shadow-[#701a08]/40 hover:scale-105 transition-all duration-300 border border-white/20"
        >
          <div className="relative">
            <Bot className="w-5 h-5" />
            <span className="absolute -top-1 -right-1 w-2.5 h-2.5 rounded-full bg-emerald-400 border-2 border-[#701a08] animate-pulse" />
          </div>
          <span className="text-xs font-black tracking-wide pr-1">Ask Saraswati AI</span>
          <Sparkles className="w-4 h-4 text-amber-300 animate-spin" style={{ animationDuration: '8s' }} />
        </button>
      )}

      {/* Floating Chat Window Modal */}
      {isOpen && (
        <div
          className={`flex flex-col bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-800 rounded-3xl shadow-2xl overflow-hidden transition-all duration-300 ${
            isExpanded ? 'w-[90vw] md:w-[680px] h-[85vh]' : 'w-[90vw] sm:w-[400px] h-[580px]'
          }`}
        >
          {/* Header */}
          <div className="p-4 bg-gradient-to-r from-[#701a08] to-[#8f1f0a] text-white flex items-center justify-between shadow-md">
            <div className="flex items-center gap-3">
              <div className="w-9 h-9 rounded-2xl bg-white/20 backdrop-blur-md flex items-center justify-center border border-white/30">
                <Bot className="w-5 h-5 text-amber-300" />
              </div>
              <div>
                <div className="flex items-center gap-1.5">
                  <h3 className="font-extrabold text-sm">Saraswati AI</h3>
                  <span className="px-1.5 py-0.5 rounded-full bg-emerald-500/20 text-emerald-300 text-[9px] font-bold border border-emerald-400/30">
                    Online
                  </span>
                </div>
                <p className="text-[10px] text-amber-200/80">Indian Literature & Vedic Assistant</p>
              </div>
            </div>

            <div className="flex items-center gap-1">
              <button
                onClick={handleClearChat}
                className="p-1.5 rounded-lg hover:bg-white/10 text-white/80 transition-colors"
                title="Reset Conversation"
              >
                <RotateCcw className="w-4 h-4" />
              </button>
              <button
                onClick={() => setIsExpanded(!isExpanded)}
                className="p-1.5 rounded-lg hover:bg-white/10 text-white/80 transition-colors hidden sm:block"
                title={isExpanded ? 'Collapse' : 'Expand'}
              >
                {isExpanded ? <Minimize2 className="w-4 h-4" /> : <Maximize2 className="w-4 h-4" />}
              </button>
              <button
                onClick={() => setIsOpen(false)}
                className="p-1.5 rounded-lg hover:bg-white/10 text-white/80 transition-colors"
                title="Close Assistant"
              >
                <X className="w-4 h-4" />
              </button>
            </div>
          </div>

          {/* Messages Body */}
          <div className="flex-1 overflow-y-auto p-4 space-y-4 text-xs bg-zinc-50/50 dark:bg-zinc-950/40">
            {messages.map((msg) => (
              <div
                key={msg.id}
                className={`flex gap-2.5 ${msg.role === 'user' ? 'justify-end' : 'justify-start'}`}
              >
                {msg.role === 'assistant' && (
                  <div className="w-7 h-7 rounded-xl bg-[#701a08] text-white flex items-center justify-center shrink-0 mt-0.5 shadow-sm">
                    <Bot className="w-4 h-4 text-amber-300" />
                  </div>
                )}

                <div
                  className={`max-w-[82%] rounded-2xl p-3.5 space-y-2 leading-relaxed shadow-sm ${
                    msg.role === 'user'
                      ? 'bg-[#701a08] text-white rounded-br-none'
                      : 'bg-white dark:bg-zinc-800 text-zinc-900 dark:text-zinc-100 border border-zinc-200 dark:border-zinc-700 rounded-bl-none'
                  }`}
                >
                  <p className="whitespace-pre-line">{msg.content}</p>

                  {/* RAG Suggested Product Cards */}
                  {msg.suggestedBooks && msg.suggestedBooks.length > 0 && (
                    <div className="pt-2 space-y-2 border-t border-zinc-100 dark:border-zinc-700">
                      <span className="text-[10px] font-extrabold uppercase tracking-wider text-[#701a08] dark:text-amber-400 block flex items-center gap-1">
                        <BookOpen className="w-3 h-3" /> Catalog Recommendations
                      </span>
                      <div className="space-y-1.5">
                        {msg.suggestedBooks.map((book) => (
                          <Link
                            key={book.id}
                            href={`/books/${book.slug}`}
                            onClick={() => setIsOpen(false)}
                            className="flex items-center gap-2.5 p-2 rounded-xl bg-zinc-50 dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-700 hover:border-[#701a08] transition-colors group"
                          >
                            {book.coverImage ? (
                              <img
                                src={book.coverImage}
                                alt={book.title}
                                className="w-8 h-11 object-cover rounded shadow-xs shrink-0"
                              />
                            ) : (
                              <div className="w-8 h-11 bg-zinc-200 dark:bg-zinc-800 rounded flex items-center justify-center text-[8px] text-zinc-400 shrink-0">
                                Book
                              </div>
                            )}
                            <div className="min-w-0 flex-1">
                              <h5 className="font-bold text-[11px] text-zinc-900 dark:text-zinc-100 line-clamp-1 group-hover:text-[#701a08] dark:group-hover:text-amber-400">
                                {book.title}
                              </h5>
                              <p className="text-[10px] text-zinc-400 line-clamp-1">{book.authorName}</p>
                              <span className="text-[10px] font-black text-[#701a08] dark:text-amber-400">
                                ₹{book.discountPrice || book.price}
                              </span>
                            </div>
                            <ChevronRight className="w-3.5 h-3.5 text-zinc-400 group-hover:text-[#701a08] transition-colors" />
                          </Link>
                        ))}
                      </div>
                    </div>
                  )}
                </div>

                {msg.role === 'user' && (
                  <div className="w-7 h-7 rounded-xl bg-zinc-300 dark:bg-zinc-700 text-zinc-800 dark:text-zinc-200 flex items-center justify-center shrink-0 mt-0.5">
                    <User className="w-4 h-4" />
                  </div>
                )}
              </div>
            ))}

            {loading && (
              <div className="flex gap-2.5 items-center text-zinc-400 text-xs">
                <div className="w-7 h-7 rounded-xl bg-[#701a08] text-white flex items-center justify-center shrink-0">
                  <Bot className="w-4 h-4 text-amber-300" />
                </div>
                <div className="bg-white dark:bg-zinc-800 border border-zinc-200 dark:border-zinc-700 p-3 rounded-2xl rounded-bl-none flex items-center gap-1.5 shadow-sm">
                  <span className="w-2 h-2 rounded-full bg-[#701a08] animate-bounce" />
                  <span className="w-2 h-2 rounded-full bg-[#701a08] animate-bounce [animation-delay:0.2s]" />
                  <span className="w-2 h-2 rounded-full bg-[#701a08] animate-bounce [animation-delay:0.4s]" />
                </div>
              </div>
            )}
            <div ref={messagesEndRef} />
          </div>

          {/* Quick Prompts Carousel */}
          {messages.length <= 2 && (
            <div className="px-3 py-2 bg-zinc-100 dark:bg-zinc-900 border-t border-zinc-200 dark:border-zinc-800 flex gap-1.5 overflow-x-auto no-scrollbar text-[11px]">
              {quickPrompts.map((prompt) => (
                <button
                  key={prompt}
                  onClick={() => handleSendMessage(prompt)}
                  className="px-2.5 py-1 rounded-lg bg-white dark:bg-zinc-800 border border-zinc-200 dark:border-zinc-700 hover:border-[#701a08] text-zinc-700 dark:text-zinc-300 whitespace-nowrap shrink-0 transition-colors"
                >
                  {prompt}
                </button>
              ))}
            </div>
          )}

          {/* Chat Input Bar */}
          <form
            onSubmit={(e) => {
              e.preventDefault();
              handleSendMessage();
            }}
            className="p-3 bg-white dark:bg-zinc-900 border-t border-zinc-200 dark:border-zinc-800 flex items-center gap-2"
          >
            <input
              type="text"
              value={input}
              onChange={(e) => setInput(e.target.value)}
              placeholder="Ask about Sanskrit texts, Upanishads, orders..."
              className="flex-1 px-3.5 py-2.5 rounded-xl border border-zinc-300 dark:border-zinc-700 bg-zinc-50 dark:bg-zinc-800 text-xs text-zinc-900 dark:text-zinc-100 placeholder:text-zinc-400 focus:outline-none"
            />
            <button
              type="submit"
              disabled={loading || !input.trim()}
              className="p-2.5 rounded-xl bg-[#701a08] hover:bg-[#581406] text-white shadow-md transition-all disabled:opacity-40 cursor-pointer"
            >
              <Send className="w-4 h-4" />
            </button>
          </form>
        </div>
      )}
    </div>
  );
}
