/* global mixpanel */

/**
 * Reports — Reports & Export tab.
 *
 * @since 1.0.273
 */

/**
 * External dependencies
 */
import { round } from 'lodash'

/**
 * WordPress dependencies
 */
import { useState, useCallback, useMemo, useEffect, useRef } from '@wordpress/element'
import { __ } from '@wordpress/i18n'
import { SelectControl, Notice } from '@wordpress/components'

/**
 * Internal dependencies
 */
import { getInsights } from '../shared/services/api/aiVisibilityApi'
import { TableSkeleton } from '@rank-math/components'
import { Button, LoadingButton, RankBadge, SentimentBadge, SectionHeader, ScoreBadge, DataTable, CountBadge } from '../shared/components'
import useDashboard from '../shared/hooks/useDashboard'
import { getReportBrandParam } from '../utils/urlState'
import { formatDateTime } from '../utils/formatDate'
import downloadJson from '../utils/downloadJson'
import { HelpTooltip } from '@rank-math/components'
import './Reports.scss'

/**
 * ReportStatCard component.
 *
 * @param {Object}             props
 * @param {string}             props.icon        Dashicon class suffix.
 * @param {string}             props.label       Card label.
 * @param {string|number|null} props.value       Numeric value or null for N/A.
 * @param {string}             props.iconBg      CSS background for the icon circle.
 * @param {string}             props.iconColor   Icon colour hex.
 * @param {string}             props.tooltip     Tooltip text for the help icon.
 * @param {string}             [props.className] Optional additional class(es) for the root.
 * @return {JSX.Element} Report stat card.
 */
const ReportStatCard = ( { icon, label, value, iconBg, iconColor, tooltip, className } ) => {
	const ns = 'rank-math-ai-visibility-reports'

	return (
		<div className={ `${ ns }__stat-card${ className ? ` ${ className }` : '' }` }>
			<div
				className={ `${ ns }__stat-icon` }
				style={ { background: iconBg } }
			>
				<span
					className={ `dashicons dashicons-${ icon }` }
					style={ { color: iconColor } }
					aria-hidden="true"
				/>
			</div>
			<div className={ `${ ns }__stat-body` }>
				<span className={ `${ ns }__stat-label` }>
					{ label }
					<HelpTooltip text={ tooltip } />
				</span>
				<span className={ `${ ns }__stat-value${ value === null || value === undefined ? ` ${ ns }__stat-value--na` : '' }` }>
					{ value !== null && value !== undefined ? value : 'N/A' }
				</span>
			</div>
		</div>
	)
}

/**
 * Reports component.
 *
 * @return {JSX.Element} Two-panel reports view.
 */
const Reports = () => {
	const ns = 'rank-math-ai-visibility-reports'

	const { brands, summary: dashboardSummary } = useDashboard()
	const SELECT_BRAND_LABEL = __( 'Select Brand', 'seo-by-rank-math' )
	const brandOptions = useMemo( () => [
		{ label: SELECT_BRAND_LABEL, value: '' },
		...brands.map( ( b ) => ( { label: b.name, value: String( b.id ) } ) ),
	], [ brands ] )

	const [ filters, setFilters ] = useState( () => ( {
		brandId: getReportBrandParam(),
	} ) )
	const setFilter = ( key ) => ( value ) => setFilters( ( prev ) => ( { ...prev, [ key ]: value } ) )

	const [ report, setReport ] = useState( null )
	const [ reportBrand, setReportBrand ] = useState( null )
	const [ loading, setLoading ] = useState( false )
	const [ error, setError ] = useState( null )

	const autoGeneratedRef = useRef( false )
	useEffect( () => {
		if ( ! autoGeneratedRef.current && filters.brandId && brands.length > 0 ) {
			autoGeneratedRef.current = true
			handleGenerate()
		}
	}, [ brands ] )

	// Phase 1: one report row per brand, built client-side from cached data
	// (latest analysis only). Date-range history awaits the Phase 2 endpoint.
	const handleGenerate = useCallback( async () => {
		setLoading( true )
		setError( null )
		setReportBrand( brands.find( ( b ) => String( b.id ) === filters.brandId ) || null )
		try {
			const selected = ( filters.brandId
				? brands.filter( ( b ) => String( b.id ) === filters.brandId )
				: brands
			).filter( ( b ) => b.last_analyzed )

			const rows = selected.map( ( b ) => ( {
				id: b.id,
				score: b.score,
				rank: b.rank,
				sentiment: b.avg_sentiment,
				mentions: b.mentions,
				citations: b.citations,
				competitors: [],
				date: b.last_analyzed,
			} ) )

			// Single-brand report: enrich with competitor names from the
			// cached insights payload.
			if ( filters.brandId && rows.length ) {
				try {
					const data = await getInsights( filters.brandId )
					rows[ 0 ].competitors = ( data?.insights?.competitors ?? [] ).map( ( c ) => c.name )
					rows[ 0 ].queries = ( data?.insights?.query_results ?? [] ).map( ( q ) => ( {
						query: q.query_text ?? '',
						response: q.response ?? '',
					} ) )
				} catch {
					// Competitors and queries are nice-to-have in the report — ignore.
				}
			}

			const sum = ( key ) => rows.reduce( ( s, r ) => s + ( r[ key ] ?? 0 ), 0 )
			const reportData = {
				summary: {
					score: filters.brandId
						? rows[ 0 ]?.score ?? null
						: dashboardSummary?.rank_score ?? null,
					avg_sentiment: rows.length
						? Math.round( sum( 'sentiment' ) / rows.length )
						: null,
					total_mentions: sum( 'mentions' ),
					total_citations: sum( 'citations' ),
				},
				details: rows,
			}
			setReport( reportData )

			if ( rankMath.tracking ) {
				const { plugin, email, language, path } = rankMath.tracking
				mixpanel.identify( email )
				mixpanel.track( 'AI Visibility Report Generated', {
					has_data: rows.length > 0,
					context: 'wp_plugin',
					brand: 'rankmath',
					application: 'rankmath',
					plugin,
					path,
					language,
				} )
			}
		} catch ( err ) {
			setError( err?.message || __( 'Failed to generate report.', 'seo-by-rank-math' ) )
		} finally {
			setLoading( false )
		}
	}, [ filters, brands, dashboardSummary ] )

	const summary = report?.summary ?? {}
	const rows = report?.details ?? []

	const previewSubtitle = useMemo( () => {
		return reportBrand ? reportBrand.name : ''
	}, [ reportBrand ] )

	return (
		<div className={ ns }>
			<SectionHeader
				title={ __( 'Reports & Export', 'seo-by-rank-math' ) }
				subtitle={ __( 'Export daily aggregates for a brand.', 'seo-by-rank-math' ) }
			/>

			<div className={ `${ ns }__layout` }>
				<aside className={ `${ ns }__filters` }>

					{ /* Panel header */ }
					<div className={ `${ ns }__filters-header` }>
						<span className="dashicons dashicons-filter" aria-hidden="true" />
						<div>
							<p className={ `${ ns }__filters-title` }>
								{ __( 'Filters', 'seo-by-rank-math' ) }
							</p>
							<p className={ `${ ns }__filters-subtitle` }>
								{ __( 'Select brand and format.', 'seo-by-rank-math' ) }
							</p>
						</div>
					</div>

					{ /* Panel body — form fields + CTA */ }
					<div className={ `${ ns }__filters-body` }>

						{ /* Brand — SelectControl renders its own associated label */ }
						<div className={ `${ ns }__filter-field` }>
							<SelectControl
								label={ __( 'BRAND', 'seo-by-rank-math' ) }
								value={ filters.brandId }
								options={ brandOptions }
								onChange={ ( value ) => {
									setFilter( 'brandId' )( value )
									if ( ! value ) {
										setReport( null )
										setReportBrand( null )
										setError( null )
									}
								} }
								__next40pxDefaultSize={ true }
								__nextHasNoMarginBottom={ true }
							/>
						</div>

						<LoadingButton
							className={ `${ ns }__generate-btn` }
							onClick={ handleGenerate }
							isLoading={ loading }
							loadingLabel={ __( 'Generating…', 'seo-by-rank-math' ) }
							disabled={ ! filters.brandId }
						>
							{ __( 'Generate preview', 'seo-by-rank-math' ) }
						</LoadingButton>

					</div>

				</aside>

				{ /* ── Right: preview panel ── */ }
				<div className={ `${ ns }__preview` }>

					{ error && (
						<Notice status="error" isDismissible={ false }>
							{ error }
						</Notice>
					) }

					{ loading && <TableSkeleton columns={ 5 } rows={ 4 } /> }

					{ ! report && ! loading && ! error && (
						<div className={ `${ ns }__empty` }>
							<p>{ __( 'Select a brand, then click "Generate preview".', 'seo-by-rank-math' ) }</p>
						</div>
					) }

					{ report && (
						<div className={ `${ ns }__report-card` }>

							{ /* Card header: chart icon + title/subtitle + actions */ }
							<div className={ `${ ns }__preview-header` }>
								<div className={ `${ ns }__preview-title-row` }>
									<span className="dashicons dashicons-chart-bar" aria-hidden="true" />
									<div>
										<p className={ `${ ns }__preview-title` }>
											{ __( 'Preview', 'seo-by-rank-math' ) }
										</p>
										{ previewSubtitle && (
											<p className={ `${ ns }__preview-subtitle` }>
												{ previewSubtitle }
											</p>
										) }
									</div>
								</div>
								<div className={ `${ ns }__preview-actions` }>
									<Button
										variant="secondary"
										onClick={ () => {
											downloadJson( report, 'ai-visibility-report.json' )
											if ( rankMath.tracking ) {
												const { plugin, email, language, path } = rankMath.tracking
												mixpanel.identify( email )
												mixpanel.track( 'Button Clicked', {
													button: 'Download AI Visibility Report',
													context: 'wp_plugin',
													brand: 'rankmath',
													application: 'rankmath',
													plugin,
													path,
													language,
												} )
											}
										} }
									>
										{ __( 'Download JSON', 'seo-by-rank-math' ) }
									</Button>
								</div>
							</div>

							{ /* Card body: stat cards + table */ }
							<div className={ `${ ns }__report-card-body` }>

								{ /* Stat cards */ }
								<div className={ `${ ns }__stat-cards` }>
									<ReportStatCard
										icon=" rm-icon-ai-visibility"
										className="rank-math-ai-visibility-reports-overall-score"
										label={ __( 'Global AI Visibility Score', 'seo-by-rank-math' ) }
										value={ summary.score !== null && summary.score !== undefined
											? `${ summary.score }/100`
											: null
										}
										iconBg="rgba(1,124,186,0.12)"
										iconColor="#017CBA"
										tooltip={ __( 'The overall AI Visibility Score for the selected brand and date range, calculated based on the volume of mentions, sentiment, and other factors.', 'seo-by-rank-math' ) }
									/>
									<ReportStatCard
										icon="smiley"
										className="rank-math-ai-visibility-reports-overall-sentiment"
										label={ __( 'Avg Sentiment', 'seo-by-rank-math' ) }
										value={ summary.avg_sentiment !== null && summary.avg_sentiment !== undefined ? `${ round( summary.avg_sentiment ) }%` : null }
										iconBg="rgba(82,96,185,0.12)"
										iconColor="#5260B9"
										tooltip={ __( 'The average sentiment score across all AI mentions for the selected brand and date range. Calculated by analyzing the sentiment of each mention and averaging the scores.', 'seo-by-rank-math' ) }
									/>
									<ReportStatCard
										icon=" rm-icon-comments"
										className="rank-math-ai-visibility-reports-total-mentions"
										label={ __( 'Total Mentions', 'seo-by-rank-math' ) }
										value={ summary.total_mentions ?? 0 }
										iconBg="rgba(255,171,64,0.15)"
										iconColor="#F59E0B"
										tooltip={ __( 'The total number of AI-generated mentions of the selected brand within the specified date range.', 'seo-by-rank-math' ) }
									/>
									<ReportStatCard
										icon=" rm-icon-misc"
										className="rank-math-ai-visibility-reports-total-citations"
										label={ __( 'Total Citations', 'seo-by-rank-math' ) }
										value={ summary.total_citations ?? 0 }
										iconBg="rgba(66,178,104,0.15)"
										iconColor="#42B268"
										tooltip={ __( 'The total number of AI-generated mentions that include a link to the selected brand’s website within the specified date range.', 'seo-by-rank-math' ) }
									/>
								</div>

								{ /* Per-run data table */ }
								{ rows.length > 0 && (
									<DataTable
										columns={ [
											{
												key: 'score',
												label: __( 'AI Visibility Score', 'seo-by-rank-math' ),
												render: ( row ) => <ScoreBadge score={ row.score ?? null } />,
											},
											{
												key: 'rank',
												label: __( 'Avg Rank', 'seo-by-rank-math' ),
												render: ( row ) => <RankBadge rank={ row.rank ?? null } />,
											},
											{
												key: 'sentiment',
												label: __( 'Sentiment', 'seo-by-rank-math' ),
												render: ( row ) => <SentimentBadge score={ row.sentiment ?? null } />,
											},
											{
												key: 'mentions',
												label: __( 'Mentions', 'seo-by-rank-math' ),
												render: ( row ) => <CountBadge value={ row.mentions ?? null } variant="mentions" />,
											},
											{
												key: 'citations',
												label: __( 'Citations', 'seo-by-rank-math' ),
												render: ( row ) => <CountBadge value={ row.citations ?? null } variant="citations" />,
											},
											{
												key: 'competitors',
												label: __( 'Top competitors', 'seo-by-rank-math' ),
												render: ( row ) => (
													<div className={ `${ ns }__competitors` }>
														{ ( row.competitors || [] ).map( ( c ) => (
															<span key={ c } className={ `${ ns }__competitor-tag` }>{ c }</span>
														) ) }
													</div>
												),
											},
											{
												key: 'date',
												label: __( 'Date', 'seo-by-rank-math' ),
												render: ( row ) => formatDateTime( row.date ),
											},
										] }
										rows={ rows }
										rowKey={ ( row, i ) => row.id ?? i }
									/>
								) }

							</div>
						</div>
					) }

				</div>
			</div>
		</div>
	)
}

Reports.displayName = 'Reports'

export default Reports
