import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useUrlState } from '../hooks/useUrlState';
import {
  SettingsSidebar,
  USER_SECTIONS,
  LEGACY_SECTION_REDIRECT,
} from '../components/settings/SettingsSidebar';
import { ConfigForm } from '../components/settings/ConfigForm';

interface SettingsPageProps {
  isAdmin: boolean;
}

export function SettingsPage({ isAdmin }: SettingsPageProps) {
  const { t } = useTranslation('settings');
  const { urlState, setUrlState } = useUrlState();
  // admin landing page: first LLM Workers (most-used setting). Non-admin
  // lands on preferences. The pre-Step-3 default was 'provider'.
  const fallbackSection = isAdmin ? 'llm-workers' : 'preferences';
  const rawRequested = urlState.section ?? fallbackSection;
  // Map legacy ids (provider / workspace / tools / browser-settings /
  // search-filter / browser-sessions) into the new sidebar layout.
  const requestedSection = LEGACY_SECTION_REDIRECT[rawRequested] ?? rawRequested;
  const section = (!isAdmin && !USER_SECTIONS.includes(requestedSection))
    ? 'preferences'
    : requestedSection;

  // If the URL still carries a legacy id, rewrite it once so bookmarks
  // and the Back button line up with the new navigation.
  useEffect(() => {
    if (urlState.section && LEGACY_SECTION_REDIRECT[urlState.section]) {
      const target = LEGACY_SECTION_REDIRECT[urlState.section];
      setUrlState(prev => ({ ...prev, section: target as any }));
    }
  }, [urlState.section, setUrlState]);

  // モバイル (< md) では list と detail を切替表示する。URL に section が
  // 明示されていれば detail から、そうでなければ list から開始。
  const [mobileView, setMobileView] = useState<'list' | 'detail'>(
    urlState.section ? 'detail' : 'list',
  );

  // 非 admin が admin section の URL に直アクセスした場合、URL も preferences へ正規化して混乱を避ける。
  useEffect(() => {
    if (!isAdmin && urlState.section && !USER_SECTIONS.includes(urlState.section)) {
      setUrlState(prev => ({ ...prev, section: 'preferences' as any }));
    }
  }, [isAdmin, urlState.section, setUrlState]);

  const handleSelectSection = (s: string) => {
    setUrlState(prev => ({ ...prev, section: s as any }));
    setMobileView('detail');
  };

  return (
    <div className="flex h-full">
      {/* Sidebar: モバイルでは list ビュー時のみ全幅、デスクトップは常に 208px */}
      <div
        className={`${mobileView === 'list' ? 'block' : 'hidden'} md:block w-full md:w-52 flex-shrink-0`}
      >
        <SettingsSidebar
          activeSection={section}
          onSelectSection={handleSelectSection}
          isAdmin={isAdmin}
        />
      </div>

      {/* Detail: モバイルでは detail ビュー時のみ表示。先頭に戻るボタン */}
      <div
        className={`${mobileView === 'detail' ? 'flex' : 'hidden'} md:flex flex-1 flex-col overflow-y-auto`}
      >
        <button
          type="button"
          onClick={() => setMobileView('list')}
          className="md:hidden flex items-center gap-1 px-4 py-2 text-xs text-slate-600 hover:text-slate-900 border-b border-hairline"
        >
          <span aria-hidden>←</span>
          <span>{t('settingsPage.sectionList')}</span>
        </button>
        <div className="flex-1 p-6">
          <ConfigForm section={section} isAdmin={isAdmin} />
        </div>
      </div>
    </div>
  );
}
