/**
 * Purrlink Settings Page Component
 *
 * Admin settings page with tabs for API, Profile, and Persona.
 *
 * @package Purrlink
 */

import { useState, useEffect } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';
import {
	Button,
	TextControl,
	TextareaControl,
	SelectControl,
	Notice,
	Spinner,
	TabPanel,
} from '@wordpress/components';

/**
 * Settings component.
 *
 * @return {JSX.Element} Settings page.
 */
const Settings = () => {
	// State for settings
	const [settings, setSettings] = useState({
		website_name: '',
		niche: '',
		target_audience: '',
		language: 'auto',
		brand_voice: '',
		link_target: '_self',
	});

	// State for persona
	const [persona, setPersona] = useState({
		display_name: 'Default',
		tone: 'friendly',
		writing_style: '',
		language_notes: '',
		signature_phrases: '',
	});

	// State for API key
	const [apiKey, setApiKey] = useState('');
	const [hasApiKey, setHasApiKey] = useState(false);

	// UI state
	const [isLoading, setIsLoading] = useState(true);
	const [isSaving, setIsSaving] = useState(false);
	const [isTesting, setIsTesting] = useState(false);
	const [notice, setNotice] = useState(null);

	// Load settings on mount
	useEffect(() => {
		loadSettings();
	}, []);

	/**
	 * Load settings from API.
	 */
	const loadSettings = async () => {
		setIsLoading(true);
		try {
			const response = await apiFetch({
				path: '/purrlink/v1/settings',
			});

			if (response.settings) {
				setSettings(response.settings);
			}
			if (response.persona) {
				setPersona(response.persona);
			}
			if (response.has_api_key !== undefined) {
				setHasApiKey(response.has_api_key);
			}
		} catch (error) {
			showNotice('error', error.message || __('Failed to load settings', 'purrlink'));
		} finally {
			setIsLoading(false);
		}
	};

	/**
	 * Save settings to API.
	 */
	const saveSettings = async () => {
		setIsSaving(true);
		setNotice(null);

		try {
			const data = {
				settings,
				persona,
			};

			// Only include API key if it was changed
			if (apiKey) {
				data.api_key = apiKey;
			}

			await apiFetch({
				path: '/purrlink/v1/settings',
				method: 'POST',
				data,
			});

			showNotice('success', __('Settings saved successfully!', 'purrlink'));

			// Clear the API key field after saving
			if (apiKey) {
				setApiKey('');
				setHasApiKey(true);
			}
		} catch (error) {
			showNotice('error', error.message || __('Failed to save settings', 'purrlink'));
		} finally {
			setIsSaving(false);
		}
	};

	/**
	 * Test API connection.
	 */
	const testConnection = async () => {
		const keyToTest = apiKey || (hasApiKey ? 'existing' : '');

		if (!keyToTest && !hasApiKey) {
			showNotice('error', __('Please enter an API key first', 'purrlink'));
			return;
		}

		setIsTesting(true);
		setNotice(null);

		try {
			// If using existing key, we need to save first then test
			if (!apiKey && hasApiKey) {
				await apiFetch({
					path: '/purrlink/v1/test-connection',
					method: 'POST',
					data: { api_key: 'use_existing' },
				});
			} else {
				await apiFetch({
					path: '/purrlink/v1/test-connection',
					method: 'POST',
					data: { api_key: apiKey },
				});
			}

			showNotice('success', __('Connection successful! API key is valid.', 'purrlink'));
		} catch (error) {
			showNotice('error', error.message || __('Connection failed. Please check your API key.', 'purrlink'));
		} finally {
			setIsTesting(false);
		}
	};

	/**
	 * Show a notice message.
	 *
	 * @param {string} type    Notice type (success, error, warning, info).
	 * @param {string} message Notice message.
	 */
	const showNotice = (type, message) => {
		setNotice({ type, message });

		// Auto-dismiss success notices
		if (type === 'success') {
			setTimeout(() => setNotice(null), 5000);
		}
	};

	/**
	 * Update settings field.
	 *
	 * @param {string} field Field name.
	 * @param {string} value Field value.
	 */
	const updateSettings = (field, value) => {
		setSettings((prev) => ({ ...prev, [field]: value }));
	};

	/**
	 * Update persona field.
	 *
	 * @param {string} field Field name.
	 * @param {string} value Field value.
	 */
	const updatePersona = (field, value) => {
		setPersona((prev) => ({ ...prev, [field]: value }));
	};

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

	// Tab definitions
	const tabs = [
		{
			name: 'api',
			title: __('API Settings', 'purrlink'),
			className: 'purrlink-tab',
		},
		{
			name: 'profile',
			title: __('Website Profile', 'purrlink'),
			className: 'purrlink-tab',
		},
		{
			name: 'persona',
			title: __('Persona', 'purrlink'),
			className: 'purrlink-tab',
		},
	];

	return (
		<div className="purrlink-settings">
			<h1 className="purrlink-settings__title">
				{__('Purrlink Settings', 'purrlink')}
			</h1>

			{notice && (
				<Notice
					status={notice.type}
					isDismissible={true}
					onRemove={() => setNotice(null)}
				>
					{notice.message}
				</Notice>
			)}

			<TabPanel
				className="purrlink-settings__tabs"
				tabs={tabs}
			>
				{(tab) => (
					<div className="purrlink-settings__panel">
						{tab.name === 'api' && (
							<div className="purrlink-settings__section">
								<h2>{__('Gemini API Configuration', 'purrlink')}</h2>
								<p className="description">
									{__('Enter your Google Gemini API key to enable AI-powered bridge sentence generation.', 'purrlink')}
								</p>

								<div className="purrlink-settings__field purrlink-settings__field--api-key">
									<TextControl
										label={__('API Key', 'purrlink')}
										type="password"
										value={apiKey}
										onChange={setApiKey}
										placeholder={hasApiKey ? '••••••••••••••••' : __('Enter your Gemini API key', 'purrlink')}
										help={hasApiKey ? __('API key is saved. Enter a new key to replace it.', 'purrlink') : __('Get your API key from Google AI Studio', 'purrlink')}
									/>
									<Button
										variant="secondary"
										onClick={testConnection}
										disabled={isTesting || (!apiKey && !hasApiKey)}
										isBusy={isTesting}
									>
										{isTesting ? __('Testing...', 'purrlink') : __('Test Connection', 'purrlink')}
									</Button>
								</div>

								<div className="purrlink-settings__guide">
									<h3>{__('How to get your API key', 'purrlink')}</h3>
									<ol>
										<li>
											{__('Go to ', 'purrlink')}
											<a
												href="https://aistudio.google.com/apikey"
												target="_blank"
												rel="noopener noreferrer"
											>
												Google AI Studio
											</a>
										</li>
										<li>{__('Sign in with your Google account', 'purrlink')}</li>
										<li>{__('Click "Create API key" and select a project', 'purrlink')}</li>
										<li>{__('Copy the key and paste it in the field above', 'purrlink')}</li>
										<li>{__('Click "Test Connection" to verify it works', 'purrlink')}</li>
									</ol>
									<p className="purrlink-settings__guide-note">
										{__('Gemini API has a generous free tier — more than enough for most WordPress sites. No credit card required.', 'purrlink')}
									</p>
								</div>
							</div>
						)}

						{tab.name === 'profile' && (
							<div className="purrlink-settings__section">
								<h2>{__('Website Profile', 'purrlink')}</h2>
								<p className="description">
									{__('Tell us about your website so AI can generate contextually appropriate bridge sentences.', 'purrlink')}
								</p>

								<TextControl
									label={__('Website Name', 'purrlink')}
									value={settings.website_name}
									onChange={(value) => updateSettings('website_name', value)}
									help={__('Your website or blog name', 'purrlink')}
								/>

								<TextControl
									label={__('Niche', 'purrlink')}
									value={settings.niche}
									onChange={(value) => updateSettings('niche', value)}
									placeholder={__('e.g., Technology, Health, Travel', 'purrlink')}
									help={__('The main topic or industry of your content', 'purrlink')}
								/>

								<TextareaControl
									label={__('Target Audience', 'purrlink')}
									value={settings.target_audience}
									onChange={(value) => updateSettings('target_audience', value)}
									placeholder={__('e.g., Developers, beginners, tech enthusiasts', 'purrlink')}
									help={__('Who are you writing for?', 'purrlink')}
									rows={3}
								/>

								<SelectControl
									label={__('Content Language', 'purrlink')}
									value={settings.language}
									onChange={(value) => updateSettings('language', value)}
									options={[
										{ label: __( 'Auto-detect', 'purrlink' ), value: 'auto' },
										{ label: __( 'English', 'purrlink' ), value: 'en' },
										{ label: __( 'Thai (ภาษาไทย)', 'purrlink' ), value: 'th' },
										{ label: __( 'Spanish (Español)', 'purrlink' ), value: 'es' },
										{ label: __( 'Portuguese (Português)', 'purrlink' ), value: 'pt' },
										{ label: __( 'French (Français)', 'purrlink' ), value: 'fr' },
										{ label: __( 'German (Deutsch)', 'purrlink' ), value: 'de' },
										{ label: __( 'Japanese (日本語)', 'purrlink' ), value: 'ja' },
										{ label: __( 'Korean (한국어)', 'purrlink' ), value: 'ko' },
										{ label: __( 'Chinese (中文)', 'purrlink' ), value: 'zh' },
										{ label: __( 'Indonesian (Bahasa Indonesia)', 'purrlink' ), value: 'id' },
										{ label: __( 'Vietnamese (Tiếng Việt)', 'purrlink' ), value: 'vi' },
										{ label: __( 'Arabic (العربية)', 'purrlink' ), value: 'ar' },
										{ label: __( 'Russian (Русский)', 'purrlink' ), value: 'ru' },
										{ label: __( 'Italian (Italiano)', 'purrlink' ), value: 'it' },
										{ label: __( 'Dutch (Nederlands)', 'purrlink' ), value: 'nl' },
										{ label: __( 'Polish (Polski)', 'purrlink' ), value: 'pl' },
										{ label: __( 'Turkish (Türkçe)', 'purrlink' ), value: 'tr' },
									]}
									help={__('Primary language for generated content', 'purrlink')}
								/>

								<SelectControl
									label={__( 'Link Opening Behavior', 'purrlink' )}
									value={settings.link_target || '_self'}
									onChange={(value) => updateSettings( 'link_target', value )}
									options={[
										{
											label: __( 'Same tab (recommended)', 'purrlink' ),
											value: '_self',
										},
										{
											label: __( 'New tab', 'purrlink' ),
											value: '_blank',
										},
									]}
									help={__( 'How bridge sentence links open. New tab automatically adds rel="noopener noreferrer".', 'purrlink' )}
								/>

								<TextareaControl
									label={__('Brand Voice', 'purrlink')}
									value={settings.brand_voice}
									onChange={(value) => updateSettings('brand_voice', value)}
									placeholder={__('e.g., Friendly but professional, casual and approachable', 'purrlink')}
									help={__('Describe your brand\'s communication style (optional)', 'purrlink')}
									rows={3}
								/>
							</div>
						)}

						{tab.name === 'persona' && (
							<div className="purrlink-settings__section">
								<h2>{__('Writing Persona', 'purrlink')}</h2>
								<p className="description">
									{__('Configure the AI writing persona for generating bridge sentences.', 'purrlink')}
								</p>

								<TextControl
									label={__('Display Name', 'purrlink')}
									value={persona.display_name}
									onChange={(value) => updatePersona('display_name', value)}
									placeholder="Default"
									help={__('Name for this persona', 'purrlink')}
								/>

								<SelectControl
									label={__('Tone', 'purrlink')}
									value={persona.tone}
									onChange={(value) => updatePersona('tone', value)}
									options={[
										{ label: __('Friendly', 'purrlink'), value: 'friendly' },
										{ label: __('Professional', 'purrlink'), value: 'professional' },
										{ label: __('Casual', 'purrlink'), value: 'casual' },
										{ label: __('Formal', 'purrlink'), value: 'formal' },
									]}
									help={__('The overall tone of the generated text', 'purrlink')}
								/>

								<TextareaControl
									label={__('Writing Style', 'purrlink')}
									value={persona.writing_style}
									onChange={(value) => updatePersona('writing_style', value)}
									placeholder={__('e.g., Conversational, uses examples, short sentences', 'purrlink')}
									help={__('Describe the writing style', 'purrlink')}
									rows={3}
								/>

								<TextareaControl
									label={__('Language Notes', 'purrlink')}
									value={persona.language_notes}
									onChange={(value) => updatePersona('language_notes', value)}
									placeholder={__('e.g., Use "we" not "I", avoid jargon', 'purrlink')}
									help={__('Special instructions for word choice', 'purrlink')}
									rows={3}
								/>

								<TextareaControl
									label={__('Signature Phrases', 'purrlink')}
									value={persona.signature_phrases}
									onChange={(value) => updatePersona('signature_phrases', value)}
									placeholder={__('e.g., "Here\'s the thing...", "Let\'s dive in"', 'purrlink')}
									help={__('Phrases this persona commonly uses (optional)', 'purrlink')}
									rows={3}
								/>
							</div>
						)}
					</div>
				)}
			</TabPanel>

			<div className="purrlink-settings__actions">
				<Button
					variant="primary"
					onClick={saveSettings}
					disabled={isSaving}
					isBusy={isSaving}
				>
					{isSaving ? __('Saving...', 'purrlink') : __('Save Settings', 'purrlink')}
				</Button>
			</div>
		</div>
	);
};

export default Settings;
