/**
 * Analytics dashboard: KPI statistics, daily chart, top tours table.
 */
import { useState, useEffect } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import {
	App,
	Typography,
	Select,
	Card,
	Statistic,
	Row,
	Col,
	Table,
	Spin,
	Empty,
	Tooltip,
} from 'antd';

import { fetchAnalytics } from '../../api';

const PERIODS = [
	{
		value: 7,
		label: __( 'Last 7 days', 'vistour-virtual-tour-builder' ),
	},
	{
		value: 30,
		label: __( 'Last 30 days', 'vistour-virtual-tour-builder' ),
	},
	{
		value: 90,
		label: __( 'Last 90 days', 'vistour-virtual-tour-builder' ),
	},
];

const Dashboard = () => {
	const { message } = App.useApp();
	const [ days, setDays ] = useState( 30 );
	const [ data, setData ] = useState( null );

	useEffect( () => {
		setData( null );
		fetchAnalytics( { days } )
			.then( setData )
			.catch( ( error ) =>
				message.error(
					error.message ||
						__(
							'Failed to load analytics.',
							'vistour-virtual-tour-builder'
						)
				)
			);
	}, [ days, message ] );

	const maxDaily = data
		? Math.max(
				1,
				...data.daily.map( ( day ) => parseInt( day.views, 10 ) )
		  )
		: 1;

	const stats = data
		? [
				[
					__( 'Views', 'vistour-virtual-tour-builder' ),
					data.totals.views,
				],
				[
					__( 'Unique visitors', 'vistour-virtual-tour-builder' ),
					data.totals.visitors,
				],
				[
					__( 'Hotspot clicks', 'vistour-virtual-tour-builder' ),
					data.totals.hotspot_clicks,
				],
				[
					__( 'Shares', 'vistour-virtual-tour-builder' ),
					data.totals.shares,
				],
		  ]
		: [];

	return (
		<div className="vist360-view">
			<div className="vist360-view__header">
				<div>
					<Typography.Title level={ 2 }>
						{ __(
							'Analytics',
							'vistour-virtual-tour-builder'
						) }
					</Typography.Title>
					<Typography.Text type="secondary">
						{ __(
							'Track how visitors engage with your tours.',
							'vistour-virtual-tour-builder'
						) }
					</Typography.Text>
				</div>
				<Select
					value={ days }
					onChange={ setDays }
					options={ PERIODS }
					style={ { width: 160 } }
				/>
			</div>

			{ ! data && (
				<div className="vist360-loading">
					<Spin size="large" />
				</div>
			) }

			{ data && (
				<>
					<Row gutter={ [ 16, 16 ] }>
						{ stats.map( ( [ label, value ] ) => (
							<Col key={ label } xs={ 12 } lg={ 6 }>
								<Card>
									<Statistic
										title={ label }
										value={ value }
									/>
								</Card>
							</Col>
						) ) }
					</Row>

					<Card
						title={ __(
							'Views over time',
							'vistour-virtual-tour-builder'
						) }
						className="vist360-chart-card"
					>
						{ data.daily.length ? (
							<div
								className="vist360-bar-chart"
								role="img"
								aria-label={ __(
									'Bar chart of daily tour views',
									'vistour-virtual-tour-builder'
								) }
							>
								{ data.daily.map( ( day ) => (
									<Tooltip
										key={ day.day }
										title={ `${ day.day }: ${ day.views }` }
									>
										<div
											className="vist360-bar-chart__bar"
											style={ {
												height: `${ Math.max(
													4,
													( parseInt(
														day.views,
														10
													) /
														maxDaily ) *
														100
												) }%`,
											} }
										/>
									</Tooltip>
								) ) }
							</div>
						) : (
							<Empty
								description={ __(
									'No views recorded in this period yet.',
									'vistour-virtual-tour-builder'
								) }
							/>
						) }
					</Card>

					{ data.top_tours.length > 0 && (
						<Card
							title={ __(
								'Top tours',
								'vistour-virtual-tour-builder'
							) }
						>
							<Table
								size="small"
								rowKey="tour_id"
								pagination={ false }
								dataSource={ data.top_tours }
								columns={ [
									{
										title: __(
											'Tour',
											'vistour-virtual-tour-builder'
										),
										dataIndex: 'title',
										render: ( title, row ) => (
											<a
												href={ `#/edit/${ row.tour_id }` }
											>
												{ title ||
													__(
														'(deleted tour)',
														'vistour-virtual-tour-builder'
													) }
											</a>
										),
									},
									{
										title: __(
											'Views',
											'vistour-virtual-tour-builder'
										),
										dataIndex: 'views',
										align: 'right',
									},
									{
										title: __(
											'Hotspot clicks',
											'vistour-virtual-tour-builder'
										),
										dataIndex: 'hotspot_clicks',
										align: 'right',
									},
								] }
							/>
						</Card>
					) }
				</>
			) }
		</div>
	);
};

export default Dashboard;
