import { useState } from '@wordpress/element';
import {
	Button,
	Card,
	CardBody,
	CardHeader,
	TextControl,
	ToggleControl,
} from '@wordpress/components';
import apiFetch from '@wordpress/api-fetch';

export default function Settings( { navigate } ) {
	const initial = window.wlconduitData?.settings || {};
	const [ settings, setSettings ] = useState( {
		cache_expiry_terms: initial.cache_expiry_terms || 30,
		cache_expiry_meta_keys: initial.cache_expiry_meta_keys || 30,
		log_retention_days: initial.log_retention_days || 30,
		logging_enabled: initial.logging_enabled !== false,
		rate_limiting_enabled: initial.rate_limiting_enabled !== false,
		rate_limit: initial.rate_limit || 20,
		rate_block_duration: initial.rate_block_duration || 60,
	} );
	const [ saving, setSaving ] = useState( false );
	const [ saved, setSaved ] = useState( false );

	function setNumeric( key, val ) {
		setSettings( { ...settings, [ key ]: val } );
	}

	async function handleSave() {
		setSaving( true );
		setSaved( false );
		try {
			// Parse numeric fields before sending — allows empty string while typing.
			const toInt = ( val, fallback ) => {
				const n = parseInt( val, 10 );
				return isNaN( n ) ? fallback : n;
			};
			const payload = {
				...settings,
				cache_expiry_terms: toInt( settings.cache_expiry_terms, 30 ),
				cache_expiry_meta_keys: toInt( settings.cache_expiry_meta_keys, 30 ),
				log_retention_days: toInt( settings.log_retention_days, 30 ),
				rate_limit: toInt( settings.rate_limit, 20 ),
				rate_block_duration: toInt( settings.rate_block_duration, 60 ),
			};
			const result = await apiFetch( {
				path: 'wlconduit/v1/settings',
				method: 'POST',
				data: payload,
			} );
			setSettings( result );
			setSaved( true );
			setTimeout( () => setSaved( false ), 3000 );
		} catch ( err ) {
			window.alert( 'Failed to save settings.' );
		}
		setSaving( false );
	}

	return (
		<div className="aic-settings">
			<div className="aic-header">
				<Button variant="tertiary" onClick={ () => navigate( '/' ) }>
					&larr; Back to Tools
				</Button>
				<h1>AI Conduit - Settings</h1>
			</div>

			<Card className="aic-settings-card">
				<CardHeader>
					<h3>Cache Settings</h3>
				</CardHeader>
				<CardBody>
					<TextControl
						label="Taxonomy terms cache (days)"
						help="How long to cache the list of taxonomy terms before querying the database again. This helps keep the builder fast on sites with many terms."
						type="number"
						min="1"
						max="30"
						value={ settings.cache_expiry_terms }
						onChange={ ( val ) => setNumeric( 'cache_expiry_terms', val ) }
					/>
					<TextControl
						label="Meta keys cache (days)"
						help="How long to cache the list of custom field keys. On sites with thousands of custom fields, caching avoids slow database lookups every time you open the builder."
						type="number"
						min="1"
						max="30"
						value={ settings.cache_expiry_meta_keys }
						onChange={ ( val ) => setNumeric( 'cache_expiry_meta_keys', val ) }
					/>
				</CardBody>
			</Card>

			<Card className="aic-settings-card">
				<CardHeader>
					<h3>Logging</h3>
				</CardHeader>
				<CardBody>
					<ToggleControl
						label="Enable request logging"
						help="When enabled, every MCP request and response is saved to the database. Useful for debugging and auditing which AI clients are accessing your data."
						checked={ settings.logging_enabled }
						onChange={ ( val ) => setSettings( { ...settings, logging_enabled: val } ) }
					/>
					<TextControl
						label="Log retention (days)"
						help="Logs older than this are automatically deleted daily. Set to 0 to keep logs forever (not recommended on busy sites)."
						type="number"
						min="0"
						value={ settings.log_retention_days }
						onChange={ ( val ) => setNumeric( 'log_retention_days', val ) }
					/>
				</CardBody>
			</Card>

			<Card className="aic-settings-card">
				<CardHeader>
					<h3>Rate Limiting</h3>
				</CardHeader>
				<CardBody>
					<ToggleControl
						label="Enable rate limiting"
						help="Limits the number of MCP requests a user can make per minute. If exceeded, the user is temporarily blocked. Sites with Redis or Memcached will see better performance for this feature."
						checked={ settings.rate_limiting_enabled }
						onChange={ ( val ) => setSettings( { ...settings, rate_limiting_enabled: val } ) }
					/>
					{ settings.rate_limiting_enabled && (
						<>
							<TextControl
								label="Max requests per minute"
								help="Maximum number of MCP requests a single user can make within one minute. A typical AI conversation uses 3-5 requests. Recommended: 20."
								type="number"
								min="1"
								value={ settings.rate_limit }
								onChange={ ( val ) => setNumeric( 'rate_limit', val ) }
							/>
							<TextControl
								label="Block duration (minutes)"
								help="How long a user is blocked after exceeding the rate limit. During this time, all their MCP requests are rejected."
								type="number"
								min="1"
								value={ settings.rate_block_duration }
								onChange={ ( val ) => setNumeric( 'rate_block_duration', val ) }
							/>
						</>
					) }
				</CardBody>
			</Card>

			<div className="aic-settings-actions">
				<Button
					variant="primary"
					onClick={ handleSave }
					isBusy={ saving }
					disabled={ saving }
				>
					Save Settings
				</Button>
				{ saved && <span className="aic-save-notice">Settings saved.</span> }
			</div>
		</div>
	);
}
