import React, { useEffect, useState } from 'react';
import { __ } from '@wordpress/i18n';
import { useDispatch, useSelector } from 'react-redux';
import { Link, useNavigate } from 'react-router-dom';
import {
	formatDateTime,
	makeRequest,
	route_path,
	sliceString,
	useQuery,
} from '@QPUtils/helper';
import Select from 'react-select';
import { Box, Button, Flex, Span } from '@chakra-ui/react';
import TopBar from '@QPComponents/TopBar';
import QPLabel from '@QPComponents/Labels/QPLabel';
import ListTable from '@QPComponents/ListTable';
import {
	deleteAttempts,
	fetchQuizInsights,
	updateQuizInsightsCurrentPage,
	updateQuizInsightsItemPerPage,
} from '@QPRedux/Slices/quizInsightsSlice/quizInsightsSlice';
import OptionMenu from '@QPComponents/OptionMenu';
import SnackbarAction from '@QPComponents/BulkAction/SnackbarAction';

const QuizInsights = () => {
	const quizInsights = useSelector( ( state ) => state.quizInsights );
	const [ dataFetchingStatus, setDataFetchingStatus ] = useState( false );
	const [ onSearchLoader, setOnSearchLoader ] = useState( false );
	const [ selectedItems, setSelectedItems ] = useState( [] );
	const [ quizpressUsers, setQuizpressUsers ] = useState( [] );
	const [ snackbarOption, setSnackbarOption ] = useState( {} );
	const [ confirm, setConfirm ] = useState( false );
	const [ resetSelectedItems, setResetSelectedItems ] = useState( false );

	const dispatch = useDispatch();
	const navigate = useNavigate();

	const location = useQuery();
	const attemptStatus = location.get( 'status' );
	const quizPerPage = location.get( 'quizPerPage' );
	const searchText = location.get( 'search' );
	const [ status, setStatus ] = useState(
		attemptStatus ? attemptStatus : 'all'
	);

	const handleNavigate = ( tableStatus = '', text = '' ) => {
		let url = `${ route_path }admin.php?page=quizpress-quiz-insights`;

		const queryParams = [];

		if ( tableStatus && tableStatus !== 'null' && tableStatus !== 'all' ) {
			queryParams.push( `status=${ encodeURIComponent( tableStatus ) }` );
		}

		if ( text && text !== 'null' ) {
			queryParams.push( `search=${ encodeURIComponent( text ) }` );
		}

		if ( queryParams.length > 0 ) {
			url +=
				( url.includes( '?' ) ? '&' : '?' ) + queryParams.join( '&' );
		}

		navigate( url );
	};

	const snackbarOptions = [
		{
			suffix: 'delete',
			label: __( 'Delete Permanently', 'quizpress' ),
			onClick: () =>
				setSnackbarOption( {
					value: 'delete',
					message: __(
						'Are you sure, you want to delete these items?',
						'quizpress'
					),
				} ),
		},
	];

	const handleReset = () => {
		setSelectedItems( [] );
		setSnackbarOption( {} );
		setResetSelectedItems( true );
		setConfirm( false );
	};

	const snackbarActionHandler = ( option ) => {
		selectedItems.forEach( ( item ) => {
			dispatch( deleteAttempts( item.attempt_id ) );
			handleReset();
		} );
	};

	React.useMemo( () => {
		if ( confirm ) {
			snackbarActionHandler( snackbarOption.value );
		} else {
			handleReset();
		}
	}, [ confirm ] );

	useEffect( () => {
		handleNavigate( attemptStatus, searchText );
	}, [ attemptStatus, searchText ] );

	useEffect( () => {
		( async () => {
			if (
				! quizInsights.data.length ||
				( quizInsights.data && quizInsights.data.length <= 1 )
			) {
				setDataFetchingStatus( true );
				dispatch( fetchQuizInsights( { status } ) ).finally( () => {
					setDataFetchingStatus( false );
				} );
			}

			makeRequest( 'admin/get_quizpress_users' ).then( ( res ) => {
				setQuizpressUsers(
					res.map( ( user ) => ( {
						value: Number( user?.ID ),
						label: user?.display_name,
					} ) )
				);
			} );
		} )();
	}, [] );

	const handleTableDataFetch = ( page = 1, perPage = 10 ) => {
		setDataFetchingStatus( true );
		dispatch(
			fetchQuizInsights( { status, page, per_page: perPage } )
		).finally( () => setDataFetchingStatus( false ) );
	};

	const handlePageChange = ( page = 1, perPage = 10 ) => {
		dispatch( updateQuizInsightsCurrentPage( page ) );
		handleTableDataFetch( page, perPage );
	};

	const handleItemsPage = ( itemsPerPage = 10, page = 1 ) => {
		dispatch( updateQuizInsightsItemPerPage( itemsPerPage ) );
		handleTableDataFetch( page, itemsPerPage );
		// handleNavigate(courseStatus);
	};

	const deleteHandler = ( id ) => {
		// eslint-disable-next-line
		if (window.confirm('Are you sure, you want to delete it?')) {
			dispatch( deleteAttempts( id ) );
		}
	};

	const columns = [
		{
			name: __( 'Title', 'quizpress' ),
			cell: ( row ) => {
				return (
					<div className="quizpress-table-title-wrap">
						<div className="quizpress-table-title">
							<Link
								to={ `${ route_path }admin.php?page=quizpress-quiz-insights` }
							>
								<span
									className="quizpress-table-title quizpress-tooltip"
									data-tooltip={ sliceString(
										row._quiz.title,
										80
									) }
									dangerouslySetInnerHTML={ {
										__html: sliceString( row._quiz.title ),
									} }
								></span>
							</Link>

							<a
								href={ row.link }
								target="_blank"
								rel="noreferrer"
							>
								<span className="quizpress-icon quizpress-icon--go-on" />
							</a>
						</div>
						<div className="quizpress-table-sub-title">
							<div className="quizpress-table-sub-title__item">
								<span className="quizpress-table-sub-title__item--label">
									{ __( 'ID', 'quizpress' ) }
								</span>
								<Span fontWeight="600">
									{ __( ':', 'quizpress' ) }
								</Span>
								{ row.attempt_id }
							</div>
						</div>
					</div>
				);
			},
		},
		{
			name: __( 'User', 'quizpress' ),
			cell: ( row ) => <span>{ row._user.display_name }</span>,
		},
		{
			name: __( 'User IP', 'quizpress' ),
			cell: ( row ) => <span>{ row.attempt_ip }</span>,
		},
		{
			name: __( 'Start Time', 'quizpress' ),
			cell: ( row ) => (
				<div>
					<span>
						{ formatDateTime(
							row.attempt_started_at,
							'MMM DD, YYYY'
						) }
					</span>
					<br />
					<span className="quizpress-table-time">
						{ formatDateTime( row.attempt_started_at, 'hh:mm A' ) }
					</span>
				</div>
			),
		},
		{
			name: __( 'End Time', 'quizpress' ),
			cell: ( row ) => (
				<div>
					<span>
						{ formatDateTime(
							row.attempt_ended_at,
							'MMM DD, YYYY'
						) }
					</span>
					<br />
					<span className="quizpress-table-time">
						{ formatDateTime( row.attempt_ended_at, 'hh:mm A' ) }
					</span>
				</div>
			),
		},
		{
			name: __( 'Score', 'quizpress' ),
			cell: ( row ) => <span>{ row.earned_marks }</span>,
		},
		{
			name: __( 'Action', 'quizpress' ),
			cell: ( row ) => {
				return (
					<Flex alignItems="center" gap="12px">
						{ /* <QPTooltip
							content={__('Details', 'quizpress')}
							noWrap={true}
						> */ }
						<Button
							height="32px"
							variant="outline"
							onClick={ () => {
								navigate(
									`${ route_path }admin.php?page=quizpress-quiz-insights&id=${ row.attempt_id }`
								);
							} }
						>
							<span className="quizpress-icon quizpress-icon--square-pen" />
						</Button>
						{ /* </QPTooltip> */ }
						<OptionMenu
							options={ [
								{
									type: 'button',
									label: __( 'Details', 'quizpress' ),
									icon: (
										<span className="quizpress-icon quizpress-icon--square-pen" />
									),
									onClick: () => {
										navigate(
											`${ route_path }admin.php?page=quizpress-quiz-insights&id=${ row.attempt_id }`
										);
									},
								},
								{
									type: 'button',
									suffix: 'trash',
									label: __( 'Delete', 'quizpress' ),
									icon: (
										<span className="quizpress-icon quizpress-icon--trash" />
									),
									onClick: () =>
										deleteHandler( row.attempt_id ),
								},
							] }
						/>
					</Flex>
				);
			},
		},
	];

	const subHeaderComponentMemo = React.useMemo( () => {
		const searchHandler = ( value ) => {
			setOnSearchLoader( true );
			dispatch(
				fetchQuizzes( { status, page: 1, per_page: 10, search: value } )
			).then( () => {
				setOnSearchLoader( false );
				handleNavigate( status, value );
			} );
		};
		const dataFetchHandler = ( option ) => {
			setDataFetchingStatus( true );
			dispatch(
				fetchQuizInsights( {
					status,
					page: 1,
					per_page: quizPerPage,
					user: option.value,
				} )
			).finally( () => {
				setDataFetchingStatus( false );
			} );
		};

		return (
			<>
				<div className="quizpress-table__sub-header-left">
					<Flex gap={ 4 } alignItems="center">
						<Select
							placeholder={ __( 'Select User', 'quizpress' ) }
							className="quizpress-select"
							classNamePrefix="quizpress-select"
							options={ quizpressUsers }
							onChange={ dataFetchHandler }
						/>
					</Flex>
				</div>
			</>
		);
	}, [ status, searchText, quizpressUsers ] );

	return (
		<>
			<TopBar
				leftContent={ () => (
					<>
						<span className="quizpress-topbar-logo quizpress-icon quizpress-icon--quizpress" />
						<span className="quizpress-icon quizpress-icon--angle-right quizpress-muted" />
						<QPLabel
							as="h2"
							color="#4F46E5"
							type="subtitle"
							fontWeight="medium"
							label={ __( 'Quiz Attempts', 'quizpress' ) }
						/>
					</>
				) }
			/>

			<Box className="quizpress-page-content">
				<ListTable
					columns={ columns }
					data={ quizInsights?.data ?? [] }
					showSubHeader={ true }
					subHeaderComponent={ subHeaderComponentMemo }
					isRowSelectable={ true }
					showColumnFilter={ true }
					noDataText={ __(
						'Please, create Quizzes to see the available list here.',
						'quizpress'
					) }
					getSelectRowValue={ ( selectedRow ) => {
						setSelectedItems( selectedRow );
						setResetSelectedItems( false );
					} }
					showPagination={ Number( quizInsights?.totalItems ) >= 10 }
					onChangePage={ handlePageChange }
					onChangeItemsPerPage={ handleItemsPage }
					totalItems={ Number( quizInsights?.totalItems ) ?? 10 }
					totalRows={ quizInsights?.data.length }
					dataFetchingStatus={ dataFetchingStatus || onSearchLoader }
					resetSelected={ resetSelectedItems }
					rowsPerPage={
						Number( quizInsights?.itemPerPage ) ??
						Number( quizPerPage )
					}
					currentPageNumber={
						Number( quizInsights?.currentPage ) ?? 1
					}
					suffix="quiz-insights-table"
				/>
			</Box>

			{ selectedItems.length > 0 && (
				<SnackbarAction
					actionButtons={ snackbarOptions }
					itemsLength={ selectedItems?.length }
					confirmHandler={ setConfirm }
					isActionSelected={ snackbarOption }
					resetHandler={ handleReset }
				/>
			) }
		</>
	);
};

export default QuizInsights;
