import { useState } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';
import { useNavigate } from 'react-router-dom';
import { Card, EmptyState, ErrorBox, StatusBadge, settingsPath, useReport } from './common';
import { fetchStockHealth } from './api';
import { downloadCsv, money, num } from './format';
import PageHeader from './ui/PageHeader';
import { SkeletonCard, SkeletonKpis, SkeletonRegion } from './ui/Skeleton';

const TEXT_DOMAIN = 'stock-sync-with-google-sheet-for-woocommerce';

const GROUPS = [
	[ 'out_of_stock', __( 'Out of stock', TEXT_DOMAIN ), 'bad' ],
	[ 'low_stock', __( 'Low stock', TEXT_DOMAIN ), 'warn' ],
	[ 'at_risk', __( 'At risk of running out', TEXT_DOMAIN ), 'warn' ],
	[ 'overstock', __( 'Too much stock', TEXT_DOMAIN ), 'info' ],
	[ 'dead_stock', __( 'Not selling', TEXT_DOMAIN ), 'muted' ],
];

function StockList( { rows, empty } ) {
	if ( ! rows.length ) {
		return <EmptyState title={ empty } />;
	}
	return (
		<div className="ssgsw-table-wrap ssgsw-table-wrap--sticky">
			<table className="ssgsw-table">
				<thead>
					<tr>
						<th>{ __( 'SKU', TEXT_DOMAIN ) }</th>
						<th>{ __( 'Product', TEXT_DOMAIN ) }</th>
						<th className="is-num">{ __( 'Stock', TEXT_DOMAIN ) }</th>
						<th className="is-num">{ __( 'Sold per day', TEXT_DOMAIN ) }</th>
						<th className="is-num">{ __( 'Days of stock', TEXT_DOMAIN ) }</th>
						<th>{ __( 'Last sale', TEXT_DOMAIN ) }</th>
					</tr>
				</thead>
				<tbody>
					{ rows.map( ( r ) => (
						<tr key={ r.sku }>
							<td>{ r.sku }</td>
							<td className="ssgsw-table__product"><span title={ r.product }>{ r.product }</span></td>
							<td className="is-num">{ r.stock === null || r.stock === undefined ? '–' : num( r.stock ) }</td>
							<td className="is-num">{ num( r.velocity, 2 ) }</td>
							<td className="is-num">{ r.days_of_cover === null || r.days_of_cover === undefined ? '–' : num( r.days_of_cover, 1 ) }</td>
							<td>{ r.last_sale || '–' }</td>
						</tr>
					) ) }
				</tbody>
			</table>
		</div>
	);
}

export default function StockHealth() {
	const navigate = useNavigate();
	const { data, loading, error, reload } = useReport( fetchStockHealth, [] );
	const [ open, setOpen ] = useState( 'out_of_stock' );

	const reorder = ( data && data.reorder ) || [];
	const exportCsv = () => downloadCsv(
		'flexstock-reorder-list.csv',
		[ 'SKU', 'Product', 'On hand', 'Sales per day', 'Days of stock', 'Suggested quantity', 'Status' ],
		reorder.map( ( r ) => [ r.sku, r.product, r.on_hand, r.velocity, r.days_of_cover, r.suggested_qty, r.status ] )
	);
	const current = GROUPS.find( ( g ) => g[ 0 ] === open ) || GROUPS[ 0 ];

	return (
		<div className="ssgsw-an-screen">
			<PageHeader
				title={ __( 'Stock', TEXT_DOMAIN ) }
				description={ __( 'What is running out, what is sitting still, and what to reorder. Shows your stock right now.', TEXT_DOMAIN ) }
				onRefresh={ reload }
				refreshing={ loading && !! data }
			/>

			{ loading && ! data && <SkeletonRegion><SkeletonKpis count={ 6 } /><SkeletonCard lines={ 6 } /></SkeletonRegion> }
			{ error && <ErrorBox message={ error } onRetry={ reload } /> }

			{ data && data.counts && (
				<div className={ loading ? 'is-refreshing' : '' }>
					<div className="ssgsw-kpis ssgsw-kpis--six" role="group" aria-label={ __( 'Filter by stock status', TEXT_DOMAIN ) }>
						{ [ ...GROUPS, [ 'healthy', __( 'Healthy', TEXT_DOMAIN ), 'ok' ] ].map( ( [ key, label, tone ] ) => (
							<button
								key={ key }
								type="button"
								className={ `ssgsw-kpi ssgsw-kpi--tone-${ tone }${ open === key ? ' is-selected' : '' }` }
								onClick={ () => key !== 'healthy' && setOpen( key ) }
								aria-pressed={ open === key }
								disabled={ key === 'healthy' }
							>
								<span className="ssgsw-kpi__label">{ label }</span>
								<strong className="ssgsw-kpi__value">{ num( data.counts[ key ] ) }</strong>
							</button>
						) ) }
					</div>
					{ data.stock_value && (
						<p className="ssgsw-an-foot ssgsw-stockvalue">
							{ sprintf( __( 'Stock value at retail prices: %s', TEXT_DOMAIN ), money( data.stock_value.retail, data.currency, data.currency_symbol ) ) }
							{ data.stock_value.cost !== null && data.stock_value.cost !== undefined ? ` · ${ sprintf( __( 'at cost: %s', TEXT_DOMAIN ), money( data.stock_value.cost, data.currency, data.currency_symbol ) ) }` : '' }
						</p>
					) }

					<Card className="ssgsw-an-card--flush" title={ current[ 1 ] } actions={ <StatusBadge status={ open } /> }>
						<StockList rows={ ( data.lists && data.lists[ open ] ) || [] } empty={ __( 'Nothing here. Good news.', TEXT_DOMAIN ) } />
					</Card>

					<Card
						className="ssgsw-an-card--flush"
						title={ __( 'Reorder list', TEXT_DOMAIN ) }
						subtitle={ __( 'Products to order from your supplier, with a suggested quantity.', TEXT_DOMAIN ) }
						actions={ reorder.length ? <button type="button" className="ssgsw-analytics-btn ssgsw-analytics-btn--primary" onClick={ exportCsv }>{ __( 'Download for supplier', TEXT_DOMAIN ) }</button> : null }
					>
						{ reorder.length ? (
							<div className="ssgsw-table-wrap ssgsw-table-wrap--sticky">
								<table className="ssgsw-table">
									<thead>
										<tr>
											<th>{ __( 'SKU', TEXT_DOMAIN ) }</th>
											<th>{ __( 'Product', TEXT_DOMAIN ) }</th>
											<th className="is-num">{ __( 'On hand', TEXT_DOMAIN ) }</th>
											<th className="is-num">{ __( 'Sold per day', TEXT_DOMAIN ) }</th>
											<th className="is-num">{ __( 'Days of stock', TEXT_DOMAIN ) }</th>
											<th className="is-num">{ __( 'Suggested order', TEXT_DOMAIN ) }</th>
											<th>{ __( 'Status', TEXT_DOMAIN ) }</th>
										</tr>
									</thead>
									<tbody>
										{ reorder.map( ( r ) => (
											<tr key={ r.sku }>
												<td>{ r.sku }</td>
												<td className="ssgsw-table__product"><span title={ r.product }>{ r.product }</span></td>
												<td className="is-num">{ num( r.on_hand ) }</td>
												<td className="is-num">{ num( r.velocity, 2 ) }</td>
												<td className="is-num">{ r.days_of_cover === null || r.days_of_cover === undefined ? '–' : num( r.days_of_cover, 1 ) }</td>
												<td className="is-num"><strong>{ num( r.suggested_qty ) }</strong></td>
												<td><StatusBadge status={ r.status } /></td>
											</tr>
										) ) }
									</tbody>
								</table>
							</div>
						) : (
							<EmptyState title={ __( 'No reorders needed', TEXT_DOMAIN ) }>{ __( 'No product is expected to run out within your supplier days plus safety days.', TEXT_DOMAIN ) }</EmptyState>
						) }
					</Card>

					{ data.thresholds && data.thresholds.lead_time !== undefined && (
						<Card
							className="ssgsw-howwedecide"
							title={ __( 'How we decide', TEXT_DOMAIN ) }
							actions={ <button type="button" className="ssgsw-link" onClick={ () => navigate( settingsPath() ) }>{ __( 'Change the rules', TEXT_DOMAIN ) }</button> }
						>
							<ul className="ssgsw-rules">
								<li>{ sprintf( __( 'Low stock: %s units or fewer.', TEXT_DOMAIN ), data.thresholds.low_stock_threshold ?? '?' ) }</li>
								<li>{ sprintf( __( 'Reorder: your supplier needs %1$s days, plus %2$s extra days of stock.', TEXT_DOMAIN ), data.thresholds.lead_time, data.thresholds.safety_days ?? '?' ) }</li>
								<li>{ sprintf( __( 'Not selling: no sales for %s days.', TEXT_DOMAIN ), data.thresholds.dead_stock_days ?? '?' ) }</li>
								<li>{ sprintf( __( 'Too much stock: it would last longer than %s days.', TEXT_DOMAIN ), data.thresholds.overstock_days ?? '?' ) }</li>
							</ul>
						</Card>
					) }
				</div>
			) }
		</div>
	);
}
