import React, { useCallback, useEffect, useState } from 'react';
import { Alert, Container, Paper, Tabs, Text, Title } from '@mantine/core';
import { IconAlertCircle, IconBug, IconSettings, IconWebhook } from '@tabler/icons-react';
import { __ } from '@wordpress/i18n';
import ConfigTab from './components/ConfigTab';
import DebugTab from './components/DebugTab';
import ReadinessSummary from './components/ReadinessSummary';
import WebhookTab from './components/WebhookTab';

const apiFetch = window.wp.apiFetch;

/**
 * Main administration app for the independently useful Free plugin.
 *
 * Pro is a separately installed add-on that contributes additional gateways.
 */
export default function App() {
	const [settings, setSettings] = useState(null);
	const [loading, setLoading] = useState(true);
	const [error, setError] = useState(null);

	const loadSettings = useCallback(() => {
		setLoading(true);
		setError(null);
		return apiFetch({
			path: '/digitalapps-payments-for-adyen/v1/settings',
			headers: { 'X-WP-Nonce': DigitalAppsPaymentsForAdyenSettings.nonce },
		})
			.then(setSettings)
			.catch((requestError) => {
				setError(requestError.message || __('The settings could not be loaded.', 'digital-apps-payments-for-adyen'));
			})
			.finally(() => setLoading(false));
	}, []);

	useEffect(() => {
		loadSettings();
	}, [loadSettings]);

	return (
		<Container size="xl" py="xl">
			<Paper shadow="sm" p="lg" mb="lg" withBorder>
				<Title order={1}>{__('Digital Apps Payments for Adyen', 'digital-apps-payments-for-adyen')}</Title>
				<Text c="dimmed" mt={4}>
					{__('Configure checkout credentials, webhook security and diagnostics.', 'digital-apps-payments-for-adyen')}
				</Text>
			</Paper>

			{error && (
				<Alert icon={<IconAlertCircle size={18} />} color="red" title={__('Unable to load settings', 'digital-apps-payments-for-adyen')} mb="lg">
					{error}
				</Alert>
			)}

			<ReadinessSummary settings={settings} loading={loading} />

			<Tabs defaultValue="config" keepMounted={false}>
				<Tabs.List>
					<Tabs.Tab value="config" leftSection={<IconSettings size={16} />}>
						{__('Configuration', 'digital-apps-payments-for-adyen')}
					</Tabs.Tab>
					<Tabs.Tab value="webhook" leftSection={<IconWebhook size={16} />}>
						{__('Webhooks', 'digital-apps-payments-for-adyen')}
					</Tabs.Tab>
					<Tabs.Tab value="debug" leftSection={<IconBug size={16} />}>
						{__('Diagnostics', 'digital-apps-payments-for-adyen')}
					</Tabs.Tab>
				</Tabs.List>

				<Tabs.Panel value="config" pt="md">
					<ConfigTab settingsData={settings} loading={loading} onSettingsChanged={setSettings} />
				</Tabs.Panel>
				<Tabs.Panel value="webhook" pt="md">
					<WebhookTab settingsData={settings} loading={loading} onSettingsChanged={setSettings} />
				</Tabs.Panel>
				<Tabs.Panel value="debug" pt="md">
					<DebugTab settingsData={settings} />
				</Tabs.Panel>
			</Tabs>
		</Container>
	);
}
