import { Fragment, useState } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';
import { Card, EmptyState, ErrorBox, useReport, rangeKey } from './common';
import PageHeader from './ui/PageHeader';
import { SkeletonKpis, SkeletonRegion, SkeletonTable } from './ui/Skeleton';
import { collectStoresNow, fetchStores } from './api_stores';
import { downloadCsv, money, niceDate, num } from './format';

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

/** Status badge for one store: OK, stale since …, error, pending. */
function StoreStatus( { store } ) {
	if ( store.stale ) {
		return (
			<span className="ssgsw-badge ssgsw-badge--bad" title={ store.error || '' }>
				{ store.stale_since ? sprintf( __( 'Stale since %s', TEXT_DOMAIN ), niceDate( store.stale_since ) ) : __( 'Stale', TEXT_DOMAIN ) }
			</span>
		);
	}
	if ( store.status === 'error' ) {
		return <span className="ssgsw-badge ssgsw-badge--warn" title={ store.error || '' }>{ __( 'Last run failed', TEXT_DOMAIN ) }</span>;
	}
	if ( store.status === 'ok' ) {
		return <span className="ssgsw-badge ssgsw-badge--ok">{ __( 'OK', TEXT_DOMAIN ) }</span>;
	}
	return <span className="ssgsw-badge ssgsw-badge--muted">{ __( 'Not collected yet', TEXT_DOMAIN ) }</span>;
}

/**
 * Request params. The stores endpoint reads `days` only without dates, so a range ending on a past day
 * (`to`, e.g. the Overview's "last period with sales") is sent as from/to.
 */
const storeParams = ( range ) => {
	if ( range.from && range.to ) {
		return { from: range.from, to: range.to };
	}
	if ( ! range.to ) {
		return { days: range.days };
	}
	const [ y, mo, d ] = String( range.to ).split( '-' ).map( Number );
	const from = new Date( Date.UTC( y, mo - 1, d - ( range.days - 1 ) ) ).toISOString().slice( 0, 10 );
	return { from, to: range.to };
};

const modeLabel = ( mode ) => {
	if ( mode === 'main' ) {
		return __( 'Main', TEXT_DOMAIN );
	}
	return mode === 'shared' ? __( 'Shared stock', TEXT_DOMAIN ) : __( 'Own stock', TEXT_DOMAIN );
};

/**
 * Multi-Store view (main store only): KPIs for all stores, one row per store with stale badges,
 * top SKUs across stores, stock per store, unmatched SKUs and a "Collect now" button.
 * Optional props `range` ({ days, to }) and `onRange` let the parent share its date range.
 */
export default function Stores( { range: rangeProp, onRange } ) {
	const [ own, setOwn ] = useState( { days: 28, to: null } );
	const range = rangeProp || own;
	const setRange = onRange || setOwn;
	const [ collecting, setCollecting ] = useState( false );
	const [ notice, setNotice ] = useState( null );

	const { data, loading, error, reload } = useReport( () => fetchStores( storeParams( range ) ), [ rangeKey( range ) ] );

	const collect = () => {
		setCollecting( true );
		setNotice( null );
		collectStoresNow()
			.then( ( res ) => {
				setNotice( { type: 'success', text: res.message || __( 'Stores collected.', TEXT_DOMAIN ) } );
				reload();
			} )
			.catch( ( e ) => setNotice( { type: 'error', text: e.message } ) )
			.finally( () => setCollecting( false ) );
	};

	if ( error ) {
		return (
			<div className="ssgsw-an-screen">
				{ /not_main_store|main store/i.test( error ) ? (
					<EmptyState title={ __( 'All-stores analytics lives on the main store', TEXT_DOMAIN ) }>
						{ __( 'Open FlexStock → Analytics on the Multi-Store main store to see every connected store together.', TEXT_DOMAIN ) }
					</EmptyState>
				) : (
					<ErrorBox message={ error } onRetry={ reload } />
				) }
			</div>
		);
	}

	const stores = ( data && data.stores ) || [];
	const totals = ( data && data.totals ) || {};
	const byCurrency = totals.by_currency || {};
	const currencies = Object.keys( byCurrency );
	const nameOf = ( id ) => {
		const s = stores.find( ( x ) => x.store_id === id );
		return s ? s.name : id;
	};

	const exportCsv = () => downloadCsv(
		'flexstock-stores.csv',
		[ 'Store', 'Status', 'Units', 'Net sales', 'Refunds', 'Currency', 'SKUs sold', 'Last collected day' ],
		stores.map( ( s ) => [ s.name, s.stale ? `stale since ${ s.stale_since }` : s.status, s.kpis.units, s.kpis.net, s.kpis.refunds, s.kpis.currency, s.kpis.skus_sold, s.last_date || '' ] )
	);

	return (
		<div className="ssgsw-an-screen">
			<PageHeader
				title={ __( 'Stores', TEXT_DOMAIN ) }
				description={ __( 'Sales from every connected store, side by side.', TEXT_DOMAIN ) }
				range={ range }
				setRange={ setRange }
				timezone={ data && data.timezone }
				showCompare={ false }
				onRefresh={ reload }
				refreshing={ loading && !! data }
				actions={ (
					<button type="button" className="ssgsw-analytics-btn ssgsw-analytics-btn--primary" onClick={ collect } disabled={ collecting }>
						{ collecting ? __( 'Collecting…', TEXT_DOMAIN ) : __( 'Collect now', TEXT_DOMAIN ) }
					</button>
				) }
			/>
			{ notice && (
				<div className={ `notice notice-${ notice.type === 'error' ? 'error' : 'success' } inline` } role="status">
					<p>{ notice.text }</p>
				</div>
			) }
			{ loading && ! data && <SkeletonRegion><SkeletonKpis count={ 4 } /><SkeletonTable rows={ 6 } cols={ 6 } /></SkeletonRegion> }

			{ data && (
				<Fragment>
					<div className="ssgsw-kpis">
						<div className="ssgsw-kpi">
							<span className="ssgsw-kpi__label">{ __( 'Units, all stores', TEXT_DOMAIN ) }</span>
							<strong className="ssgsw-kpi__value">{ num( totals.units ) }</strong>
							<span className="ssgsw-kpi__meta">
								<small>
									{ sprintf(
										/* translators: 1: stores with data, 2: all stores */
										__( '%1$d of %2$d stores', TEXT_DOMAIN ),
										totals.stores_with_data || 0,
										totals.stores_total || 0
									) }
								</small>
							</span>
						</div>
						{ currencies.map( ( cur ) => (
							<div key={ cur } className="ssgsw-kpi">
								<span className="ssgsw-kpi__label">{ sprintf( __( 'Net sales (%s)', TEXT_DOMAIN ), cur ) }</span>
								<strong className="ssgsw-kpi__value">{ money( byCurrency[ cur ].net, cur ) }</strong>
								<span className="ssgsw-kpi__meta">
									<small>{ sprintf( __( 'Refunds %s', TEXT_DOMAIN ), money( byCurrency[ cur ].refunds, cur ) ) }</small>
								</span>
							</div>
						) ) }
						{ totals.converted && (
							<div className="ssgsw-kpi">
								<span className="ssgsw-kpi__label">{ __( 'Net sales, converted', TEXT_DOMAIN ) }</span>
								<strong className="ssgsw-kpi__value">{ money( totals.converted.net, totals.converted.currency ) }</strong>
								<span className="ssgsw-kpi__meta">
									<small>{ totals.converted.complete ? __( 'Fixed rates from settings', TEXT_DOMAIN ) : __( 'Some currencies have no rate', TEXT_DOMAIN ) }</small>
								</span>
							</div>
						) }
						<div className="ssgsw-kpi">
							<span className="ssgsw-kpi__label">{ __( 'Stale stores', TEXT_DOMAIN ) }</span>
							<strong className="ssgsw-kpi__value">{ num( totals.stores_stale ) }</strong>
							<span className="ssgsw-kpi__meta">
								<small>{ data.next_collect ? sprintf( __( 'Next collection %s UTC', TEXT_DOMAIN ), data.next_collect ) : __( 'Nightly collection is off', TEXT_DOMAIN ) }</small>
							</span>
						</div>
					</div>

					<Card
						title={ sprintf( __( 'Stores (%d)', TEXT_DOMAIN ), stores.length ) }
						actions={ <button type="button" className="ssgsw-analytics-btn ssgsw-analytics-btn--secondary" onClick={ exportCsv }>{ __( 'Download CSV', TEXT_DOMAIN ) }</button> }
					>
						{ stores.length <= 1 && (
							<p className="ssgsw-analytics-muted">{ __( 'No connected stores yet. Connect stores with the Multi-Store add-on; their sales appear here after the first collection.', TEXT_DOMAIN ) }</p>
						) }
						<div className="ssgsw-table-wrap">
							<table className="ssgsw-table">
								<thead>
									<tr>
										<th>{ __( 'Store', TEXT_DOMAIN ) }</th>
										<th>{ __( 'Status', TEXT_DOMAIN ) }</th>
										<th>{ __( 'Stock', TEXT_DOMAIN ) }</th>
										<th className="is-num">{ __( 'Units', TEXT_DOMAIN ) }</th>
										<th className="is-num">{ __( 'Net sales', TEXT_DOMAIN ) }</th>
										<th className="is-num">{ __( 'Refunds', TEXT_DOMAIN ) }</th>
										<th className="is-num">{ __( 'SKUs sold', TEXT_DOMAIN ) }</th>
										<th>{ __( 'Collected up to', TEXT_DOMAIN ) }</th>
									</tr>
								</thead>
								<tbody>
									{ stores.map( ( s ) => (
										<tr key={ s.store_id }>
											<td>
												<strong>{ s.name || s.url }</strong>
												{ s.is_main && <small className="ssgsw-analytics-muted"> { __( '(this store)', TEXT_DOMAIN ) }</small> }
												{ s.error && ! s.stale && s.status !== 'ok' && <div className="ssgsw-analytics-muted"><small>{ s.error }</small></div> }
											</td>
											<td><StoreStatus store={ s } /></td>
											<td>{ modeLabel( s.stock_mode ) }</td>
											<td className="is-num">{ num( s.kpis.units ) }</td>
											<td className="is-num">{ money( s.kpis.net, s.kpis.currency || data.currency ) }</td>
											<td className="is-num">{ money( s.kpis.refunds, s.kpis.currency || data.currency ) }</td>
											<td className="is-num">{ num( s.kpis.skus_sold ) }</td>
											<td>{ s.last_date ? niceDate( s.last_date ) : '–' }</td>
										</tr>
									) ) }
								</tbody>
							</table>
						</div>
					</Card>

					<Card title={ __( 'Top SKUs across stores', TEXT_DOMAIN ) }>
						{ ! ( data.top_skus || [] ).length ? (
							<p className="ssgsw-analytics-muted">{ __( 'No sales in this period.', TEXT_DOMAIN ) }</p>
						) : (
							<div className="ssgsw-table-wrap">
								<table className="ssgsw-table">
									<thead>
										<tr>
											<th>{ __( 'SKU', TEXT_DOMAIN ) }</th>
											<th>{ __( 'Product', TEXT_DOMAIN ) }</th>
											<th className="is-num">{ __( 'Units', TEXT_DOMAIN ) }</th>
											<th>{ __( 'By store', TEXT_DOMAIN ) }</th>
										</tr>
									</thead>
									<tbody>
										{ data.top_skus.slice( 0, 20 ).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.units ) }</td>
												<td>{ Object.keys( r.stores ).map( ( id ) => `${ nameOf( id ) }: ${ num( r.stores[ id ] ) }` ).join( ' · ' ) }</td>
											</tr>
										) ) }
									</tbody>
								</table>
							</div>
						) }
					</Card>

					{ ( data.stock || [] ).length > 0 && (
						<Card title={ __( 'Stock per store', TEXT_DOMAIN ) }>
							<p className="ssgsw-analytics-muted">{ __( 'Shared stock is counted once in the total; days of cover for shared stock use the combined sales of every store sharing it.', TEXT_DOMAIN ) }</p>
							<div className="ssgsw-table-wrap">
								<table className="ssgsw-table">
									<thead>
										<tr>
											<th>{ __( 'SKU', TEXT_DOMAIN ) }</th>
											{ stores.map( ( s ) => <th key={ s.store_id } className="is-num">{ s.name }</th> ) }
											<th className="is-num">{ __( 'Total', TEXT_DOMAIN ) }</th>
											<th className="is-num">{ __( 'Days of cover', TEXT_DOMAIN ) }</th>
										</tr>
									</thead>
									<tbody>
										{ data.stock.slice( 0, 50 ).map( ( r ) => (
											<tr key={ r.sku }>
												<td>
													{ r.sku }
													{ r.drift && <span className="ssgsw-badge ssgsw-badge--warn" title={ __( 'Stores that share stock show different numbers.', TEXT_DOMAIN ) }> { __( 'Differs', TEXT_DOMAIN ) }</span> }
												</td>
												{ stores.map( ( s ) => <td key={ s.store_id } className="is-num">{ r.stores[ s.store_id ] === undefined ? '–' : num( r.stores[ s.store_id ] ) }</td> ) }
												<td className="is-num">{ num( r.total_stock ) }</td>
												<td className="is-num">{ r.days_of_cover === null ? '–' : num( r.days_of_cover, 1 ) }</td>
											</tr>
										) ) }
									</tbody>
								</table>
							</div>
						</Card>
					) }

					{ ( data.unmatched || [] ).length > 0 && (
						<Card title={ sprintf( __( 'Unmatched SKUs (%d)', TEXT_DOMAIN ), data.unmatched.length ) }>
							<p className="ssgsw-analytics-muted">{ __( 'These products are on a connected store but not on this store, or have no SKU. They are counted under their own store only.', TEXT_DOMAIN ) }</p>
							<ul className="ssgsw-an-list">
								{ data.unmatched.slice( 0, 50 ).map( ( u ) => (
									<li key={ `${ u.sku }-${ u.stores.join( ',' ) }` }>
										<strong>{ u.sku }</strong> { u.product } — { u.stores.map( nameOf ).join( ', ' ) }
										{ u.reason === 'no_sku' ? ` (${ __( 'no SKU', TEXT_DOMAIN ) })` : '' }
									</li>
								) ) }
							</ul>
						</Card>
					) }
				</Fragment>
			) }
		</div>
	);
}
