import { useEffect, useMemo, useState } from 'react';
import { useIsSettingsModalOpen, useSetIsSettingsModalOpen } from '../../contexts/UIContext';
import { useAuth } from '../../contexts/AuthContext';
import { IS_WORDPRESS } from '../../constants';
import { useAppRoute } from '../../hooks/useAppRoute';
import { SettingsSection } from '../../utils/appRoute';
import { ModalShell, StatusBadge } from '../ui';
import { useCurrentConversationId } from '../../contexts/ChatContext';
import AccountSettingsSection from './settings/AccountSettingsSection';
import AppearanceSettingsSection from './settings/AppearanceSettingsSection';
import AssistantSettingsSection from './settings/AssistantSettingsSection';
import BillingSettingsSection from './settings/BillingSettingsSection';
import SettingsSectionNav from './settings/SettingsSectionNav';
import {
  SECTION_BLURBS,
  SECTION_LABELS,
  visibleSettingsSections,
} from './settings/settingsConfig';
import type { SettingsMessage } from './settings/types';

export default function SettingsModal() {
  const isSettingsModalOpen = useIsSettingsModalOpen();
  const setIsSettingsModalOpen = useSetIsSettingsModalOpen();
  const { route, openSettingsRoute, setRoute } = useAppRoute();
  const requestedSection = route.name === 'settings' ? route.section : 'account';
  const currentConversationId = useCurrentConversationId();
  const { isLoggedIn } = useAuth();
  const [message, setMessage] = useState<SettingsMessage | null>(null);

  const sections = useMemo(() => visibleSettingsSections(isLoggedIn), [isLoggedIn]);
  const activeSection: SettingsSection = sections.includes(requestedSection)
    ? requestedSection
    : (sections[0] ?? 'appearance');

  useEffect(() => {
    if (!isSettingsModalOpen) {
      setMessage(null);
    }
  }, [isSettingsModalOpen]);

  const close = () => {
    setIsSettingsModalOpen(false);
    setRoute(
      currentConversationId
        ? { name: 'conversation', conversationId: currentConversationId }
        : { name: 'home' },
    );
  };

  const renderSection = () => {
    if (activeSection === 'appearance') return <AppearanceSettingsSection />;
    if (activeSection === 'assistant' && IS_WORDPRESS) return <AssistantSettingsSection />;
    if (activeSection === 'billing') return <BillingSettingsSection />;
    return (
      <AccountSettingsSection
        isOpen={isSettingsModalOpen}
        onMessageChange={setMessage}
      />
    );
  };

  return (
    <ModalShell
      open={isSettingsModalOpen}
      title="Settings"
      maxWidthClass="max-w-3xl"
      onClose={close}
    >
      <div className="flex flex-col gap-5 sm:min-h-[440px] sm:flex-row sm:gap-6">
        <SettingsSectionNav
          sections={sections}
          activeSection={activeSection}
          onSelect={openSettingsRoute}
        />

        <div className="min-w-0 flex-1 space-y-4">
          <div className="hidden sm:block">
            <h3 className="text-base font-semibold text-app-text">{SECTION_LABELS[activeSection]}</h3>
            <p className="mt-0.5 text-sm text-app-muted">{SECTION_BLURBS[activeSection]}</p>
          </div>
          <div aria-live="polite">
            {message && <StatusBadge tone={message.tone}>{message.text}</StatusBadge>}
          </div>
          {renderSection()}
        </div>
      </div>
    </ModalShell>
  );
}
