import { defineStore } from 'pinia';

export const useStore = defineStore( 'simplestats-store', {
	state() {
		return {
			isNotificationOpen: false,
			notifications: {},
			addons: SimpleStatsVue.addons,
			range: { preset: '7d', from: null, to: null },
			report: {
				isLoading: false,
				loaded:    false,
				error:     null,
				data:      {},
			},
			realtime: {
				isLoading:  false,
				online:     0,
				activities: [],
				pollHandle: null,
			},
			connection: {
				status: 'idle',
				email: null,
				plan: SimpleStatsVue.connection?.plan || 'free',
				planName: SimpleStatsVue.connection?.plan_name || '',
				error: null,
				isFetching: false,
			},
			settings: {
				exclude_admins: SimpleStatsVue.settings?.exclude_admins ?? true,
				show_admin_bar_indicator: SimpleStatsVue.settings?.show_admin_bar_indicator ?? true,
				show_dashboard_widget: SimpleStatsVue.settings?.show_dashboard_widget ?? true,
			},
			saveStatus: 'idle',
			_saveStatusTimer: null,
		};
	},
	getters: {
		showNotification: ( state ) => state.isNotificationOpen,
		getNotification: ( state ) => state.notifications,
		getAddons: ( state ) => state.addons,
		getDashboardReport: ( state ) => state.report.data,
		hasReportData: ( state ) => {
			if ( ! state.report.loaded ) {
				return false;
			}
			const k = state.report.data?.kpis || {};
			return Number( k.visitors?.value ) > 0 || Number( k.pageviews?.value ) > 0;
		},
		currentRange: ( state ) => {
			if ( state.range.preset === 'custom' && state.range.from && state.range.to ) {
				return { from: state.range.from, to: state.range.to };
			}
			const days = { '7d': 7, '14d': 14, '30d': 30, '60d': 60, '90d': 90 }[ state.range.preset ] || 7;
			const today = SimpleStatsVue.todayIso || new Date().toISOString().slice( 0, 10 );
			const fromDate = new Date( `${ today }T00:00:00Z` );
			fromDate.setUTCDate( fromDate.getUTCDate() - ( days - 1 ) );
			return { from: fromDate.toISOString().slice( 0, 10 ), to: today };
		},
		chartSeries: ( state ) => ( tab ) => state.report.data?.series?.[ tab ] || [],
	},
	actions: {
		toggleNotification() {
			this.isNotificationOpen = !this.isNotificationOpen;
		},

		fetchNotifications() {
			return wp.ajax.post( 'simplestats_get_notifications', {
				_ajax_nonce: SimpleStatsVue.wpNonce,
			} ).done( ( data ) => {
				if ( data && data.events ) {
					this.notifications = data;
				}
			} );
		},

		dismissNotifications( id ) {
			this.notifications.events.forEach( ( element, index ) => {
				if ( element.id === id ) {
					this.notifications.events.splice( index, 1 );
					this.notifications.dismissed.splice( 0, 0, element );
				}
			} );

			return wp.ajax.post( 'simplestats_dismiss_notification', {
				_ajax_nonce: SimpleStatsVue.wpNonce,
				notification_id: id,
			} );
		},

		updateAddonsList() {
			return wp.ajax.post( 'simplestats_get_addons', {
				_ajax_nonce: SimpleStatsVue.pluginNonce,
			} ).done( ( data ) => {
				this.addons = data;
			} );
		},

		fetchReport() {
			const { from, to } = this.currentRange;
			this.report.isLoading = true;
			this.report.error     = null;

			return wp.ajax.post( 'simplestats_get_report', {
				_ajax_nonce: SimpleStatsVue.wpNonce,
				from,
				to,
			} ).done( ( data ) => {
				this.report.data   = data || {};
				this.report.loaded = true;
			} ).fail( ( err ) => {
				this.report.error = err?.code || 'upstream';
			} ).always( () => {
				this.report.isLoading = false;
			} );
		},

		setRange( preset, custom = {} ) {
			this.range = {
				preset,
				from: preset === 'custom' ? ( custom.from || null ) : null,
				to:   preset === 'custom' ? ( custom.to   || null ) : null,
			};
			return this.fetchReport();
		},

		fetchRealtime() {
			this.realtime.isLoading = true;
			return wp.ajax.post( 'simplestats_get_realtime', {
				_ajax_nonce: SimpleStatsVue.wpNonce,
			} ).done( ( data ) => {
				this.realtime.online     = Number( data?.online ) || 0;
				this.realtime.activities = Array.isArray( data?.activities ) ? data.activities : [];
			} ).always( () => {
				this.realtime.isLoading = false;
			} );
		},

		startRealtimePolling() {
			if ( this.realtime.pollHandle ) {
				return;
			}
			this.fetchRealtime();
			this.realtime.pollHandle = setInterval( () => this.fetchRealtime(), 30000 );
		},

		stopRealtimePolling() {
			if ( this.realtime.pollHandle ) {
				clearInterval( this.realtime.pollHandle );
				this.realtime.pollHandle = null;
			}
		},

		fetchConnectionStatus() {
			if ( this.connection.isFetching ) {
				return;
			}

			this.connection.isFetching = true;
			this.connection.status = 'checking';
			this.connection.error  = null;

			return wp.ajax.post( 'simplestats_validate_connection', {
				_ajax_nonce: SimpleStatsVue.wpNonce,
			} ).done( ( data ) => {
				this.connection.status = 'connected';
				this.connection.email  = data?.email || null;
				if ( data?.plan ) {
					this.connection.plan = data.plan;
				}
				if ( typeof data?.plan_name === 'string' ) {
					this.connection.planName = data.plan_name;
				}
			} ).fail( ( err ) => {
				if ( err?.code === 'not_connected' ) {
					this.connection.status = 'disconnected';
					this.connection.email  = null;
				} else {
					this.connection.status = 'error';
					this.connection.error  = err?.message || 'Connection check failed';
				}
			} ).always( () => {
				this.connection.isFetching = false;
			} );
		},

		saveSettings( draft ) {
			this.saveStatus = 'saving';

			if ( this._saveStatusTimer ) {
				clearTimeout( this._saveStatusTimer );
				this._saveStatusTimer = null;
			}

			return wp.ajax.post( 'simplestats_save_settings', {
				_ajax_nonce: SimpleStatsVue.wpNonce,
				settings: draft,
			} ).done( ( data ) => {
				this.settings   = { ...this.settings, ...data };
				this.saveStatus = 'saved';
				this._saveStatusTimer = setTimeout( () => {
					this.saveStatus = 'idle';
					this._saveStatusTimer = null;
				}, 2000 );
			} ).fail( () => {
				this.saveStatus = 'error';
			} );
		},

		disconnect() {
			return wp.ajax.post( 'simplestats_disconnect', {
				_ajax_nonce: SimpleStatsVue.wpNonce,
			} ).done( () => {
				this.connection.status = 'disconnected';
				this.connection.email  = null;
			} );
		},
	},
} );
