import React, { useCallback, useRef } from 'react';
import Sidebar from './Sidebar/Sidebar';
import ChatArea from './ChatArea/ChatArea';
import InputSection from './ChatArea/InputSection';
import DropZoneOverlay from './ChatArea/DropZoneOverlay';
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 ProfileLogo from './Logos/ProfileLogo';
import SettingsModal from './Modals/SettingsModal';
import UpgradeModal from './Modals/UpgradeModal';
import WorkflowsLibraryModal from './Workflows/WorkflowsLibraryModal';
import { useFeatureFlag } from '../featureFlags';
import Footer from './Footer/Footer';
import { useAuth } from '../contexts/AuthContext';
import { useIsMobileSidebarOpen } from '../contexts/UIContext';
import { useCurrentConversationId } from '../contexts/ChatContext';
import useRenderTracker from '../hooks/useRenderTracker';
import MobileSidebar from './Sidebar/MobileSidebar';
import { ALLOW_ACTIONPANEL_AI_REQUESTS, TARGET_ENV, IS_WORDPRESS, SETUP_COMPLETED } from '../constants';
import AssistantDisabledGate from './AssistantDisabledGate';
import InitialSetupGate from './InitialSetupGate';
import { useAppRoute } from '../hooks/useAppRoute';
import { usePluginSettings } from '../contexts/PluginSettingsContext';
import WebNavigationLinks from './Header/WebNavigationLinks';
import { useConversationRouteSync } from '../hooks/useConversationRouteSync';

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 isMobileSidebarOpen = useIsMobileSidebarOpen();
  const currentConversationId = useCurrentConversationId();
  const pluginSettings = usePluginSettings();
  const billingEnabled = useFeatureFlag('billing');
  const workflowsEnabled = useFeatureFlag('workflows') && IS_WORDPRESS;
  const { openSettingsRoute } = useAppRoute();
  const { 
    isLoggedIn, 
    userInfo,
  } = useAuth();
  const setupCompleted = TARGET_ENV === 'wordpress'
    ? pluginSettings.setupCompleted
    : SETUP_COMPLETED;
  const allowActionPanelAiRequests = TARGET_ENV === 'wordpress'
    ? pluginSettings.allowActionPanelAiRequests
    : ALLOW_ACTIONPANEL_AI_REQUESTS;

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

  useConversationRouteSync();

  // Memoized handler
  const handleSettingsOpen = useCallback(() => {
    openSettingsRoute('account');
  }, [openSettingsRoute]);

  const scrollRef = useRef<HTMLDivElement>(null);

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

  // Calculate whether banner is showing

  const openAssistantSettings = useCallback(() => {
    openSettingsRoute('assistant');
  }, [openSettingsRoute]);

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

  if (TARGET_ENV === 'wordpress' && !allowActionPanelAiRequests) {
    return (
      <div className="flex h-full min-h-0 flex-col bg-app-bg text-app-text">
        <MobileHeader />
        <SettingsModal />
        <AssistantDisabledGate onOpenSettings={openAssistantSettings} />
      </div>
    );
  }

  return (
    <div className="flex h-full min-h-0 flex-col overflow-hidden bg-app-bg text-app-text">
      <MobileHeader />
      <LoginModal openSignup={true}/>
      <ConfirmDeleteModal />
      <RateLimitModal />
      <SettingsModal />
      {billingEnabled && <UpgradeModal />}
      {workflowsEnabled && <WorkflowsLibraryModal />}
      <DropZoneOverlay />
      <ProposeChangesModal />
      <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">
            {/* Soft brand wash bleeding from the very top, behind the (transparent)
                header and the scroll content. */}
            <div
              aria-hidden
              className="app-top-glow pointer-events-none absolute inset-x-0 top-0 z-0 h-40"
            />
            {/* Header sits in normal flow (not overlaying the scroll area) so the
                conversation scrollbar starts cleanly below it instead of vanishing
                behind it. It's transparent, so the top glow still shows through. */}
            <div className="relative z-10 hidden h-16 w-full shrink-0 md:block">
              <div className="flex items-center h-full px-4 w-full">
                <div className="absolute right-4 flex items-center">
                  {!IS_WORDPRESS && (
                    <nav className="mr-4">
                      <WebNavigationLinks />
                    </nav>
                  )}
                  {isLoggedIn && userInfo && (
                    <ProfileLogo
                      name={userInfo.name}
                      email={userInfo.email}
                      onClick={handleSettingsOpen}
                      showLabel={true}
                    />
                  )}
                </div>
              </div>
            </div>
            <div className="relative z-10 min-h-0 flex-1">
              <div
                className="h-full 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 ${currentConversationId ? 'pt-4' : ''}`}>
                  <ChatArea scrollRef={scrollRef} scrollToBottom={scrollToBottom} />
                </div>
              </div>
              {currentConversationId && (
                <div
                  aria-hidden
                  className="pointer-events-none absolute inset-x-0 bottom-0 h-8 bg-gradient-to-t from-app-bg to-transparent"
                />
              )}
            </div>
            <div className="relative z-10 w-full max-w-[825px] mx-auto px-6 mb-2">
              {currentConversationId && (
                <InputSection scrollToBottom={scrollToBottom} />
              )}
              {!IS_WORDPRESS && (
                <div className="relative mb-0 flex items-center justify-center">
                  <span className="items-center text-[0.7rem] text-app-muted sm:text-[.8rem]">
                    Still stuck? Atiba can help. <a href={ATIBA_CONTACT_URL} className="font-medium text-brand-text underline">Contact us here.</a>
                  </span>
                </div>
              )}
            </div>
            <Footer />
          </div>
        </div>
      </div>
    </div>
  );
};

export default WPAssistant;
