/**
 * Main admin application.
 *
 * @package RawTypeOE
 */

import { useEffect, useMemo, useRef, useState } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import { applyFilters } from '@wordpress/hooks';
import {
	AdminNav,
	Button,
	Card,
	CardContent,
	CardDescription,
	CardHeader,
	CardTitle,
	Chat,
	Field,
	Label,
	Notice,
	Select,
	Skeleton,
	SkeletonGroup,
	Tabs,
	Toast,
	TooltipProvider,
} from '@rawtype/ui';
import useSettings from './hooks/useSettings';
import ExportPage from './components/ExportPage';
import TemplateLibrary from './components/TemplateLibrary';
import ProfileManager from './components/ProfileManager';
import ProUpgrade from './components/ProUpgrade';

function SettingsSkeleton() {
	return (
		<SkeletonGroup>
			<Skeleton width={ 180 } height={ 20 } />
			<Skeleton width="100%" height={ 44 } />
			<Skeleton width={ 180 } height={ 20 } />
			<Skeleton width="100%" height={ 44 } />
			<Skeleton width={ 180 } height={ 20 } />
			<Skeleton width="100%" height={ 44 } />
			<Skeleton width={ 160 } height={ 44 } />
		</SkeletonGroup>
	);
}

function SettingsTab( {
	draftSettings,
	onDefaultFormatChange,
	onDateFormatChange,
	onSave,
	error,
	loading,
	saving,
} ) {
	if ( loading ) {
		return <SettingsSkeleton />;
	}

	if ( error ) {
		return (
			<Notice type="error">
				{ __( 'Could not load settings.', 'rawtype-order-exporter-woocommerce' ) }
			</Notice>
		);
	}

	return (
		<Card>
			<CardHeader>
				<CardTitle>{ __( 'Settings', 'rawtype-order-exporter-woocommerce' ) }</CardTitle>
				<CardDescription>
					{ __( 'Base exporter configuration.', 'rawtype-order-exporter-woocommerce' ) }
				</CardDescription>
			</CardHeader>
			<CardContent className="rawtype-oe-settings-form">
				<Field>
					<Label htmlFor="rawtype-oe-default-format">
						{ __( 'Default format', 'rawtype-order-exporter-woocommerce' ) }
					</Label>
					<Select.Root
						value={ draftSettings.default_format }
						onValueChange={ onDefaultFormatChange }
					>
						<Select.Trigger
							id="rawtype-oe-default-format"
							placeholder={ __( 'Select format', 'rawtype-order-exporter-woocommerce' ) }
						/>
						<Select.Content>
							<Select.Item value="csv">CSV</Select.Item>
							<Select.Item value="xlsx">XLSX</Select.Item>
						</Select.Content>
					</Select.Root>
				</Field>

				<Field>
					<Label htmlFor="rawtype-oe-date-format">
						{ __( 'Date format', 'rawtype-order-exporter-woocommerce' ) }
					</Label>
					<Select.Root
						value={ draftSettings.date_format }
						onValueChange={ onDateFormatChange }
					>
						<Select.Trigger
							id="rawtype-oe-date-format"
							placeholder={ __( 'Select date format', 'rawtype-order-exporter-woocommerce' ) }
						/>
						<Select.Content>
							<Select.Item value="Y-m-d">Y-m-d</Select.Item>
							<Select.Item value="d/m/Y">d/m/Y</Select.Item>
							<Select.Item value="m/d/Y">m/d/Y</Select.Item>
						</Select.Content>
					</Select.Root>
				</Field>

				<Button type="button" onClick={ onSave } disabled={ saving }>
					{ saving
						? __( 'Saving...', 'rawtype-order-exporter-woocommerce' )
						: __( 'Save settings', 'rawtype-order-exporter-woocommerce' ) }
				</Button>
			</CardContent>
		</Card>
	);
}

export default function App() {
	const { settings, loading, saving, error, saveSettings } = useSettings();
	const [ activeTab, setActiveTab ] = useState(
		() => window.location.hash.slice( 1 ) || 'export',
	);

	// Sync URL hash with active tab so F5 restores the current view.
	useEffect( () => {
		const newHash = '#' + activeTab;
		if ( window.location.hash !== newHash ) {
			history.replaceState( null, '', newHash );
		}
	}, [ activeTab ] );

	const [ draftSettings, setDraftSettings ] = useState( settings );
	const [ toast, setToast ] = useState( { open: false, type: 'success', message: '' } );
	const [ exportState, setExportState ] = useState( null );
	const exportKeyRef = useRef( 0 );
	const pluginVersion = window.rawtypeOEAdmin?.version || '1.0.0';
	const pluginUrl = window.rawtypeOEAdmin?.pluginUrl || '';
	const isPro = window.rawtypeOEAdmin?.isPro;

	useEffect( () => {
		setDraftSettings( settings );
	}, [ settings ] );

	// Navigate to export tab with a pre-loaded config (from template or profile).
	const goToExport = ( nextState ) => {
		exportKeyRef.current += 1;
		setExportState( nextState || null );
		setActiveTab( 'export' );
	};

	const defaultTabs = useMemo(
		() => {
			const tabs = [
				{
					id: 'export',
					label: __( 'Export', 'rawtype-order-exporter-woocommerce' ),
					render: () => (
						<ExportPage
							key={ exportKeyRef.current }
							initialConfig={ exportState?.config || null }
							initialProfile={ exportState?.profile || null }
						/>
					),
				},
				{
					id: 'templates',
					label: __( 'Templates', 'rawtype-order-exporter-woocommerce' ),
					render: () => (
						<TemplateLibrary
							onSelectTemplate={ ( template ) => {
								goToExport( {
									config: {
										entity: template.entity,
										filters: template.filters,
										columns: template.columns,
										format: template.options?.format || 'csv',
										options: template.options,
										initialStep: 3,
									},
								} );
							} }
						/>
					),
				},
				{
					id: 'profiles',
					label: __( 'Profiles', 'rawtype-order-exporter-woocommerce' ),
					render: () => (
						<ProfileManager
							onEditProfile={ ( profile ) => {
								goToExport( {
									config: profile.config,
									profile,
								} );
							} }
							onCreateExport={ () => goToExport( null ) }
						/>
					),
				},
				{
					id: 'settings',
					label: __( 'Settings', 'rawtype-order-exporter-woocommerce' ),
					render: () => (
						<SettingsTab
							draftSettings={ draftSettings }
							onDefaultFormatChange={ ( value ) => {
								setDraftSettings( ( previous ) => ( {
									...previous,
									default_format: value,
								} ) );
							} }
							onDateFormatChange={ ( value ) => {
								setDraftSettings( ( previous ) => ( {
									...previous,
									date_format: value,
								} ) );
							} }
							onSave={ () => {
								saveSettings( draftSettings )
									.then( ( data ) => {
										setDraftSettings( data );
										setToast( {
											open: true,
											type: 'success',
											message: __( 'Settings saved', 'rawtype-order-exporter-woocommerce' ),
										} );
									} )
									.catch( () => {
										setToast( {
											open: true,
											type: 'error',
											message: __( 'Error saving settings', 'rawtype-order-exporter-woocommerce' ),
										} );
									} );
							} }
							error={ error }
							loading={ loading }
							saving={ saving }
						/>
					),
				},
			];

			if ( ! isPro ) {
				tabs.push( {
					id: 'pro',
					label: __( 'Pro', 'rawtype-order-exporter-woocommerce' ),
					render: () => <ProUpgrade />,
				} );
			}

			tabs.push( {
				id: 'support',
				label: __( 'Support', 'rawtype-order-exporter-woocommerce' ),
				render: () => (
					<Chat
						disabled={ ! isPro }
						disabledTitle={ __( 'Priority support', 'rawtype-order-exporter-woocommerce' ) }
						disabledDescription={ __( 'Upgrade to Pro to access direct support chat with our technical team.', 'rawtype-order-exporter-woocommerce' ) }
						disabledAction={
							<Button variant="primary" onClick={ () => setActiveTab( 'pro' ) }>
								{ __( 'Get Pro', 'rawtype-order-exporter-woocommerce' ) }
							</Button>
						}
						placeholder={ __( 'Type your message...', 'rawtype-order-exporter-woocommerce' ) }
						emptyTitle={ __( 'Support', 'rawtype-order-exporter-woocommerce' ) }
						emptyDescription={ __( 'Send a message to start a conversation with our team.', 'rawtype-order-exporter-woocommerce' ) }
						messages={ ! isPro ? [
							{ id: 1, role: 'agent', content: __( 'Hello! Welcome to WooExport support. How can I help you?', 'rawtype-order-exporter-woocommerce' ) },
							{ id: 2, role: 'user', content: __( 'I need help with product export.', 'rawtype-order-exporter-woocommerce' ) },
							{ id: 3, role: 'agent', content: __( 'Sure, tell me about your issue and I will help you resolve it.', 'rawtype-order-exporter-woocommerce' ) },
						] : [] }
					/>
				),
			} );

			return tabs;
		},
		[ draftSettings, error, exportState, isPro, loading, saveSettings, saving ],
	);

	const filteredTabs = applyFilters( 'rawtype_oe_admin_tabs', defaultTabs );
	const tabs = Array.isArray( filteredTabs ) && filteredTabs.length ? filteredTabs : defaultTabs;

	return (
		<TooltipProvider>
		<Toast.Provider swipeDirection="right">
			<div className="rawtype-oe-admin-wrap">
				<AdminNav
					pluginName={ __( 'Export Excel', 'rawtype-order-exporter-woocommerce' ) }
					version={ pluginVersion }
				/>

				<Tabs.Root value={ activeTab } onValueChange={ setActiveTab }>
					<Tabs.List>
						{ tabs.map( ( tab ) => (
							<Tabs.Trigger key={ tab.id } value={ tab.id }>
								{ tab.label }
							</Tabs.Trigger>
						) ) }
					</Tabs.List>

					{ tabs.map( ( tab ) => (
						<Tabs.Content
							key={ tab.id }
							value={ tab.id }
							{ ...( tab.id === 'export' ? { forceMount: true } : {} ) }
						>
							{ tab.render() }
						</Tabs.Content>
					) ) }
				</Tabs.Root>
			</div>

			<Toast.Notification
				open={ toast.open }
				onOpenChange={ ( isOpen ) => {
					setToast( ( previous ) => ( {
						...previous,
						open: isOpen,
					} ) );
				} }
				type={ toast.type }
				message={ toast.message }
			/>
			<Toast.Viewport />
		</Toast.Provider>
		</TooltipProvider>
	);
}
