import { useState } from '@wordpress/element';
import { __, _n, sprintf } from '@wordpress/i18n';
import { useNavigate } from 'react-router-dom';
import { Card, EmptyState, ErrorBox, rangeDates, settingsPath, useReport } from './common';
import PageHeader from './ui/PageHeader';
import { SkeletonCard, SkeletonRegion } from './ui/Skeleton';
import { shiftToLatest } from './ui/rangeUtils';
import { BarList, LineChart } from './charts';
import { askReport, fetchReportOptions, runReport } from './api_expansion';
import { downloadCsv, money, niceDate, num, rangePhrase, rangeText } from './format';

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

const TIME_DIMS = [ 'date', 'week', 'month' ];

const DEFAULT_SPEC = {
	dimensions: [ 'sku' ],
	metrics: [ 'units', 'net' ],
	filters: { from: '', to: '', status: [], sku: '', category: '', country: '' },
	sort: { by: 'units', dir: 'desc' },
	limit: 50,
};

const splitList = ( text ) => String( text || '' ).split( ',' ).map( ( s ) => s.trim() ).filter( Boolean );

/** Spec from the form state (empty filters left out so the server defaults apply). */
const toSpec = ( form ) => {
	const f = form.filters;
	const filters = {};
	if ( f.from ) {
		filters.from = f.from;
	}
	if ( f.to ) {
		filters.to = f.to;
	}
	if ( f.status.length ) {
		filters.status = f.status;
	}
	[ 'sku', 'category', 'country' ].forEach( ( k ) => {
		const list = splitList( f[ k ] );
		if ( list.length ) {
			filters[ k ] = list;
		}
	} );
	return {
		...( form.title ? { title: form.title } : {} ),
		dimensions: form.dimensions,
		metrics: form.metrics,
		filters,
		sort: form.sort,
		limit: Number( form.limit ) || 50,
	};
};

/** Form state from a spec the server returned (after an AI question). */
const fromSpec = ( spec ) => ( {
	title: spec.title || '',
	dimensions: spec.dimensions || [],
	metrics: spec.metrics || [],
	filters: {
		from: ( spec.filters && spec.filters.from ) || '',
		to: ( spec.filters && spec.filters.to ) || '',
		status: ( spec.filters && spec.filters.status ) || [],
		sku: ( ( spec.filters && spec.filters.sku ) || [] ).join( ', ' ),
		category: ( ( spec.filters && spec.filters.category ) || [] ).join( ', ' ),
		country: ( ( spec.filters && spec.filters.country ) || [] ).join( ', ' ),
	},
	sort: spec.sort || DEFAULT_SPEC.sort,
	limit: spec.limit || 50,
} );

/** Cell text for a column format. */
export const formatCell = ( value, col, currency ) => {
	if ( value === null || value === undefined || value === '' ) {
		return '–';
	}
	switch ( col.format ) {
		case 'money':
			return money( value, currency );
		case 'number':
			return num( value );
		case 'date':
			return niceDate( value );
		case 'month': {
			const [ y, m ] = String( value ).split( '-' ).map( Number );
			return y && m ? new Date( Date.UTC( y, m - 1, 1 ) ).toLocaleDateString( undefined, { timeZone: 'UTC', month: 'short', year: 'numeric' } ) : String( value );
		}
		default:
			return String( value );
	}
};

/** Results table with totals (also used by the locked preview). */
export function ResultTable( { result } ) {
	const cols = result.columns || [];
	const firstMetric = cols.findIndex( ( c ) => c.type === 'metric' );
	return (
		<div className="ssgsw-table-wrap">
			<table className="ssgsw-table ssgsw-rb-table">
				<thead>
					<tr>
						{ cols.map( ( c ) => <th key={ c.key } className={ c.type === 'metric' ? 'is-num' : '' }>{ c.label }</th> ) }
					</tr>
				</thead>
				<tbody>
					{ result.rows.map( ( r, i ) => (
						<tr key={ i }>
							{ cols.map( ( c ) => (
								<td key={ c.key } className={ c.type === 'metric' ? 'is-num' : c.key === 'product' ? 'ssgsw-table__product' : '' }>
									{ c.key === 'product' ? <span title={ r[ c.key ] }>{ formatCell( r[ c.key ], c, result.currency ) }</span> : formatCell( r[ c.key ], c, result.currency ) }
								</td>
							) ) }
						</tr>
					) ) }
				</tbody>
				{ result.totals && firstMetric > 0 && (
					<tfoot>
						<tr>
							<th colSpan={ firstMetric }>{ __( 'Total', TEXT_DOMAIN ) }</th>
							{ cols.slice( firstMetric ).map( ( c ) => (
								<th key={ c.key } className="is-num">{ formatCell( result.totals[ c.key ], c, result.currency ) }</th>
							) ) }
						</tr>
					</tfoot>
				) }
			</table>
		</div>
	);
}

/** Small chart for the result: a line for one time dimension, bars for one other dimension. */
function ResultChart( { result } ) {
	const dims = result.spec.dimensions;
	const metric = result.columns.find( ( c ) => c.type === 'metric' );
	if ( dims.length !== 1 || ! metric || result.rows.length < 2 ) {
		return null;
	}
	const fmt = ( v ) => formatCell( v, metric, result.currency );
	if ( TIME_DIMS.includes( dims[ 0 ] ) ) {
		const rows = [ ...result.rows ].sort( ( a, b ) => String( a[ dims[ 0 ] ] ).localeCompare( String( b[ dims[ 0 ] ] ) ) );
		return (
			<LineChart
				labels={ rows.map( ( r ) => formatCell( r[ dims[ 0 ] ], result.columns[ 0 ], result.currency ) ) }
				series={ [ { name: metric.label, values: rows.map( ( r ) => Number( r[ metric.key ] ) || 0 ), area: true } ] }
				format={ fmt }
				ariaLabel={ sprintf( __( '%1$s by %2$s', TEXT_DOMAIN ), metric.label, result.columns[ 0 ].label ) }
			/>
		);
	}
	return (
		<BarList
			ariaLabel={ sprintf( __( '%1$s by %2$s', TEXT_DOMAIN ), metric.label, result.columns[ 0 ].label ) }
			rows={ result.rows.slice( 0, 10 ).map( ( r ) => ( { label: String( r[ dims[ 0 ] ] ?? '–' ), sub: r.product || '', value: Number( r[ metric.key ] ) || 0 } ) ) }
			format={ fmt }
		/>
	);
}

/** Toggle chips for dimensions / metrics. */
function ChipGroup( { legend, options, value, onToggle, disabledFor } ) {
	return (
		<fieldset className="ssgsw-analytics-chips ssgsw-rb-chips">
			<legend className="ssgsw-analytics-field__label">{ legend }</legend>
			<div className="ssgsw-analytics-chips__list">
				{ options.map( ( o ) => {
					const on = value.includes( o.key );
					const disabled = ! on && disabledFor && disabledFor( o.key );
					return (
						<label key={ o.key } className={ `ssgsw-analytics-chip${ on ? ' is-on' : '' }${ disabled ? ' is-disabled' : '' }` }>
							<input type="checkbox" className="screen-reader-text" checked={ on } disabled={ disabled } onChange={ () => onToggle( o.key ) } />
							<span>{ o.label }</span>
						</label>
					);
				} ) }
			</div>
		</fieldset>
	);
}

/**
 * Reports tab: build a report from dimensions, metrics and filters, or type a question (needs AI),
 * then see the table, a quick chart and download it as CSV.
 */
export default function Reports( { range, setRange } ) {
	const navigate = useNavigate();
	const opts = useReport( fetchReportOptions, [] );
	const [ form, setForm ] = useState( { ...DEFAULT_SPEC, title: '' } );
	const [ question, setQuestion ] = useState( '' );
	const [ busy, setBusy ] = useState( '' ); // '' | 'run' | 'ask'
	const [ result, setResult ] = useState( null );
	const [ runError, setRunError ] = useState( null ); // { message, code }

	const header = (
		<PageHeader
			title={ __( 'Custom reports', TEXT_DOMAIN ) }
			description={ __( 'Build your own table: choose what to group by and what to show, then download it.', TEXT_DOMAIN ) }
			range={ range }
			setRange={ setRange }
			showCompare={ false }
		/>
	);
	if ( opts.loading && ! opts.data ) {
		return <div className="ssgsw-an-screen">{ header }<SkeletonRegion><div className="ssgsw-rb-layout"><SkeletonCard lines={ 8 } /><SkeletonCard chart height={ 260 } /></div></SkeletonRegion></div>;
	}
	if ( opts.error ) {
		return <div className="ssgsw-an-screen">{ header }<ErrorBox message={ opts.error } onRetry={ opts.reload } /></div>;
	}
	const o = opts.data;
	const maxDims = o.max_dims || 2;
	const aiOn = !! o.ai_configured;

	const patch = ( p ) => setForm( ( f ) => ( { ...f, ...p } ) );
	const patchFilter = ( p ) => setForm( ( f ) => ( { ...f, filters: { ...f.filters, ...p } } ) );
	const sortable = [ ...form.dimensions, ...form.metrics ];
	const labelOf = ( key ) => {
		const c = [ ...o.dimensions, ...o.metrics ].find( ( x ) => x.key === key );
		return c ? c.label : key;
	};
	// Keep the sort column valid when a dimension or metric is removed.
	const fixSort = ( next ) => {
		const keys = [ ...next.dimensions, ...next.metrics ];
		if ( keys.includes( next.sort.by ) ) {
			return next;
		}
		const time = next.dimensions.find( ( d ) => TIME_DIMS.includes( d ) );
		return { ...next, sort: time ? { by: time, dir: 'asc' } : { by: next.metrics[ 0 ] || keys[ 0 ] || '', dir: 'desc' } };
	};
	const toggleDim = ( key ) => setForm( ( f ) => fixSort( { ...f, dimensions: f.dimensions.includes( key ) ? f.dimensions.filter( ( d ) => d !== key ) : [ ...f.dimensions, key ] } ) );
	const toggleMetric = ( key ) => setForm( ( f ) => fixSort( { ...f, metrics: f.metrics.includes( key ) ? f.metrics.filter( ( m ) => m !== key ) : [ ...f.metrics, key ] } ) );
	const hasTime = form.dimensions.some( ( d ) => TIME_DIMS.includes( d ) );

	// The report period follows the shared range bar (7 / 14 / 28 / 90 days or a custom range).
	const [ dFrom, dTo ] = rangeDates( range );
	const run = async ( dates ) => {
		const [ f, t ] = dates || [ dFrom, dTo ];
		setBusy( 'run' );
		setRunError( null );
		try {
			setResult( await runReport( toSpec( { ...form, filters: { ...form.filters, from: f, to: t } } ) ) );
		} catch ( e ) {
			setRunError( { message: e.message, code: e.code } );
		} finally {
			setBusy( '' );
		}
	};

	const ask = async ( text ) => {
		const q = ( text ?? question ).trim();
		if ( ! q ) {
			return;
		}
		setQuestion( q );
		setBusy( 'ask' );
		setRunError( null );
		try {
			const res = await askReport( q );
			setResult( res );
			if ( res.spec ) {
				setForm( fromSpec( res.spec ) );
				const sf = res.spec.filters || {};
				if ( sf.from && sf.to ) {
					const span = Math.round( ( Date.parse( sf.to ) - Date.parse( sf.from ) ) / 86400000 ) + 1;
					setRange( { ...range, from: sf.from, to: sf.to, days: span, auto: false, stay: false } );
				}
			}
		} catch ( e ) {
			setRunError( { message: e.message, code: e.code } );
		} finally {
			setBusy( '' );
		}
	};

	const exportCsv = () => {
		const cols = result.columns;
		downloadCsv(
			`flexstock-report-${ result.from }-${ result.to }.csv`,
			cols.map( ( c ) => c.label ),
			result.rows.map( ( r ) => cols.map( ( c ) => ( r[ c.key ] === null || r[ c.key ] === undefined ? '' : r[ c.key ] ) ) )
		);
	};

	const canRun = form.metrics.length > 0 && ! busy;
	const aiBlocked = runError && /^ai_(not_configured|paused|daily_limit|budget)/.test( runError.code || '' );

	return (
		<div className="ssgsw-an-screen">
			{ header }
			<Card title={ __( 'Ask in plain words', TEXT_DOMAIN ) } className="ssgsw-rb-ask">
				{ aiOn ? (
					<>
						<form
							className="ssgsw-rb-ask__row"
							onSubmit={ ( e ) => {
								e.preventDefault();
								ask();
							} }
						>
							<label htmlFor="ssgsw-rb-question" className="screen-reader-text">{ __( 'Your question', TEXT_DOMAIN ) }</label>
							<input
								id="ssgsw-rb-question"
								type="text"
								className="ssgsw-analytics-input"
								maxLength={ 600 }
								placeholder={ __( 'e.g. Top 20 SKUs by net sales last month', TEXT_DOMAIN ) }
								value={ question }
								onChange={ ( e ) => setQuestion( e.target.value ) }
							/>
							<button type="submit" className="ssgsw-analytics-btn ssgsw-analytics-btn--primary" disabled={ !! busy || ! question.trim() }>
								{ busy === 'ask' ? __( 'Building…', TEXT_DOMAIN ) : __( 'Build report', TEXT_DOMAIN ) }
							</button>
						</form>
						{ Array.isArray( o.examples ) && o.examples.length > 0 && (
							<div className="ssgsw-rb-examples">
								<span className="ssgsw-analytics-muted">{ __( 'Try:', TEXT_DOMAIN ) }</span>
								{ o.examples.map( ( ex ) => (
									<button key={ ex } type="button" className="ssgsw-rb-example" onClick={ () => ask( ex ) } disabled={ !! busy }>{ ex }</button>
								) ) }
							</div>
						) }
						<p className="ssgsw-an-foot">{ __( 'The AI only picks the fields below; your data is read by WordPress, never sent as rows. Each question uses one AI request (repeated questions are cached for an hour).', TEXT_DOMAIN ) }</p>
					</>
				) : (
					<div className="ssgsw-rb-ai-off">
						<span className="dashicons dashicons-format-chat" aria-hidden="true"></span>
						<div>
							<strong>{ __( 'Questions need AI, which is not set up', TEXT_DOMAIN ) }</strong>
							<p>{ __( 'Set up the AI assistant to type questions like “weekly units per category”. You can still build any report with the options below.', TEXT_DOMAIN ) }</p>
						</div>
						<button type="button" className="ssgsw-analytics-btn ssgsw-analytics-btn--secondary" onClick={ () => navigate( settingsPath() ) }>{ __( 'Set up AI', TEXT_DOMAIN ) }</button>
					</div>
				) }
			</Card>

			<div className="ssgsw-rb-layout">
			<Card title={ __( 'Build a report', TEXT_DOMAIN ) } subtitle={ sprintf( __( 'Period: %s. Change it with the date button above.', TEXT_DOMAIN ), rangeText( dFrom, dTo ) ) } className="ssgsw-rb-builder">
				<div className="ssgsw-rb-grid">
					<ChipGroup
						legend={ sprintf( __( 'Group by (up to %d)', TEXT_DOMAIN ), maxDims ) }
						options={ o.dimensions }
						value={ form.dimensions }
						onToggle={ toggleDim }
						disabledFor={ ( key ) => form.dimensions.length >= maxDims || ( hasTime && TIME_DIMS.includes( key ) ) }
					/>
					<ChipGroup legend={ __( 'Show', TEXT_DOMAIN ) } options={ o.metrics } value={ form.metrics } onToggle={ toggleMetric } />
				</div>
				{ ! form.dimensions.length && <p className="ssgsw-analytics-muted">{ __( 'No grouping: one row with the totals for the whole period.', TEXT_DOMAIN ) }</p> }

				<div className="ssgsw-analytics-grid ssgsw-rb-filters">
					<div className="ssgsw-analytics-field">
						<label htmlFor="ssgsw-rb-sku" className="ssgsw-analytics-field__label">{ __( 'Only these SKUs', TEXT_DOMAIN ) }</label>
						<input id="ssgsw-rb-sku" type="text" className="ssgsw-analytics-input" placeholder={ __( 'Comma separated', TEXT_DOMAIN ) } value={ form.filters.sku } onChange={ ( e ) => patchFilter( { sku: e.target.value } ) } />
					</div>
					<div className="ssgsw-analytics-field">
						<label htmlFor="ssgsw-rb-cat" className="ssgsw-analytics-field__label">{ __( 'Only these categories', TEXT_DOMAIN ) }</label>
						<input id="ssgsw-rb-cat" type="text" className="ssgsw-analytics-input" placeholder={ __( 'Comma separated', TEXT_DOMAIN ) } value={ form.filters.category } onChange={ ( e ) => patchFilter( { category: e.target.value } ) } />
					</div>
					<div className="ssgsw-analytics-field">
						<label htmlFor="ssgsw-rb-country" className="ssgsw-analytics-field__label">{ __( 'Only these countries', TEXT_DOMAIN ) }</label>
						<input id="ssgsw-rb-country" type="text" className="ssgsw-analytics-input" placeholder={ __( 'e.g. US, GB', TEXT_DOMAIN ) } value={ form.filters.country } onChange={ ( e ) => patchFilter( { country: e.target.value } ) } />
					</div>
				</div>

				<fieldset className="ssgsw-analytics-chips ssgsw-rb-chips">
					<legend className="ssgsw-analytics-field__label">{ __( 'Order statuses (none chosen = the statuses counted in Settings)', TEXT_DOMAIN ) }</legend>
					<div className="ssgsw-analytics-chips__list">
						{ o.statuses.map( ( s ) => {
							const on = form.filters.status.includes( s.value );
							return (
								<label key={ s.value } className={ `ssgsw-analytics-chip${ on ? ' is-on' : '' }` }>
									<input
										type="checkbox"
										className="screen-reader-text"
										checked={ on }
										onChange={ () => patchFilter( { status: on ? form.filters.status.filter( ( x ) => x !== s.value ) : [ ...form.filters.status, s.value ] } ) }
									/>
									<span>{ s.label }</span>
								</label>
							);
						} ) }
					</div>
				</fieldset>

				<div className="ssgsw-analytics-grid ssgsw-rb-filters">
					<div className="ssgsw-analytics-field">
						<label htmlFor="ssgsw-rb-sort" className="ssgsw-analytics-field__label">{ __( 'Sort by', TEXT_DOMAIN ) }</label>
						<select id="ssgsw-rb-sort" className="ssgsw-analytics-input" value={ form.sort.by } onChange={ ( e ) => patch( { sort: { ...form.sort, by: e.target.value } } ) }>
							{ sortable.map( ( k ) => <option key={ k } value={ k }>{ labelOf( k ) }</option> ) }
						</select>
					</div>
					<div className="ssgsw-analytics-field">
						<label htmlFor="ssgsw-rb-dir" className="ssgsw-analytics-field__label">{ __( 'Order', TEXT_DOMAIN ) }</label>
						<select id="ssgsw-rb-dir" className="ssgsw-analytics-input" value={ form.sort.dir } onChange={ ( e ) => patch( { sort: { ...form.sort, dir: e.target.value } } ) }>
							<option value="desc">{ __( 'Highest first', TEXT_DOMAIN ) }</option>
							<option value="asc">{ __( 'Lowest / oldest first', TEXT_DOMAIN ) }</option>
						</select>
					</div>
					<div className="ssgsw-analytics-field">
						<label htmlFor="ssgsw-rb-limit" className="ssgsw-analytics-field__label">{ __( 'Rows', TEXT_DOMAIN ) }</label>
						<input id="ssgsw-rb-limit" type="number" min={ 1 } max={ o.max_limit || 500 } className="ssgsw-analytics-input" value={ form.limit } onChange={ ( e ) => patch( { limit: e.target.value === '' ? '' : Math.max( 1, Math.min( o.max_limit || 500, Number( e.target.value ) ) ) } ) } />
					</div>
				</div>

				<div className="ssgsw-rb-actions">
					<button type="button" className="ssgsw-analytics-btn ssgsw-analytics-btn--primary" onClick={ () => run() } disabled={ ! canRun }>
						{ busy === 'run' ? __( 'Running…', TEXT_DOMAIN ) : __( 'Run report', TEXT_DOMAIN ) }
					</button>
					<button type="button" className="ssgsw-analytics-btn ssgsw-analytics-btn--secondary" onClick={ () => { setForm( { ...DEFAULT_SPEC, title: '' } ); setResult( null ); setRunError( null ); } } disabled={ !! busy }>
						{ __( 'Reset', TEXT_DOMAIN ) }
					</button>
					{ ! form.metrics.length && <span className="ssgsw-analytics-muted">{ __( 'Choose at least one value to show.', TEXT_DOMAIN ) }</span> }
				</div>
			</Card>

			<div className="ssgsw-rb-layout__result">
			{ ! result && ! runError && ! busy && (
				<EmptyState title={ __( 'Your report will appear here', TEXT_DOMAIN ) }>{ __( 'Choose what to group by and show, then press Run report.', TEXT_DOMAIN ) }</EmptyState>
			) }
			{ runError && aiBlocked && (
				<EmptyState
					title={ __( 'AI is not available right now', TEXT_DOMAIN ) }
					action={ <button type="button" className="ssgsw-analytics-btn ssgsw-analytics-btn--secondary" onClick={ () => navigate( settingsPath() ) }>{ __( 'Open AI settings', TEXT_DOMAIN ) }</button> }
				>
					{ runError.message }
				</EmptyState>
			) }
			{ runError && ! aiBlocked && (
				<div className="ssgsw-an-state ssgsw-an-state--error" role="alert">
					<strong>{ __( 'The report could not be built.', TEXT_DOMAIN ) }</strong>
					<span>{ runError.message }</span>
				</div>
			) }
			{ busy && ! result && <SkeletonRegion label={ busy === 'ask' ? __( 'Asking the AI for the report fields…', TEXT_DOMAIN ) : __( 'Running the report…', TEXT_DOMAIN ) }><SkeletonCard chart height={ 200 } /></SkeletonRegion> }

			{ result && (
				<Card
					className={ busy ? 'is-refreshing' : '' }
					title={ result.spec && result.spec.title ? result.spec.title : __( 'Results', TEXT_DOMAIN ) }
					actions={ result.rows.length ? <button type="button" className="ssgsw-analytics-btn ssgsw-analytics-btn--secondary" onClick={ exportCsv }>{ __( 'Download CSV', TEXT_DOMAIN ) }</button> : null }
				>
					<p className="ssgsw-analytics-muted ssgsw-rb-meta">
						{ rangeText( result.from, result.to ) }
						{ ' · ' }
						{ sprintf( _n( '%d row', '%d rows', Number( result.total_rows ) || 0, TEXT_DOMAIN ), result.total_rows ) }
						{ result.truncated ? ` · ${ sprintf( _n( 'showing the first row', 'showing the first %d', result.rows.length, TEXT_DOMAIN ), result.rows.length ) }` : '' }
						{ result.question ? ` · ${ sprintf( __( 'Built by AI from “%s”', TEXT_DOMAIN ), result.question ) }${ result.ai && result.ai.cached ? ` ${ __( '(cached)', TEXT_DOMAIN ) }` : '' }` : '' }
					</p>
					{ result.rows.length ? (
						<>
							<ResultChart result={ result } />
							<ResultTable result={ result } />
						</>
					) : (
						<EmptyState
							title={ __( 'No rows', TEXT_DOMAIN ) }
							action={ result.latest_sale_date && result.latest_sale_date < result.from ? (
								<button
									type="button"
									className="ssgsw-analytics-btn ssgsw-analytics-btn--primary"
									onClick={ () => {
										const next = shiftToLatest( { ...range, latest: result.latest_sale_date } );
										setRange( next );
										run( rangeDates( next ) );
									} }
								>
									{ __( 'Show my latest sales', TEXT_DOMAIN ) }
								</button>
							) : null }
						>
							{ result.latest_sale_date && result.latest_sale_date < result.from
								? sprintf( __( 'No sales %1$s. The latest sale was on %2$s.', TEXT_DOMAIN ), rangePhrase( result.from, result.to ), niceDate( result.latest_sale_date ) )
								: __( 'Nothing matched these filters in this period. Widen the dates or remove a filter.', TEXT_DOMAIN ) }
						</EmptyState>
					) }
					{ result.spec && result.spec.metrics && result.spec.metrics.includes( 'margin' ) && (
						<p className="ssgsw-an-foot">{ __( 'Gross margin = net sales − cost. Cost comes from the cost field or the default margin set in Settings; it is empty when neither is set.', TEXT_DOMAIN ) }</p>
					) }
				</Card>
			) }
			</div>
			</div>
		</div>
	);
}
