import { TabPanel, Spinner } from '@wordpress/components';
import { __ } from '@wordpress/i18n';
import { useSettings } from './hooks/useSettings';
import GeneralTab from './tabs/GeneralTab';
import HeaderTab from './tabs/HeaderTab';
import ButtonsTab from './tabs/ButtonsTab';
import DesignTab from './tabs/DesignTab';
import AdvancedTab from './tabs/AdvancedTab';
import PreviewFrame from './components/PreviewFrame';
import SaveBar from './components/SaveBar';

const TABS = [
	{ name: 'general', title: 'General', Component: GeneralTab },
	{ name: 'header', title: 'Header', Component: HeaderTab },
	{ name: 'buttons', title: 'Buttons', Component: ButtonsTab },
	{ name: 'design', title: 'Design', Component: DesignTab },
	{ name: 'advanced', title: 'Advanced', Component: AdvancedTab },
];

export default function App() {
	const boot = window.wuppiSettingsBoot || {};

	const {
		settings,
		updateField,
		isLoading,
		isSaving,
		isDirty,
		isResetting,
		save,
		discard,
		resetToDefaults,
		notice,
		dismissNotice,
	} = useSettings();

	if ( isLoading ) {
		return (
			<div className="wuppi-settings-loading-state">
				<Spinner />
				<span>{ __( 'Loading settings…', 'wuppi' ) }</span>
			</div>
		);
	}

	const tabPanelTabs = TABS.map( ( t ) => ( {
		name: t.name,
		title: t.title,
		className: `wuppi-tab wuppi-tab-${ t.name }`,
	} ) );

	return (
		<div className="wuppi-settings-layout">
			<div className="wuppi-settings-controls">
				<TabPanel
					tabs={ tabPanelTabs }
					activeClass="is-active"
					onSelect={ () => {} }
				>
					{ ( tab ) => {
						const def = TABS.find( ( t ) => t.name === tab.name );
						if ( ! def ) {
							return null;
						}
						const Component = def.Component;
						return (
							<div className="wuppi-tab-panel">
								<Component settings={ settings } updateField={ updateField } />
							</div>
						);
					} }
				</TabPanel>
				<SaveBar
					isDirty={ isDirty }
					isSaving={ isSaving }
					isResetting={ isResetting }
					onSave={ save }
					onDiscard={ discard }
					onReset={ resetToDefaults }
					notice={ notice }
				/>
			</div>
			<div className="wuppi-settings-preview">
				{ boot.homeUrl ? (
					<PreviewFrame
						settings={ settings }
						homeUrl={ boot.homeUrl }
						previewOrigin={ boot.previewOrigin }
					/>
				) : (
					<p>{ __( 'Preview unavailable.', 'wuppi' ) }</p>
				) }
			</div>
		</div>
	);
}
