import { useEffect, useMemo, useState } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';
import { useAnalyticsSettings, setIn } from '../SettingsStore';
import { Advanced, Button, Card, NumberInput, PageHeader, SettingRow, SettingsLayout, Select, SwitchRow, TextInput } from '../controls';
import SheetPreview from '../preview/SheetPreview';
import { removeAiKey, saveAiKey } from '../../api';
import { fetchAiUsage, testAiConnection } from '../../api_ai';
import { Icon } from '../icons';
import { HOURS } from './shared';

const TEXT_DOMAIN = 'stock-sync-with-google-sheet-for-woocommerce';
const OTHER_MODEL = '__other__';

export default function AiAssistant() {
	const { v, set, draft, meta, setMeta, dirty, notices } = useAnalyticsSettings();
	const [ keyInput, setKeyInput ] = useState( '' );
	const [ keyBusy, setKeyBusy ] = useState( false );
	const [ replacingKey, setReplacingKey ] = useState( false );
	const [ customModel, setCustomModel ] = useState( false );
	const [ aiTesting, setAiTesting ] = useState( false );
	const [ aiUsage, setAiUsage ] = useState( null );
	const { setDraftRaw } = useAnalyticsSettings();

	useEffect( () => {
		fetchAiUsage().then( ( data ) => setAiUsage( data.usage ) ).catch( () => setAiUsage( null ) );
	}, [] );

	const provider = useMemo( () => meta.providers.find( ( p ) => p.value === draft.ai.provider ) || null, [ meta, draft ] );

	useEffect( () => {
		// Show the free-text box when the saved model is not one of the suggestions.
		if ( provider ) {
			setCustomModel( provider.models.length === 0 || ( !! draft.ai.model && ! provider.models.includes( draft.ai.model ) ) );
		}
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [ provider && provider.value ] );

	const onProviderChange = ( value ) => {
		const next = meta.providers.find( ( p ) => p.value === value );
		setDraftRaw( ( previous ) => setIn( setIn( previous, 'ai.provider', value ), 'ai.model', next ? next.default_model : '' ) );
		setCustomModel( !! next && next.models.length === 0 );
	};

	const onModelSelect = ( value ) => {
		if ( value === OTHER_MODEL ) {
			setCustomModel( true );
			set( 'ai.model' )( '' );
			return;
		}
		setCustomModel( false );
		set( 'ai.model' )( value );
	};

	const submitKey = async () => {
		if ( ! keyInput.trim() ) {
			return;
		}
		setKeyBusy( true );
		try {
			const data = await saveAiKey( keyInput.trim() );
			setMeta( ( previous ) => ( { ...previous, ai_key: data.ai_key } ) );
			setKeyInput( '' );
			setReplacingKey( false );
			notices.success( __( 'Key saved', TEXT_DOMAIN ), __( 'It is stored encrypted in WordPress and never sent to your sheet.', TEXT_DOMAIN ) );
		} catch ( error ) {
			notices.error( __( 'Key not saved', TEXT_DOMAIN ), error.message );
		} finally {
			setKeyBusy( false );
		}
	};

	const deleteKey = async () => {
		// eslint-disable-next-line no-alert
		if ( ! window.confirm( __( 'Remove the saved key? The AI assistant stops until you add a key again.', TEXT_DOMAIN ) ) ) {
			return;
		}
		setKeyBusy( true );
		try {
			const data = await removeAiKey();
			setMeta( ( previous ) => ( { ...previous, ai_key: data.ai_key } ) );
			notices.success( __( 'Key removed', TEXT_DOMAIN ) );
		} catch ( error ) {
			notices.error( __( 'Key not removed', TEXT_DOMAIN ), error.message );
		} finally {
			setKeyBusy( false );
		}
	};

	const runAiTest = async () => {
		setAiTesting( true );
		try {
			const data = await testAiConnection();
			if ( data.usage ) {
				setAiUsage( data.usage );
			}
			notices.success( __( 'The AI assistant works', TEXT_DOMAIN ), sprintf( /* translators: 1: provider, 2: model */ __( '%1$s answered using %2$s.', TEXT_DOMAIN ), data.provider, data.model ) );
		} catch ( error ) {
			notices.error( __( 'The AI assistant did not answer', TEXT_DOMAIN ), error.message );
		} finally {
			setAiTesting( false );
		}
	};

	const modelOptions = provider ? [ ...provider.models.map( ( m ) => ( { value: m, label: m } ) ), { value: OTHER_MODEL, label: __( 'Another model…', TEXT_DOMAIN ) } ] : [];

	return (
		<SettingsLayout preview={ <SheetPreview page="ai" usage={ aiUsage } /> }>
			<PageHeader
				title={ __( 'AI assistant', TEXT_DOMAIN ) }
				description={ __( 'Ask about your sales in plain words. You bring your own AI account.', TEXT_DOMAIN ) }
			/>
			<Card title={ __( 'Connect your AI account', TEXT_DOMAIN ) } description={ __( 'Your key is stored encrypted and never reaches your sheet.', TEXT_DOMAIN ) }>
				<SettingRow id="ai.provider" label={ __( 'AI company', TEXT_DOMAIN ) } help={ __( 'Choose “No AI” to keep the assistant off.', TEXT_DOMAIN ) }>
					<Select id="ai.provider" value={ v( 'ai.provider' ) } onChange={ onProviderChange } options={ [ { value: '', label: __( 'No AI (off)', TEXT_DOMAIN ) }, ...meta.providers.map( ( p ) => ( { value: p.value, label: p.label } ) ) ] } />
				</SettingRow>
				{ provider && (
					<SettingRow id="ai.model" label={ __( 'AI model', TEXT_DOMAIN ) } help={ customModel ? __( 'Type the exact model name from your AI company.', TEXT_DOMAIN ) : __( 'The default works for most stores.', TEXT_DOMAIN ) }>
						<div className="ssgsw-ui-stack">
							{ provider.models.length > 0 && <Select id="ai.model" value={ customModel ? OTHER_MODEL : v( 'ai.model' ) } onChange={ onModelSelect } options={ modelOptions } /> }
							{ customModel && <TextInput id={ provider.models.length > 0 ? 'ssgsw-an-model-custom' : 'ai.model' } value={ v( 'ai.model' ) } placeholder={ __( 'e.g. llama-3.1-70b', TEXT_DOMAIN ) } onChange={ set( 'ai.model' ) } /> }
						</div>
					</SettingRow>
				) }
				{ provider && provider.needs_base && (
					<SettingRow id="ai.base_url" label={ __( 'Service web address', TEXT_DOMAIN ) } help={ __( 'An OpenAI-compatible address, e.g. https://api.groq.com/openai/v1', TEXT_DOMAIN ) }>
						<TextInput id="ai.base_url" type="url" value={ v( 'ai.base_url' ) } onChange={ set( 'ai.base_url' ) } />
					</SettingRow>
				) }
				{ provider && (
					<SettingRow id="ai.key" label={ __( 'Your AI key', TEXT_DOMAIN ) } help={ __( 'Paste the key from your AI account.', TEXT_DOMAIN ) } stacked htmlFor="ssgsw-an-key">
						{ meta.ai_key.set && ! replacingKey ? (
							<div className="ssgsw-ui-keyrow">
								<span className="ssgsw-ui-keysaved">
									<Icon name="lock" size={ 14 } />
									{ meta.ai_key.last4 ? sprintf( /* translators: %s: last four characters of the key */ __( 'Key saved (ends in %s)', TEXT_DOMAIN ), meta.ai_key.last4 ) : __( 'Key saved', TEXT_DOMAIN ) }
								</span>
								<Button onClick={ () => setReplacingKey( true ) } disabled={ keyBusy }>{ __( 'Replace key', TEXT_DOMAIN ) }</Button>
								<Button variant="danger" onClick={ deleteKey } disabled={ keyBusy }>{ __( 'Remove', TEXT_DOMAIN ) }</Button>
							</div>
						) : (
							<div className="ssgsw-ui-keyrow">
								<input id="ssgsw-an-key" type="password" autoComplete="off" className="ssgsw-ui-input" aria-label={ __( 'Your AI key', TEXT_DOMAIN ) } placeholder={ __( 'Paste your key', TEXT_DOMAIN ) } value={ keyInput } onChange={ ( e ) => setKeyInput( e.target.value ) } />
								<Button variant="primary" onClick={ submitKey } disabled={ keyBusy || ! keyInput.trim() }>{ keyBusy ? __( 'Saving…', TEXT_DOMAIN ) : __( 'Save key', TEXT_DOMAIN ) }</Button>
								{ replacingKey && <Button onClick={ () => { setReplacingKey( false ); setKeyInput( '' ); } }>{ __( 'Cancel', TEXT_DOMAIN ) }</Button> }
							</div>
						) }
						{ provider.key_url && (
							<p className="ssgsw-ui-keylink">
								<a href={ provider.key_url } target="_blank" rel="noreferrer" className="ssgsw-ui-link">
									{ sprintf( /* translators: %s: provider name */ __( 'Get a key from %s', TEXT_DOMAIN ), provider.label ) }
								</a>
							</p>
						) }
					</SettingRow>
				) }
				{ provider && (
					<div className="ssgsw-ui-testrow" id="ssgsw-row-ai.test">
						<Button onClick={ runAiTest } disabled={ aiTesting || dirty || ! meta.ai_key.set }>{ aiTesting ? __( 'Testing…', TEXT_DOMAIN ) : __( 'Test the connection', TEXT_DOMAIN ) }</Button>
						{ dirty && <span className="ssgsw-ui-muted">{ __( 'Save your changes first. The test uses your saved settings.', TEXT_DOMAIN ) }</span> }
						{ ! dirty && ! meta.ai_key.set && <span className="ssgsw-ui-muted">{ __( 'Save a key to test the connection.', TEXT_DOMAIN ) }</span> }
						{ aiUsage && (
							<span className="ssgsw-ui-muted">
								{ sprintf(
									/* translators: 1: requests today, 2: daily limit, 3: estimated month cost */
									__( '%1$s of %2$s questions used today · about $%3$s this month', TEXT_DOMAIN ),
									Number( aiUsage.used_today ).toLocaleString(),
									Number( aiUsage.daily_limit ).toLocaleString(),
									Number( aiUsage.month_cost ).toLocaleString( undefined, { maximumFractionDigits: 2 } )
								) }
							</span>
						) }
					</div>
				) }
			</Card>

			{ provider && (
				<Card title={ __( 'Limits and privacy', TEXT_DOMAIN ) }>
					<SwitchRow id="ai.send_product_names" label={ __( 'Share product names with the AI', TEXT_DOMAIN ) } help={ __( 'Off = only product codes (SKUs) and totals leave your site. Customer data is never sent.', TEXT_DOMAIN ) } checked={ v( 'ai.send_product_names' ) } onChange={ set( 'ai.send_product_names' ) } />
					<SettingRow id="ai.daily_limit" label={ __( 'Questions allowed per day', TEXT_DOMAIN ) } help={ __( 'For the whole site. 0 = the assistant cannot be used.', TEXT_DOMAIN ) }>
						<NumberInput id="ai.daily_limit" value={ v( 'ai.daily_limit' ) } onChange={ set( 'ai.daily_limit' ) } min={ 0 } />
					</SettingRow>
					<SettingRow id="ai.monthly_budget" label={ __( 'Monthly AI spending limit', TEXT_DOMAIN ) } help={ __( 'Stops for the month at this cost. 0 = no limit.', TEXT_DOMAIN ) }>
						<NumberInput id="ai.monthly_budget" value={ v( 'ai.monthly_budget' ) } onChange={ set( 'ai.monthly_budget' ) } min={ 0 } step={ 0.5 } suffix="USD" />
					</SettingRow>
					<SwitchRow id="ai.paused" label={ __( 'Pause the AI assistant', TEXT_DOMAIN ) } help={ __( 'Stops all questions; keeps your key and settings.', TEXT_DOMAIN ) } checked={ v( 'ai.paused' ) } onChange={ set( 'ai.paused' ) } />
					<Advanced>
						<SettingRow id="ai.max_tokens" label={ __( 'Answer length', TEXT_DOMAIN ) } help={ __( 'Longer answers cost more. 100 to 32,000 (roughly 4 characters each).', TEXT_DOMAIN ) }>
							<NumberInput id="ai.max_tokens" value={ v( 'ai.max_tokens' ) } onChange={ set( 'ai.max_tokens' ) } min={ 100 } max={ 32000 } step={ 100 } />
						</SettingRow>
					</Advanced>
				</Card>
			) }

			<Card title={ __( 'Daily email summary', TEXT_DOMAIN ) } description={ __( 'Yesterday’s sales and stock alerts each morning.', TEXT_DOMAIN ) }>
				<SwitchRow id="email.enabled" label={ __( 'Send me a daily email summary', TEXT_DOMAIN ) } checked={ v( 'email.enabled' ) } onChange={ set( 'email.enabled' ) } />
				{ v( 'email.enabled' ) && (
					<>
						<SettingRow id="email.recipients" label={ __( 'Send it to', TEXT_DOMAIN ) } help={ __( 'Separate email addresses with commas.', TEXT_DOMAIN ) }>
							<TextInput id="email.recipients" value={ v( 'email.recipients' ) } onChange={ set( 'email.recipients' ) } />
						</SettingRow>
						<SettingRow id="email.hour" label={ __( 'Send it at', TEXT_DOMAIN ) } help={ __( 'Uses your store time.', TEXT_DOMAIN ) }>
							<Select id="email.hour" value={ v( 'email.hour' ) } onChange={ ( value ) => set( 'email.hour' )( Number( value ) ) } options={ HOURS } />
						</SettingRow>
					</>
				) }
			</Card>
		</SettingsLayout>
	);
}
