'use client';

import React, { useState, useEffect, useRef } from 'react';
import { useRouter, usePathname } from 'next/navigation';
import {
  X,
  Send,
  ExternalLink,
} from 'lucide-react';
import { apiRequest } from '@/lib/api';

interface ChatMessage {
  id: string;
  sender: 'ai' | 'user';
  text: string;
  timestamp: Date;
  suggestedAction?: {
    label: string;
    href: string;
  };
}

export default function FloatingAIAssistant() {
  const router = useRouter();
  const currentPathname = usePathname();

  const [isOpen, setIsOpen] = useState(false);
  const [showTooltip, setShowTooltip] = useState(true);

  // Input & Chat State
  const [inputQuery, setInputQuery] = useState('');
  const [isTyping, setIsTyping] = useState(false);
  const [messages, setMessages] = useState<ChatMessage[]>([]);

  const chatEndRef = useRef<HTMLDivElement>(null);

  // Initial greeting
  useEffect(() => {
    setMessages([
      {
        id: 'welcome_1',
        sender: 'ai',
        text: `Hi! I'm your **WhatsApp Commerce AI Setup Guide**! 🤖\n\nI can guide you step-by-step through creating your **Meta WhatsApp App**, generating your **Permanent Meta Token**, configuring **Webhooks**, and connecting your store.\n\n**Quick Links:**\n- [Meta Developer Portal](https://developers.facebook.com/apps/)\n- [Meta Business Settings](https://business.facebook.com/settings/system-users)\n- [WhatsApp Setup Page](/dashboard/integrations)\n\nHow can I help you today?`,
        timestamp: new Date(),
        suggestedAction: {
          label: 'Open Meta Developer Portal',
          href: 'https://developers.facebook.com/apps/',
        },
      },
    ]);

    // Hide speech bubble tooltip after 10 seconds
    const timer = setTimeout(() => setShowTooltip(false), 10000);
    return () => clearTimeout(timer);
  }, []);

  // Scroll to bottom when new messages arrive
  useEffect(() => {
    if (isOpen) {
      chatEndRef.current?.scrollIntoView({ behavior: 'smooth' });
    }
  }, [messages, isOpen]);

  const navigateTo = (href: string) => {
    if (href.startsWith('http://') || href.startsWith('https://')) {
      window.open(href, '_blank', 'noopener,noreferrer');
    } else {
      router.push(href);
    }
  };

  // Offline / Knowledge Base Generator focusing on Meta Apps and Store Setup
  const generateOfflineResponse = (query: string): { text: string; action?: { label: string; href: string } } => {
    const q = query.toLowerCase();

    // META APP CREATION
    if (q.includes('meta app') || q.includes('create app') || q.includes('developer') || q.includes('facebook app') || q.includes('create a app')) {
      return {
        text: `**How to Create a Meta WhatsApp App (Step-by-Step):**\n\n` +
          `1. **Open Meta Developer Portal:** Go to the [Meta Developer Portal](https://developers.facebook.com/apps/) and log in with your Facebook account.\n` +
          `2. **Create New App:** Click **Create App** > Select **Other** > Choose **Business** as your app type.\n` +
          `3. **Add WhatsApp Product:** In your App Dashboard, scroll down to **WhatsApp** and click **Set Up**.\n` +
          `4. **Copy API Credentials:** Go to *WhatsApp > API Setup* to view your **Phone Number ID**, **WhatsApp Business Account ID**, and temporary token.\n` +
          `5. **Configure Store:** Paste your IDs into our [WhatsApp Integration Page](/dashboard/integrations).\n\n` +
          `Read official Meta docs: [Meta Cloud API Getting Started](https://developers.facebook.com/docs/whatsapp/cloud-api/get-started).`,
        action: { label: 'Go to Meta Developer Portal', href: 'https://developers.facebook.com/apps/' },
      };
    }

    // META PERMANENT TOKEN & SYSTEM USERS
    if (q.includes('token') || q.includes('system user') || q.includes('permanent') || q.includes('access token') || q.includes('secret')) {
      return {
        text: `**How to Generate a Permanent Meta Access Token:**\n\n` +
          `1. **Open Business Settings:** Go to [Meta Business Settings](https://business.facebook.com/settings/system-users).\n` +
          `2. **Add System User:** Navigate to **System Users** > Click **Add** > Name your user and select **Admin** role.\n` +
          `3. **Assign Assets:** Click **Add Assets** > Select **Apps** > Choose your WhatsApp App and enable full control.\n` +
          `4. **Generate Token:** Click **Generate New Token** > Select your App > Check permissions \`whatsapp_business_management\` and \`whatsapp_business_messaging\`.\n` +
          `5. **Save Token:** Copy your permanent access token and paste it in [WhatsApp Integrations](/dashboard/integrations).\n\n` +
          `Official guide: [Meta System Users Documentation](https://developers.facebook.com/docs/whatsapp/business-management-api/get-started).`,
        action: { label: 'Open Meta Business Settings', href: 'https://business.facebook.com/settings/system-users' },
      };
    }

    // WEBHOOK SETUP
    if (q.includes('webhook') || q.includes('callback') || q.includes('verify token')) {
      return {
        text: `**How to Configure Meta Webhooks for Live Messaging:**\n\n` +
          `1. **Go to Webhook Config:** In your [Meta App Dashboard](https://developers.facebook.com/apps/), go to *WhatsApp > Configuration*.\n` +
          `2. **Edit Callback URL:** Click **Edit Webhook** and enter your public server URL (e.g. \`https://your-domain.com/whatsapp/webhook\`).\n` +
          `3. **Enter Verify Token:** Use your configured verify token (e.g. \`whatsapp-verify-token\`).\n` +
          `4. **Subscribe to Events:** Toggle subscription for the **messages** webhook field.\n\n` +
          `Read official setup docs: [Meta Webhooks Setup Guide](https://developers.facebook.com/docs/whatsapp/cloud-api/guides/set-up-webhooks).`,
        action: { label: 'Meta Webhooks Documentation', href: 'https://developers.facebook.com/docs/whatsapp/cloud-api/guides/set-up-webhooks' },
      };
    }

    // WHATSAPP API GENERAL
    if (q.includes('whatsapp') || q.includes('connect') || q.includes('phone') || q.includes('channel')) {
      return {
        text: `**Connecting WhatsApp Business API:**\n\n` +
          `To pair your store with WhatsApp:\n` +
          `1. Create your app on [Meta Developer Portal](https://developers.facebook.com/apps/).\n` +
          `2. Obtain your Phone Number ID and Business Account ID from *WhatsApp > API Setup*.\n` +
          `3. Generate a permanent token in [Meta Business Settings](https://business.facebook.com/settings/system-users).\n` +
          `4. Enter all credentials in [WhatsApp Integrations](/dashboard/integrations).`,
        action: { label: 'Go to WhatsApp Integrations', href: '/dashboard/integrations' },
      };
    }

    // PRODUCTS CATALOG & SYNC
    if (q.includes('product') || q.includes('catalog') || q.includes('sync') || q.includes('inventory')) {
      return {
        text: `**Product Catalog Management:**\n\n` +
          `To list items for WhatsApp buyers:\n` +
          `1. Navigate to [Products & Sync](/dashboard/products).\n` +
          `2. Add products manually or import your WooCommerce / Meta catalog.\n` +
          `3. Set prices, currencies (USD/ZWL/ZWG), and stock levels.`,
        action: { label: 'Go to Products & Sync', href: '/dashboard/products' },
      };
    }

    // PAYMENTS
    if (q.includes('payment') || q.includes('ecocash') || q.includes('paynow') || q.includes('pesepay')) {
      return {
        text: `**Payment Gateway Setup:**\n\n` +
          `Accept instant payments inside WhatsApp chats:\n` +
          `1. Go to [Integrations Page](/dashboard/integrations) -> Payment Gateways.\n` +
          `2. Enable EcoCash, Paynow, or PesePay.\n` +
          `3. Customers will receive instant payment links upon checkout!`,
        action: { label: 'Configure Payments', href: '/dashboard/integrations' },
      };
    }

    // DEFAULT OVERVIEW
    return {
      text: `**WhatsApp Commerce Setup Overview:**\n\n` +
        `Here is everything you need to get started:\n` +
        `1. **Create Meta App:** [Meta Developer Portal](https://developers.facebook.com/apps/)\n` +
        `2. **Permanent Token:** [Meta System Users](https://business.facebook.com/settings/system-users)\n` +
        `3. **Connect API:** [WhatsApp Integration](/dashboard/integrations)\n` +
        `4. **Manage Catalog:** [Products & Sync](/dashboard/products)\n` +
        `5. **Enable Payments:** [Payment Settings](/dashboard/integrations)\n\n` +
        `Ask me any question about Meta setup, Webhooks, or Store configuration!`,
      action: { label: 'Open Meta Developer Portal', href: 'https://developers.facebook.com/apps/' },
    };
  };

  // Send query to configured backend AI API endpoint or offline fallback
  const handleSendMessage = async (queryText?: string) => {
    const textToSend = queryText || inputQuery;
    if (!textToSend.trim()) return;

    const userMsg: ChatMessage = {
      id: `user_${Date.now()}`,
      sender: 'user',
      text: textToSend.trim(),
      timestamp: new Date(),
    };

    setMessages((prev) => [...prev, userMsg]);
    if (!queryText) setInputQuery('');
    setIsTyping(true);

    try {
      const systemPrompt = `You are the AI Onboarding Assistant for WhatsApp Commerce Hub.
Current Page: ${currentPathname}

Instructions & Knowledge Base:
- Provide clear, encouraging, step-by-step instructions for Meta WhatsApp App creation and WhatsApp Commerce setup.
- Always include direct markdown links when explaining Meta or Store steps:
  - Meta App Creation: [Meta Developer Portal](https://developers.facebook.com/apps/)
  - Meta System Users & Tokens: [Meta Business Settings](https://business.facebook.com/settings/system-users)
  - Meta Webhooks: [Meta Webhooks Setup Guide](https://developers.facebook.com/docs/whatsapp/cloud-api/guides/set-up-webhooks)
  - Meta Cloud API Docs: [Meta Cloud API Getting Started](https://developers.facebook.com/docs/whatsapp/cloud-api/get-started)
  - Internal Hub Pages: [Connect WhatsApp](/dashboard/integrations), [Manage Products](/dashboard/products), [Edit Templates](/dashboard/templates), [Setup Payments](/dashboard/integrations), [Store Profile](/dashboard/profile)
- Keep formatting clean, markdown-enabled, and user-friendly.`;

      const chatMessages = [
        { role: 'system', content: systemPrompt },
        ...messages.slice(-6).map((m) => ({
          role: m.sender === 'user' ? 'user' : 'assistant',
          content: m.text,
        })),
        { role: 'user', content: textToSend },
      ];

      // Query backend NestJS OpenRouter API endpoint
      try {
        const backendRes = await apiRequest<{ success: boolean; text: string }>('ai/chat', 'POST', {
          messages: chatMessages,
          model: 'openai/gpt-oss-20b:free',
        });

        if (backendRes && backendRes.text) {
          const aiResponseText = backendRes.text;
          let action: { label: string; href: string } | undefined;

          if (aiResponseText.includes('developers.facebook.com/apps')) {
            action = { label: 'Go to Meta Developer Portal', href: 'https://developers.facebook.com/apps/' };
          } else if (aiResponseText.includes('business.facebook.com')) {
            action = { label: 'Open Meta Business Settings', href: 'https://business.facebook.com/settings/system-users' };
          } else if (aiResponseText.includes('/dashboard/integrations')) {
            action = { label: 'Open Integrations', href: '/dashboard/integrations' };
          } else if (aiResponseText.includes('/dashboard/products')) {
            action = { label: 'Open Products', href: '/dashboard/products' };
          }

          setMessages((prev) => [
            ...prev,
            {
              id: `ai_${Date.now()}`,
              sender: 'ai',
              text: aiResponseText,
              timestamp: new Date(),
              suggestedAction: action,
            },
          ]);
          setIsTyping(false);
          return;
        }
      } catch {
        // Fall back gracefully to offline response generator if OpenRouter key is not set or network fails
      }

      // Offline / Knowledge-base Fallback
      setTimeout(() => {
        const offlineResult = generateOfflineResponse(textToSend);
        setMessages((prev) => [
          ...prev,
          {
            id: `ai_${Date.now()}`,
            sender: 'ai',
            text: offlineResult.text,
            timestamp: new Date(),
            suggestedAction: offlineResult.action,
          },
        ]);
        setIsTyping(false);
      }, 350);
    } catch {
      const offlineResult = generateOfflineResponse(textToSend);
      setMessages((prev) => [
        ...prev,
        {
          id: `ai_${Date.now()}`,
          sender: 'ai',
          text: offlineResult.text,
          timestamp: new Date(),
          suggestedAction: offlineResult.action,
        },
      ]);
      setIsTyping(false);
    }
  };

  const parseFormattedText = (text: string) => {
    const lines = text.split('\n');
    return lines.map((line, idx) => {
      // Regex matching markdown bold **bold** and markdown links [text](url)
      const regex = /(\*\*.*?\*\*|\[.*?\]\(.*?\))/g;
      const parts = line.split(regex);

      return (
        <p key={idx} className={line.trim() === '' ? 'h-2' : 'mb-1.5 leading-relaxed text-xs'}>
          {parts.map((part, pIdx) => {
            if (part.startsWith('**') && part.endsWith('**')) {
              return (
                <strong key={pIdx} className="font-bold text-emerald-400 dark:text-emerald-400">
                  {part.slice(2, -2)}
                </strong>
              );
            }
            if (part.startsWith('[') && part.includes('](') && part.endsWith(')')) {
              const match = part.match(/^\[(.*?)\]\((.*?)\)$/);
              if (match) {
                const label = match[1];
                const url = match[2];
                if (url.startsWith('http://') || url.startsWith('https://')) {
                  return (
                    <a
                      key={pIdx}
                      href={url}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="text-emerald-400 dark:text-emerald-400 underline font-semibold hover:opacity-80 inline-flex items-center gap-0.5 mx-0.5"
                    >
                      <span>{label}</span>
                      <ExternalLink className="w-2.5 h-2.5 inline" />
                    </a>
                  );
                }
                return (
                  <button
                    key={pIdx}
                    type="button"
                    onClick={() => navigateTo(url)}
                    className="text-emerald-400 dark:text-emerald-400 underline font-semibold hover:opacity-80 cursor-pointer mx-0.5"
                  >
                    {label}
                  </button>
                );
              }
            }
            return part;
          })}
        </p>
      );
    });
  };

  return (
    <>
      {/* FLOATING BOT TRIGGER (BOTTOM RIGHT) */}
      <div className="fixed bottom-6 right-6 z-50 flex flex-col items-end gap-2 group">
        {/* Optional Speech Bubble Tooltip */}
        {showTooltip && !isOpen && (
          <div className="ai-tooltip-bubble relative text-xs font-bold px-3.5 py-2 animate-bounce flex items-center gap-2 max-w-xs">
            <span className="ai-tooltip-text">Ask AI for Meta App Setup & Links!</span>
            <button
              onClick={(e) => {
                e.stopPropagation();
                setShowTooltip(false);
              }}
              className="p-0.5 transition-colors cursor-pointer"
              title="Dismiss tooltip"
            >
              <X className="w-3.5 h-3.5" />
            </button>
            <div className="ai-tooltip-arrow absolute -bottom-1.5 right-6 w-3 h-3 rotate-45" />
          </div>
        )}

        {/* Floating Robot GIF Trigger Button */}
        <button
          onClick={() => {
            setIsOpen(!isOpen);
            setShowTooltip(false);
          }}
          className="relative transition-all duration-300 transform hover:scale-110 active:scale-95 cursor-pointer focus:outline-none"
          title="Open AI Setup Guide"
          aria-label="Open AI Setup Guide"
        >
          {/* 3D Robot GIF Container (Transparent Background) */}
          <div className="relative w-16 h-16 md:w-20 md:h-20 bg-transparent flex items-center justify-center">
            <img
              src="/assets/3d-casual-life-gpt-robot-with-speech-bubble.gif"
              alt="AI Onboarding Assistant"
              className="w-full h-full object-contain scale-110"
            />
          </div>
        </button>
      </div>

      {/* FLOATING AI ASSISTANT PANEL */}
      {isOpen && (
        <div className="ai-assistant-modal fixed bottom-24 right-4 md:right-6 z-50 w-[92vw] sm:w-[380px] md:w-[430px] max-h-[620px] h-[580px] flex flex-col border rounded-3xl shadow-2xl backdrop-blur-xl font-sans overflow-hidden animate-in fade-in slide-in-from-bottom-5 duration-300">
          {/* ASSISTANT HEADER */}
          <div className="ai-assistant-header p-4 flex items-center justify-between shrink-0 border-b border-[#d1cbbe]/20 dark:border-white/10">
            <div className="flex items-center gap-3">
              <div className="relative w-8 h-8 rounded-full bg-[#008069] flex items-center justify-center p-1.5 shrink-0 shadow-sm">
                <img
                  src="/assets/icons8-ai.svg"
                  alt="AI Icon"
                  className="w-full h-full object-contain brightness-0 invert"
                />
              </div>
              <div>
                <h3 className="text-sm font-black tracking-wide">AI Setup Assistant</h3>
              </div>
            </div>

            <div className="flex items-center gap-1">
              <button
                onClick={() => setIsOpen(false)}
                className="p-2 rounded-xl transition-colors cursor-pointer hover:bg-black/5 dark:hover:bg-white/10"
                title="Close Assistant"
              >
                <X className="w-4 h-4" />
              </button>
            </div>
          </div>

          {/* CHAT MESSAGES & INPUT AREA */}
          <div className="flex-1 flex flex-col min-h-0 overflow-hidden">
            {/* MESSAGES LIST */}
            <div className="ai-chat-messages-area flex-1 overflow-y-auto p-4 space-y-3.5 scrollbar-thin">
              {messages.map((msg) => (
                <div
                  key={msg.id}
                  className={`flex ${
                    msg.sender === 'user' ? 'justify-end' : 'justify-start'
                  }`}
                >
                  <div className="space-y-2 max-w-[88%]">
                    <div
                      className={`p-3.5 rounded-2xl text-xs shadow-sm ${
                        msg.sender === 'user'
                          ? 'ai-msg-user rounded-tr-none'
                          : 'ai-msg-bot rounded-tl-none'
                      }`}
                    >
                      {parseFormattedText(msg.text)}
                    </div>

                    {/* ACTION BUTTON LINK INSIDE MESSAGE */}
                    {msg.suggestedAction && (
                      <button
                        onClick={() => navigateTo(msg.suggestedAction!.href)}
                        className="ai-action-btn px-3 py-1.5 rounded-xl text-[11px] font-bold transition-all cursor-pointer shadow-sm flex items-center gap-1.5"
                      >
                        <span>{msg.suggestedAction.label}</span>
                        {msg.suggestedAction.href.startsWith('http') && (
                          <ExternalLink className="w-3 h-3" />
                        )}
                      </button>
                    )}
                  </div>
                </div>
              ))}

              {isTyping && (
                <div className="ai-msg-bot flex items-center gap-2 text-xs p-2.5 rounded-2xl w-fit">
                  <span className="w-2 h-2 rounded-full bg-[#008069] animate-ping" />
                  <span>AI is thinking...</span>
                </div>
              )}
              <div ref={chatEndRef} />
            </div>

            {/* QUICK PROMPT SUGGESTION CHIPS */}
            <div className="ai-prompt-bar px-3 py-2 flex items-center gap-1.5 overflow-x-auto scrollbar-none shrink-0 border-t border-[#d1cbbe]/20 dark:border-white/10">
              <button
                onClick={() => handleSendMessage('How to create a Meta App?')}
                className="ai-prompt-chip px-2.5 py-1 rounded-full text-[10px] font-medium whitespace-nowrap transition-colors cursor-pointer shrink-0"
              >
                Create Meta App?
              </button>
              <button
                onClick={() => handleSendMessage('How to get Meta Permanent Token?')}
                className="ai-prompt-chip px-2.5 py-1 rounded-full text-[10px] font-medium whitespace-nowrap transition-colors cursor-pointer shrink-0"
              >
                Get Meta Token?
              </button>
              <button
                onClick={() => handleSendMessage('How to setup Meta Webhooks?')}
                className="ai-prompt-chip px-2.5 py-1 rounded-full text-[10px] font-medium whitespace-nowrap transition-colors cursor-pointer shrink-0"
              >
                Setup Webhooks?
              </button>
              <button
                onClick={() => handleSendMessage('How do I connect WhatsApp API?')}
                className="ai-prompt-chip px-2.5 py-1 rounded-full text-[10px] font-medium whitespace-nowrap transition-colors cursor-pointer shrink-0"
              >
                Connect WhatsApp?
              </button>
              <button
                onClick={() => handleSendMessage('How do payment gateways work?')}
                className="ai-prompt-chip px-2.5 py-1 rounded-full text-[10px] font-medium whitespace-nowrap transition-colors cursor-pointer shrink-0"
              >
                Setup Payments?
              </button>
            </div>

            {/* COMPACT TEXTAREA CHAT INPUT */}
            <div className="ai-input-bar p-3 shrink-0">
              <form
                onSubmit={(e) => {
                  e.preventDefault();
                  handleSendMessage();
                }}
                className="flex items-center gap-2"
              >
                <textarea
                  rows={1}
                  value={inputQuery}
                  onChange={(e) => setInputQuery(e.target.value)}
                  onKeyDown={(e) => {
                    if (e.key === 'Enter' && !e.shiftKey) {
                      e.preventDefault();
                      handleSendMessage();
                    }
                  }}
                  placeholder="Ask AI about Meta App setup, tokens, webhooks..."
                  className="ai-input-field flex-1 px-3 py-2 rounded-xl text-xs focus:outline-none focus:border-emerald-500 resize-none max-h-20 scrollbar-none"
                />

                <button
                  type="submit"
                  disabled={!inputQuery.trim() || isTyping}
                  className="p-2.5 bg-[#008069] hover:bg-[#006e5a] disabled:opacity-50 text-white rounded-xl transition-all font-bold cursor-pointer shrink-0 shadow-sm"
                  title="Send message"
                >
                  <Send className="w-4 h-4" />
                </button>
              </form>
            </div>
          </div>
        </div>
      )}
    </>
  );
}

