import React, { useCallback, useEffect, useRef } from 'react';
import Sidebar from './Sidebar/Sidebar';
import ChatArea from './ChatArea/ChatArea';
import InputSection from './ChatArea/InputSection';
import MobileHeader from './Header/MobileHeader';
import LoginModal from './Modals/LoginModal';
import RateLimitModal from './Modals/RateLimitModal';
import ConfirmDeleteModal from './Modals/ConfirmDeleteModal';
import ProposeChangesModal from './Modals/ProposeChangesModal';
import ReadApprovalModal from './Modals/ReadApprovalModal';
import ProfileLogo from './Logos/ProfileLogo';
import SettingsModal from './Modals/SettingsModal';
import SeoConsentBanner from './SeoConsent/SeoConsentBanner';
import Footer from './Footer/Footer';
import { useAuth } from '../contexts/AuthContext';
import { useSetIsSettingsModalOpen, useIsMobileSidebarOpen } from '../contexts/UIContext';
import { useCloneSeoPage, useCurrentConversationId } from '../contexts/ChatContext';
import useRenderTracker from '../hooks/useRenderTracker';
import MobileSidebar from './Sidebar/MobileSidebar';
import { ASSISTANT_ENABLED, TARGET_ENV, IS_WORDPRESS, SETUP_COMPLETED } from '../constants';
import AssistantDisabledGate from './AssistantDisabledGate';
import InitialSetupGate from './InitialSetupGate';

const ATIBA_CONTACT_URL = IS_WORDPRESS
  ? 'https://atiba.com/get-quote'
  : 'https://atiba.com/get-quote?utm_source=wpassistant&utm_medium=referral&utm_campaign=wpassistant&utm_id=10219074-wpassistant';

const WPAssistant: React.FC = () => {

  const setIsSettingsModalOpen = useSetIsSettingsModalOpen();
  const isMobileSidebarOpen = useIsMobileSidebarOpen();
  const currentConversationId = useCurrentConversationId();
  const { 
    isLoggedIn, 
    userInfo,
    hasDismissedBanner,
  } = useAuth();
  const cloneSeoPage = useCloneSeoPage();

  useRenderTracker('WPAssistant', {
    setIsSettingsModalOpen,
    isLoggedIn,
    userInfo,
  });

  // Check for clone_seo_page parameter on load
  useEffect(() => {
    if (!ASSISTANT_ENABLED) return;
    const urlParams = new URLSearchParams(window.location.search);
    const seoPageId = urlParams.get('continue_seo_page');
    
    if (seoPageId) {
      cloneSeoPage(seoPageId);
    }
  }, [cloneSeoPage, ASSISTANT_ENABLED]);

  // Memoized handler
  const handleSettingsOpen = useCallback(() => {
    setIsSettingsModalOpen(true);
  }, [setIsSettingsModalOpen]);

  const scrollRef = useRef<HTMLDivElement>(null);

  const scrollToBottom = useCallback((behavior: ScrollBehavior) => {
    const el = scrollRef.current;
    if (el) {
      el.scrollTo({ top: el.scrollHeight, behavior });
    }
  }, []);

  const scrollToTop = useCallback((behavior: ScrollBehavior) => {
    const el = scrollRef.current;
    if (el) {
      el.scrollTo({ top: 0, behavior });
    }
  }, []);

  // Calculate whether banner is showing
  const showBanner = !hasDismissedBanner && !IS_WORDPRESS;

  const openPluginSettings = useCallback(() => {
    const target = window.top ?? window;
    const targetUrl = 'admin.php?page=actionpanel-ai-settings';
    try {
      target.location.assign(targetUrl);
    } catch (e) {
      target.location.href = targetUrl;
    }
  }, []);

  if (TARGET_ENV === 'wordpress' && !SETUP_COMPLETED) {
    return (
      <div className="flex flex-col h-full min-h-0 bg-background-light dark:bg-background-dark text-text-light dark:text-text-dark">
        <MobileHeader />
        <LoginModal openSignup={true}/>
        <InitialSetupGate />
      </div>
    );
  }

  if (TARGET_ENV === 'wordpress' && !ASSISTANT_ENABLED) {
    return (
      <div className="flex flex-col h-full min-h-0 bg-background-light dark:bg-background-dark text-text-light dark:text-text-dark">
        <MobileHeader />
        <AssistantDisabledGate onOpenSettings={openPluginSettings} />
      </div>
    );
  }

  return (
    <div className="flex flex-col h-full overflow-hidden min-h-0 bg-background-light dark:bg-background-dark text-text-light dark:text-text-dark">
      <MobileHeader />
      <LoginModal openSignup={true}/>
      <ConfirmDeleteModal />
      <RateLimitModal />
      <SettingsModal />
      <ProposeChangesModal />
      <ReadApprovalModal />
      <div className="flex items-stretch flex-1 overflow-hidden min-h-0 h-full">
        <div className="flex-shrink-0 h-full">
          <Sidebar />
        </div>
        {isMobileSidebarOpen && (
          <MobileSidebar
          />
        )}
        <div
          className="flex flex-col flex-1 overflow-hidden min-h-0 transition-all duration-200 ease-in-out"
        >
          <div className="flex flex-col h-full relative min-h-0">
            <div className="w-full h-16 bg-background-light dark:bg-background-dark absolute top-0 left-0 z-10 hidden md:block">
              <div className="flex items-center h-full px-4 w-full">
                {showBanner && (
                  <div className="flex-grow flex justify-center max-w-[825px] mx-auto">
                    <SeoConsentBanner />
                  </div>
                )}
                <div className="absolute right-4 flex items-center">
                  {!IS_WORDPRESS && (
                  <nav className="mr-4">
                    <ul className="flex space-x-4 items-center">
                      <li>
                        <a 
                          href="https://wpassistant.ai/about" 
                          className="relative text-[15px] font-medium text-gray-700 dark:text-gray-200 hover:text-black dark:hover:text-white transition-colors duration-200 py-2 after:content-[''] after:absolute after:w-full after:h-[2px] after:bg-current after:left-0 after:bottom-0 after:scale-x-0 hover:after:scale-x-100 after:transition-transform after:duration-300"
                        >
                          About
                        </a>
                      </li>
                      <li>
                        <a 
                          href="https://wpassistant.ai/faq" 
                          className="relative text-[15px] font-medium text-gray-700 dark:text-gray-200 hover:text-black dark:hover:text-white transition-colors duration-200 py-2 after:content-[''] after:absolute after:w-full after:h-[2px] after:bg-current after:left-0 after:bottom-0 after:scale-x-0 hover:after:scale-x-100 after:transition-transform after:duration-300"
                        >
                          FAQ
                        </a>
                      </li>
                      <li className="relative group">
                        <button
                          type="button"
                          className="relative text-[15px] font-medium text-gray-700 dark:text-gray-200 hover:text-black dark:hover:text-white transition-colors duration-200 py-2 flex items-center"
                          aria-haspopup="true"
                          aria-expanded="false"
                        >
                          Knowledge Base
                          <span className="ml-1">▾</span>
                        </button>
                        <div className="absolute right-0 top-full z-[9000] w-64 bg-background-light dark:bg-background-dark border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg opacity-0 invisible group-hover:opacity-100 group-hover:visible focus-within:opacity-100 focus-within:visible transition-opacity px-3 py-3 max-h-[70vh] overflow-auto">
                          <ul className="space-y-1">
                            <li>
                              <a href="https://wpassistant.ai/knowledge-base/caching/" className="block px-3 py-2 text-sm dark:text-gray-400 text-gray-500 hover:text-foreground hover:bg-secondary/10 dark:hover:bg-secondary/40 transition-colors duration-0 rounded-lg">Caching</a>
                            </li>
                            <li>
                              <a href="https://wpassistant.ai/knowledge-base/content_management/" className="block px-3 py-2 text-sm dark:text-gray-400 text-gray-500 hover:text-foreground hover:bg-secondary/10 dark:hover:bg-secondary/40 transition-colors duration-0 rounded-lg">Content Management</a>
                            </li>
                            <li>
                              <a href="https://wpassistant.ai/knowledge-base/custom_development/" className="block px-3 py-2 text-sm dark:text-gray-400 text-gray-500 hover:text-foreground hover:bg-secondary/10 dark:hover:bg-secondary/40 transition-colors duration-0 rounded-lg">Custom Development</a>
                            </li>
                            <li>
                              <a href="https://wpassistant.ai/knowledge-base/database/" className="block px-3 py-2 text-sm dark:text-gray-400 text-gray-500 hover:text-foreground hover:bg-secondary/10 dark:hover:bg-secondary/40 transition-colors duration-0 rounded-lg">Database</a>
                            </li>
                            <li>
                              <a href="https://wpassistant.ai/knowledge-base/debugging/" className="block px-3 py-2 text-sm dark:text-gray-400 text-gray-500 hover:text-foreground hover:bg-secondary/10 dark:hover:bg-secondary/40 transition-colors duration-0 rounded-lg">Debugging</a>
                            </li>
                            <li>
                              <a href="https://wpassistant.ai/knowledge-base/ecommerce/" className="block px-3 py-2 text-sm dark:text-gray-400 text-gray-500 hover:text-foreground hover:bg-secondary/10 dark:hover:bg-secondary/40 transition-colors duration-0 rounded-lg">Ecommerce</a>
                            </li>
                            <li>
                              <a href="https://wpassistant.ai/knowledge-base/gutenberg_editor/" className="block px-3 py-2 text-sm dark:text-gray-400 text-gray-500 hover:text-foreground hover:bg-secondary/10 dark:hover:bg-secondary/40 transition-colors duration-0 rounded-lg">Gutenberg Editor</a>
                            </li>
                            <li>
                              <a href="https://wpassistant.ai/knowledge-base/hosting/" className="block px-3 py-2 text-sm dark:text-gray-400 text-gray-500 hover:text-foreground hover:bg-secondary/10 dark:hover:bg-secondary/40 transition-colors duration-0 rounded-lg">Hosting</a>
                            </li>
                            <li>
                              <a href="https://wpassistant.ai/knowledge-base/maintenance/" className="block px-3 py-2 text-sm dark:text-gray-400 text-gray-500 hover:text-foreground hover:bg-secondary/10 dark:hover:bg-secondary/40 transition-colors duration-0 rounded-lg">Maintenance</a>
                            </li>
                            <li>
                              <a href="https://wpassistant.ai/knowledge-base/performance/" className="block px-3 py-2 text-sm dark:text-gray-400 text-gray-500 hover:text-foreground hover:bg-secondary/10 dark:hover:bg-secondary/40 transition-colors duration-0 rounded-lg">Performance</a>
                            </li>
                            <li>
                              <a href="https://wpassistant.ai/knowledge-base/plugin_issues/" className="block px-3 py-2 text-sm dark:text-gray-400 text-gray-500 hover:text-foreground hover:bg-secondary/10 dark:hover:bg-secondary/40 transition-colors duration-0 rounded-lg">Plugin Issues</a>
                            </li>
                            <li>
                              <a href="https://wpassistant.ai/knowledge-base/security/" className="block px-3 py-2 text-sm dark:text-gray-400 text-gray-500 hover:text-foreground hover:bg-secondary/10 dark:hover:bg-secondary/40 transition-colors duration-0 rounded-lg">Security</a>
                            </li>
                            <li>
                              <a href="https://wpassistant.ai/knowledge-base/seo_optimization/" className="block px-3 py-2 text-sm dark:text-gray-400 text-gray-500 hover:text-foreground hover:bg-secondary/10 dark:hover:bg-secondary/40 transition-colors duration-0 rounded-lg">SEO Optimization</a>
                            </li>
                            <li>
                              <a href="https://wpassistant.ai/knowledge-base/theme_customization/" className="block px-3 py-2 text-sm dark:text-gray-400 text-gray-500 hover:text-foreground hover:bg-secondary/10 dark:hover:bg-secondary/40 transition-colors duration-0 rounded-lg">Theme Customization</a>
                            </li>
                            <li>
                              <a href="https://wpassistant.ai/knowledge-base/wordpress_setup/" className="block px-3 py-2 text-sm dark:text-gray-400 text-gray-500 hover:text-foreground hover:bg-secondary/10 dark:hover:bg-secondary/40 transition-colors duration-0 rounded-lg">WordPress Setup</a>
                            </li>
                          </ul>
                        </div>
                      </li>
                    </ul>
                  </nav>
                  )}
                  {isLoggedIn && userInfo && (
                    <ProfileLogo 
                      name={userInfo.name} 
                      email={userInfo.email} 
                      onClick={handleSettingsOpen} 
                      showLabel={true} 
                    />
                  )}
                </div>
              </div>
            </div>
            <div 
              className="flex-1 overflow-y-auto w-full scrollbar-custom" 
              id="chat-scroll-container"
              ref={scrollRef}
            >
              <div className="w-full h-full max-w-[825px] mx-auto px-4 pt-4 md:pt-10">
                <ChatArea scrollRef={scrollRef} scrollToBottom={scrollToBottom} scrollToTop={scrollToTop} />
              </div>
            </div>
            <div className="w-full max-w-[825px] mx-auto px-6 mb-2">
              {currentConversationId && (
                <InputSection scrollToBottom={scrollToBottom} />
              )}
              {!IS_WORDPRESS && (
                <div className="relative flex items-center justify-center mb-0">
                  <span className="sm:text-[.8rem] text-[0.7rem] items-center dark:text-gray-400 text-gray-500">
                    Still stuck? Atiba can help. <a href={ATIBA_CONTACT_URL} className="underline">Contact us here.</a>
                  </span>
                </div>
              )}
            </div>
            <Footer />
          </div>
        </div>
      </div>
    </div>
  );
};

export default WPAssistant;
