import { render, useReducer, useState, useCallback } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import {
	Truck, BookOpen, Save, Check,
	Settings2, LayoutPanelTop, Globe, CalendarOff, SlidersHorizontal,
} from 'lucide-react';
import './admin.css';
import { reducer, getInitialState } from './store';
import { getTabs, notifySaved } from './hooks';
import { saveSettings } from './api';
import LivePreview from './components/LivePreview';
import GeneralTab from './tabs/GeneralTab';
import DisplayTab from './tabs/DisplayTab';
import RulesTab from './tabs/RulesTab';
import HolidaysTab from './tabs/HolidaysTab';
import AdvancedTab from './tabs/AdvancedTab';

const TAB_COMPONENTS = {
	general: GeneralTab,
	display: DisplayTab,
	rules: RulesTab,
	holidays: HolidaysTab,
	advanced: AdvancedTab,
};

const TAB_ICONS = {
	general: Settings2,
	display: LayoutPanelTop,
	rules: Globe,
	holidays: CalendarOff,
	advanced: SlidersHorizontal,
};

function App() {
	const [ state, dispatch ] = useReducer( reducer, undefined, getInitialState );
	const [ active, setActive ] = useState( 'general' );
	const [ status, setStatus ] = useState( 'idle' );

	// The chosen accent themes the STOREFRONT (and its live preview) only.
	// The admin chrome stays a stable WooCommerce purple.
	const storeAccent = state.settings.accent_color || '#7f54b3';
	const BRAND = '#7f54b3';
	const BRAND_DARK = '#6a4595';

	const tabs = getTabs( [
		{ name: 'general', title: __( 'General', 'wpactpro-estimated-delivery-date' ) },
		{ name: 'display', title: __( 'Display', 'wpactpro-estimated-delivery-date' ) },
		{ name: 'rules', title: __( 'Delivery Rules', 'wpactpro-estimated-delivery-date' ) },
		{ name: 'holidays', title: __( 'Holidays', 'wpactpro-estimated-delivery-date' ) },
		{ name: 'advanced', title: __( 'Advanced', 'wpactpro-estimated-delivery-date' ) },
	] );

	const onSave = useCallback( async () => {
		setStatus( 'saving' );
		try {
			const res = await saveSettings( state.settings, state.rules );
			dispatch( { type: 'HYDRATE', settings: res.settings, rules: res.rules, schema: res.schema } );
			notifySaved( state );
			setStatus( 'saved' );
			setTimeout( () => setStatus( 'idle' ), 2500 );
		} catch ( e ) {
			setStatus( 'error' );
		}
	}, [ state ] );

	const Comp = TAB_COMPONENTS[ active ];
	const rootStyle = { '--edfw-accent': BRAND, '--edfw-accent-dark': BRAND_DARK };

	return (
		<div className="edfw-app" style={ rootStyle }>
			<div className="edfw-header">
				<div className="edfw-logo"><Truck size={ 24 } /></div>
				<div className="edfw-htext">
					<div className="edfw-title-row">
						<h1>{ __( 'Estimated Delivery Date for WooCommerce', 'wpactpro-estimated-delivery-date' ) }</h1>
						<span className="edfw-badge-ver">v{ window.edfwData?.version || '1.0.0' }</span>
					</div>
					<div className="edfw-subtitle">
						{ __( 'Show shoppers exactly when their order will arrive — on the product, cart & checkout pages.', 'wpactpro-estimated-delivery-date' ) }
					</div>
				</div>
				<div className="edfw-header-actions">
					{ status === 'error' && (
						<span className="edfw-save-status">{ __( 'Couldn’t save — try again.', 'wpactpro-estimated-delivery-date' ) }</span>
					) }
					<a className="edfw-doc-link" href="https://wpactpro.com/" target="_blank" rel="noreferrer">
						<BookOpen size={ 16 } />{ __( 'Documentation', 'wpactpro-estimated-delivery-date' ) }
					</a>
					<button
						className={ `edfw-save-btn ${ status === 'saved' ? 'is-saved' : '' }` }
						disabled={ ! state.dirty || status === 'saving' }
						onClick={ onSave }
					>
						{ status === 'saved' ? <Check size={ 16 } /> : <Save size={ 16 } /> }
						<span>
							{ status === 'saving'
								? __( 'Saving…', 'wpactpro-estimated-delivery-date' )
								: status === 'saved'
									? __( 'Saved', 'wpactpro-estimated-delivery-date' )
									: __( 'Save changes', 'wpactpro-estimated-delivery-date' ) }
						</span>
					</button>
				</div>
			</div>

			<div className="edfw-tabs">
				{ tabs.map( ( t ) => {
					const Icon = TAB_ICONS[ t.name ] || Settings2;
					return (
						<button
							key={ t.name }
							className={ `edfw-tab ${ active === t.name ? 'is-active' : '' }` }
							onClick={ () => setActive( t.name ) }
						>
							<Icon size={ 16 } />{ t.title }
						</button>
					);
				} ) }
			</div>

			<div className="edfw-grid">
				<div className="edfw-col">
					{ Comp && <Comp state={ state } dispatch={ dispatch } accent={ BRAND } /> }
				</div>
				<div className="edfw-side">
					<LivePreview state={ state } accent={ storeAccent } />
				</div>
			</div>
		</div>
	);
}

const root = document.getElementById( 'edfw-admin-app' );
if ( root ) {
	render( <App />, root );
}
