import { useState, useEffect, useRef } from 'react';
import { Header } from './Header';
import { OverviewTab } from './OverviewTab';
import { SubscribersTab } from './SubscribersTab';
import { ActivityLogTab } from './ActivityLogTab';
import { DebugToolsTab } from './DebugToolsTab';
import { FormEditorTab } from './FormEditorTab';
import { EmailEditorTab } from './EmailEditorTab';

import type { AdminData } from '../types';

type TabId = 'overview' | 'subscribers' | 'activity' | 'debug' | 'form-editor' | 'email-editor' | 'settings';
const TAB_STORAGE_KEY = 'stockbeacon-active-tab';
const TAB_IDS: TabId[] = ['overview', 'subscribers', 'activity', 'debug', 'form-editor', 'email-editor', 'settings'];

function isTabId(value: string | null | undefined): value is TabId {
	return !!value && TAB_IDS.includes(value as TabId);
}

function readInitialTab(isPremium: boolean): TabId {
	const hash = window.location.hash.replace(/^#/, '');
	const stored = window.localStorage?.getItem(TAB_STORAGE_KEY);
	const candidate = isTabId(hash) ? hash : (isTabId(stored) ? stored : 'overview');
	return candidate === 'settings' && !isPremium ? 'overview' : candidate;
}

export function App() {
	const adminData: Partial<AdminData> = window.stockbeaconAdmin ?? {};
	const isPremium = !!adminData.isPremium;
	const [activeTab, setActiveTab] = useState<TabId>(() => readInitialTab(isPremium));

	// Collect WP admin notices injected into the root into a notice host
	const noticesRef = useRef<HTMLDivElement>(null);
	const rootRef = useRef<HTMLDivElement>(null);

	const changeTab = (tab: TabId) => {
		setActiveTab(tab);
		window.localStorage?.setItem(TAB_STORAGE_KEY, tab);
		if (window.location.hash.replace(/^#/, '') !== tab) {
			window.history.replaceState(null, '', `${window.location.pathname}${window.location.search}#${tab}`);
		}
	};

	useEffect(() => {
		const onHashChange = () => {
			const hashTab = window.location.hash.replace(/^#/, '');
			if (!isTabId(hashTab) || (hashTab === 'settings' && !isPremium)) return;
			setActiveTab(hashTab);
			window.localStorage?.setItem(TAB_STORAGE_KEY, hashTab);
		};
		onHashChange();
		window.addEventListener('hashchange', onHashChange);
		return () => window.removeEventListener('hashchange', onHashChange);
	}, [isPremium]);

	useEffect(() => {
		const noticesEl = noticesRef.current;
		const rootEl = rootRef.current;
		if (!noticesEl || !rootEl) return;
		const collect = () => {
			rootEl.querySelectorAll<HTMLElement>('.notice, .updated, .error, .fs-notice').forEach((node) => {
				if (node.closest('#stockbeacon-admin-notices')) return;
				noticesEl.appendChild(node);
			});
		};
		collect();
		const observer = new MutationObserver(collect);
		observer.observe(rootEl, { childList: true, subtree: true });
		return () => observer.disconnect();
	}, []);

	const header = (
		<Header
			activeTab={activeTab}
			onTabChange={(tab) => changeTab(tab as TabId)}
			isPremium={isPremium}
		/>
	);

	

	return (
		<div className="stockbeacon-admin-root" ref={rootRef}>
			<div id="stockbeacon-admin-notices" className="stockbeacon-admin-notices" aria-live="polite" ref={noticesRef} />
			{header}
			<div className="stockbeacon-content">
				<div style={{ display: activeTab === 'overview' ? 'block' : 'none' }}>
					<OverviewTab />
				</div>
				<div style={{ display: activeTab === 'subscribers' ? 'block' : 'none' }}>
					{activeTab === 'subscribers' && <SubscribersTab />}
				</div>
				<div style={{ display: activeTab === 'activity' ? 'block' : 'none' }}>
					{activeTab === 'activity' && <ActivityLogTab />}
				</div>
				<div style={{ display: activeTab === 'debug' ? 'block' : 'none' }}>
					{activeTab === 'debug' && <DebugToolsTab />}
				</div>
				<div style={{ display: activeTab === 'form-editor' ? 'block' : 'none' }}>
					{activeTab === 'form-editor' && <FormEditorTab />}
				</div>
				<div style={{ display: activeTab === 'email-editor' ? 'block' : 'none' }}>
					{activeTab === 'email-editor' && <EmailEditorTab />}
				</div>
			</div>
		</div>
	);
}
