import { useCallback, useEffect, useState } from '@wordpress/element';
import { Cell, Pie, PieChart, ResponsiveContainer, Tooltip } from 'recharts';
import { loadDeviceBreakdown } from '../api';

const COLORS = { DESKTOP: '#6366f1', MOBILE: '#22c55e', TABLET: '#f97316' };

export function DeviceDonut( { initial, channels, days, i18n } ) {
	const [ channel, setChannel ] = useState( 'web' );
	const [ data, setData ] = useState( initial || [] );
	const [ loading, setLoading ] = useState( false );

	const load = useCallback( async ( ch ) => {
		setLoading( true );
		try {
			const rows = await loadDeviceBreakdown( days, ch );
			setData( rows );
		} finally {
			setLoading( false );
		}
	}, [ days ] );

	useEffect( () => {
		if ( channel === 'web' && initial?.length ) {
			setData( initial );
			return;
		}
		load( channel );
	}, [ channel, initial, load ] );

	const chartData = ( data || [] ).map( ( d ) => ( {
		name: d.label || d.device,
		value: d.clicks || 0,
		fill: d.color || COLORS[ d.device ] || '#94a3b8',
	} ) );

	return (
		<section className="nros-bento-card">
			<h3>{ i18n.devices }</h3>
			<div className="nros-device-chips">
				{ ( channels || [] ).map( ( ch ) => (
					<button
						key={ ch.id }
						type="button"
						className={ `nros-workflow__chip${ channel === ch.id ? ' is-active' : '' }` }
						onClick={ () => setChannel( ch.id ) }
					>
						{ ch.label }
					</button>
				) ) }
			</div>
			<div className={ `nros-donut-wrap${ loading ? ' is-loading' : '' }` }>
				{ chartData.length ? (
					<ResponsiveContainer width="100%" height={ 200 }>
						<PieChart>
							<Pie data={ chartData } dataKey="value" nameKey="name" innerRadius={ 55 } outerRadius={ 80 } paddingAngle={ 2 }>
								{ chartData.map( ( entry, i ) => (
									<Cell key={ i } fill={ entry.fill } />
								) ) }
							</Pie>
							<Tooltip />
						</PieChart>
					</ResponsiveContainer>
				) : (
					<p className="nros-empty-hint">{ i18n.no_devices }</p>
				) }
			</div>
			<ul className="nros-donut-legend">
				{ chartData.map( ( d ) => (
					<li key={ d.name }>
						<span className="nros-donut-legend__dot" style={ { background: d.fill } } />
						{ d.name } — { d.value }
					</li>
				) ) }
			</ul>
		</section>
	);
}
