/**
 * Dashboard: connection health, 30-day counters, recent deliveries and a
 * quick-start checklist that disappears once the three steps are done.
 */
import { useCallback, useEffect, useState } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';
import { useNavigate } from 'react-router-dom';

import {
	BlockStack,
	Card,
	EmptyState,
	InlineStack,
	Note,
	SkeletonLoader,
} from '../../ui/molecules';
import { Button, Icon, Text } from '../../ui/atoms';
import Section from '../../components/Section';
import StatusBadge from '../../components/StatusBadge';
import { testConnection } from '../../api/brevo';
import { fetchFeeds } from '../../api/feeds';
import { fetchLogs, fetchStats } from '../../api/logs';
import { useApp } from '../../store/AppStore';
import { formatDateTime, formatRelative } from '../../utils/format';

function StatCard( { label, value, icon, iconColor = 'gray-400', loading } ) {
	return (
		<Card padding={ 20 } rounded="lg" border="gray-200" background="white">
			<BlockStack gap={ 6 }>
				<InlineStack gap={ 8 } blockAlign="center">
					<Icon name={ icon } color={ iconColor } fontSize="xl" />
					{ loading ? (
						<SkeletonLoader width="48px" height="28px" />
					) : (
						<Text size="2xl" weight="semibold">
							{ value }
						</Text>
					) }
				</InlineStack>
				<Text size="xs" color="gray-500">
					{ label }
				</Text>
			</BlockStack>
		</Card>
	);
}

export default function Dashboard() {
	const { connection, setConnection, addToast } = useApp();
	const navigate = useNavigate();

	const [ loading, setLoading ] = useState( true );
	const [ error, setError ] = useState( '' );
	const [ stats, setStats ] = useState( null );
	const [ recent, setRecent ] = useState( [] );
	const [ feeds, setFeeds ] = useState( [] );
	const [ testing, setTesting ] = useState( false );

	const load = useCallback( async () => {
		setLoading( true );
		setError( '' );

		try {
			const [ statsResponse, logsResponse, feedsResponse ] =
				await Promise.all( [
					fetchStats( 30 ),
					fetchLogs( {}, 1, 10 ),
					fetchFeeds(),
				] );

			setStats( statsResponse.stats );
			setRecent( logsResponse.items || [] );
			setFeeds( feedsResponse.items || [] );
		} catch ( requestError ) {
			setError( requestError.message );
		} finally {
			setLoading( false );
		}
	}, [] );

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

	const onTest = async () => {
		setTesting( true );

		try {
			const result = await testConnection();

			setConnection( ( current ) => ( {
				...current,
				hasKey: true,
				lastVerified: result.verified_at,
			} ) );

			addToast(
				sprintf(
					/* translators: %s: Brevo account company name. */
					__(
						'Connected to Brevo account: %s',
						'rewind-form-bridge-for-brevo'
					),
					result.company
				)
			);
		} catch ( requestError ) {
			addToast( requestError.message, 'error' );
		} finally {
			setTesting( false );
		}
	};

	const activeFeeds = feeds.filter( ( feed ) => feed.status === 'active' );

	const steps = [
		{
			done: connection.hasKey,
			label: __(
				'Connect your Brevo account',
				'rewind-form-bridge-for-brevo'
			),
			to: '/connections',
		},
		{
			done: feeds.length > 0,
			label: __(
				'Map a form to a Brevo list',
				'rewind-form-bridge-for-brevo'
			),
			to: '/mappings/new',
		},
		{
			done: activeFeeds.length > 0,
			label: __( 'Turn the mapping on', 'rewind-form-bridge-for-brevo' ),
			to: '/mappings',
		},
	];

	const checklistDone = steps.every( ( step ) => step.done );

	return (
		<div className="rbfb-page rbfb-page--wide">
			<BlockStack gap={ 20 }>
				{ error && (
					<Note type="error">
						<Note.Normal>{ error }</Note.Normal>
					</Note>
				) }

				<Section
					title={ __(
						'Brevo connection',
						'rewind-form-bridge-for-brevo'
					) }
					icon="cloud_done"
					actions={
						<Button
							variant="outlined"
							size="small"
							startIcon="refresh"
							loading={ testing }
							disabled={ testing }
							onClick={ onTest }
						>
							{ __(
								'Test connection',
								'rewind-form-bridge-for-brevo'
							) }
						</Button>
					}
				>
					<InlineStack gap={ 40 } blockAlign="start">
						<BlockStack gap={ 6 }>
							<Text size="xs" color="gray-500">
								{ __(
									'Status',
									'rewind-form-bridge-for-brevo'
								) }
							</Text>
							<StatusBadge
								status={
									connection.hasKey ? 'active' : 'paused'
								}
							/>
						</BlockStack>

						<BlockStack gap={ 6 }>
							<Text size="xs" color="gray-500">
								{ __(
									'API key',
									'rewind-form-bridge-for-brevo'
								) }
							</Text>
							<Text size="sm">
								{ connection.hint ||
									__(
										'Not set',
										'rewind-form-bridge-for-brevo'
									) }
							</Text>
						</BlockStack>

						<BlockStack gap={ 6 }>
							<Text size="xs" color="gray-500">
								{ __(
									'Last verified',
									'rewind-form-bridge-for-brevo'
								) }
							</Text>
							<Text size="sm">
								{ formatDateTime( connection.lastVerified ) }
							</Text>
						</BlockStack>

						<BlockStack gap={ 6 }>
							<Text size="xs" color="gray-500">
								{ __(
									'Active mappings',
									'rewind-form-bridge-for-brevo'
								) }
							</Text>
							<Text size="sm">{ `${ activeFeeds.length } / ${ feeds.length }` }</Text>
						</BlockStack>
					</InlineStack>
				</Section>

				{ ! checklistDone && ! loading && (
					<Section
						title={ __(
							'Quick start',
							'rewind-form-bridge-for-brevo'
						) }
						icon="rocket_launch"
					>
						<BlockStack gap={ 12 } style={ { width: '100%' } }>
							{ steps.map( ( step ) => (
								<InlineStack
									key={ step.to }
									gap={ 10 }
									align="between"
									blockAlign="center"
								>
									<InlineStack gap={ 10 } blockAlign="center">
										<Icon
											name={
												step.done
													? 'check_circle'
													: 'radio_button_unchecked'
											}
											color={
												step.done
													? 'success'
													: 'gray-400'
											}
											fontSize="lg"
										/>
										<Text
											color={
												step.done ? 'gray-500' : 'black'
											}
											size="sm"
										>
											{ step.label }
										</Text>
									</InlineStack>

									{ ! step.done && (
										<Button
											variant="link"
											size="small"
											endIcon="arrow_forward"
											onClick={ () =>
												navigate( step.to )
											}
										>
											{ __(
												'Do this',
												'rewind-form-bridge-for-brevo'
											) }
										</Button>
									) }
								</InlineStack>
							) ) }
						</BlockStack>
					</Section>
				) }

				<div className="rbfb-stat-cards">
					<StatCard
						label={ __(
							'Submissions synced (30 days)',
							'rewind-form-bridge-for-brevo'
						) }
						icon="move_to_inbox"
						value={ stats?.total ?? 0 }
						loading={ loading }
					/>
					<StatCard
						label={ __(
							'Contacts created',
							'rewind-form-bridge-for-brevo'
						) }
						icon="person_add"
						iconColor="success"
						value={ stats?.created ?? 0 }
						loading={ loading }
					/>
					<StatCard
						label={ __(
							'Contacts updated',
							'rewind-form-bridge-for-brevo'
						) }
						icon="sync_alt"
						value={ stats?.updated ?? 0 }
						loading={ loading }
					/>
					<StatCard
						label={ __(
							'Failed syncs',
							'rewind-form-bridge-for-brevo'
						) }
						icon="error"
						iconColor="error"
						value={ stats?.failed ?? 0 }
						loading={ loading }
					/>
				</div>

				<Section
					title={ __(
						'Recent activity',
						'rewind-form-bridge-for-brevo'
					) }
					icon="history"
					actions={
						<Button
							variant="link"
							size="small"
							startIcon="receipt_long"
							endIcon="arrow_forward"
							onClick={ () => navigate( '/logs' ) }
						>
							{ __(
								'View all logs',
								'rewind-form-bridge-for-brevo'
							) }
						</Button>
					}
				>
					{ loading && (
						<BlockStack gap={ 10 } style={ { width: '100%' } }>
							{ [ 0, 1, 2, 3 ].map( ( row ) => (
								<SkeletonLoader
									key={ row }
									width="100%"
									height="34px"
								/>
							) ) }
						</BlockStack>
					) }

					{ ! loading && recent.length === 0 && (
						<EmptyState
							icon={
								<Icon
									name="move_to_inbox"
									fontSize="4xl"
									color="gray-400"
								/>
							}
							title={ __(
								'No deliveries yet',
								'rewind-form-bridge-for-brevo'
							) }
							description={ __(
								'Once a mapped form is submitted, every attempt shows up here.',
								'rewind-form-bridge-for-brevo'
							) }
						>
							<Button
								variant="primary"
								size="small"
								startIcon="add"
								onClick={ () => navigate( '/mappings/new' ) }
							>
								{ __(
									'Add your first mapping',
									'rewind-form-bridge-for-brevo'
								) }
							</Button>
						</EmptyState>
					) }

					{ ! loading && recent.length > 0 && (
						<table className="rbfb-table">
							<thead>
								<tr>
									<th>
										{ __(
											'Form',
											'rewind-form-bridge-for-brevo'
										) }
									</th>
									<th>
										{ __(
											'Contact',
											'rewind-form-bridge-for-brevo'
										) }
									</th>
									<th>
										{ __(
											'Status',
											'rewind-form-bridge-for-brevo'
										) }
									</th>
									<th>
										{ __(
											'When',
											'rewind-form-bridge-for-brevo'
										) }
									</th>
								</tr>
							</thead>
							<tbody>
								{ recent.map( ( row ) => (
									<tr
										key={ row.id }
										className="rbfb-table__row--clickable"
										onClick={ () =>
											navigate(
												`/logs?entry=${ row.id }`
											)
										}
									>
										<td>{ row.feed_title }</td>
										<td>
											{ row.email ||
												__(
													'(no email)',
													'rewind-form-bridge-for-brevo'
												) }
										</td>
										<td>
											<StatusBadge
												status={ row.status }
											/>
										</td>
										<td
											title={ formatDateTime(
												row.created_at
											) }
										>
											{ formatRelative( row.created_at ) }
										</td>
									</tr>
								) ) }
							</tbody>
						</table>
					) }
				</Section>
			</BlockStack>
		</div>
	);
}
