/**
 * External dependencies.
 */
import { useState, useEffect } from "@wordpress/element";
import { Link2, Loader2 } from 'lucide-react';

/**
 * Internal dependencies.
 */
import { showPromiseToast, showToast } from "../../utils";
import { fetchOptions, APICheck } from "../../api/settings";
import { SettingsCard, TextInput } from "../templates";
import SettingsLayout from "../layout/SettingsLayout";
import { usePluginConfig } from "../../context/PluginContext";

const Setup = () => {
	const { pluginUrl } = usePluginConfig();
	const [processing, setProcessing] = useState(true);
	const INVALID_CREDENTIALS_MESSAGE = "Invalid credentials. Please try again.";

	const [options, setOptions] = useState({
		"general-settings": {},
	});
	const [isLoading, setIsLoading] = useState(false);

	const updateOption = (value, id) => {
		setOptions({
			...options,
			"general-settings": {
				...options["general-settings"],
				[id]: value,
			},
		});
	};

	const onSave = async () => {
		if (!processing) {
			setIsLoading(true);

			let token_id = options["general-settings"]["your-real-token-id"];
			let api_token = options["general-settings"]["your-real-api-token"];
			let client_instance_url =
				options["general-settings"]["client-instance-url"];

			if (
				!token_id?.trim() ||
				!api_token?.trim() ||
				!client_instance_url?.trim()
			) {
				setIsLoading(false);
				showToast("Please fill in all fields.", "error");
				return;
			}

			const data = {
				token_id,
				api_token,
				client_instance_url,
			};

			try {
				await APICheck(data);

				// Credentials verified and all settings saved by the server.
				// Redirect to the dashboard.
				const redirectTo = window.openAssetPluginState?.redirectTo || '';
				window.location.href = redirectTo
					? redirectTo.replace(/#\/dashboard.*$/, '#/dashboard?installComplete=true')
					: '/wp-admin/admin.php?page=openasset#/dashboard?installComplete=true';
				window.location.reload(true);
			} catch (error) {
				setIsLoading(false);
				// eslint-disable-next-line no-console
				console.error("Failed to check API credentials:", error);
				showToast(INVALID_CREDENTIALS_MESSAGE, "error");
			}
		}
	};

	useEffect(() => {
		const updateOptions = (settings) =>
			setOptions({ ...options, ...settings });
		const res = fetchOptions({ updateOptions }).then((res) =>
			setProcessing(false)
		);

		showPromiseToast(res);
	}, []);
	return (
		<SettingsLayout showNavigation={false}>
			<div className='max-w-7xl space-y-6'>
				<SettingsCard
					icon={Link2}
					title='Connect to OpenAsset'
					description='Enter your API credentials to connect to your OpenAsset instance'
				>
					{isLoading ? (
						<div className='flex flex-col items-center justify-center py-12'>
							<Loader2 className='w-12 h-12 text-[#2563eb] animate-spin mb-4' />
							<p className='text-oa-text-secondary font-oa-medium'>
								Checking Credentials...
							</p>
						</div>
					) : (
						<>
							<div className='bg-blue-50 border border-blue-200 rounded-oa-md p-4 mb-6'>
								<p className='text-oa-sm text-oa-text-secondary'>
									An OpenAsset WordPress Plugin License is required to connect and access data. Please contact your Customer Success manager if you do not have one.
								</p>
							</div>

							<div className='space-y-6'>
								<TextInput
									id='client-instance-url'
									label='Your OpenAsset Instance URL'
									value={options["general-settings"]["client-instance-url"]}
									setOption={updateOption}
									required={true}
								/>
								<TextInput
									id='your-real-token-id'
									label='Token ID'
									value={options["general-settings"]["your-real-token-id"]}
									setOption={updateOption}
									required={true}
								/>
								<TextInput
									id='your-real-api-token'
									label='API Token'
									value={options["general-settings"]["your-real-api-token"]}
									setOption={updateOption}
									type='password'
									required={true}
								/>
							</div>

							<div className='pt-6 border-t border-oa-border-secondary mt-6'>
								<button
									type='submit'
									onClick={onSave}
									className='inline-flex items-center justify-center gap-2 px-6 py-3 bg-[#2563eb] text-white font-oa-semibold rounded-oa-md hover:bg-[#1d4ed8] transition-colors shadow-sm'
								>
									Begin Install
								</button>
							</div>
						</>
					)}
				</SettingsCard>
			</div>
		</SettingsLayout>
	);
};

export default Setup;
