import React, { useEffect, useState } from 'react';
import { __ } from '@wordpress/i18n';
import TopBar from '@QPComponents/TopBar';
import { Box, Button, Flex, Span } from '@chakra-ui/react';
import QPLabel from '@QPComponents/Labels/QPLabel';
import { primaryBtn } from '../../../../../assets/scss/chakra/recipe';
import { Link, useNavigate } from 'react-router-dom';
import {
	makeRequest,
	copyToClipboard,
	hideHtmlTags,
	route_path,
	sliceString,
	useQuery,
	formatDateTime,
} from '@QPUtils/helper';
import ListTable from '@QPComponents/ListTable';
import { useDispatch, useSelector } from 'react-redux';
import OptionMenu from '@QPComponents/OptionMenu';
import {
	deleteQuiz,
	fetchQuizzes,
	moveQuizToTrash,
	restoreQuiz,
	updateQuiz,
	updateQuizCurrentPage,
	updateQuizItemPerPage,
} from '@QPRedux/Slices/quizSlice/quizSlice';
import Search from '@QPComponents/Search';
import StatusOptions from '@QPComponents/StatusOptions';
import { showNotification } from '@QPRedux/Slices/notificationSlice/notificationSlice';
import SnackbarAction from '@QPComponents/BulkAction/SnackbarAction';

const statusArray = [
	{
		label: __( 'All', 'quizpress' ),
		value: 'all',
	},
	{
		label: __( 'Publish', 'quizpress' ),
		value: 'publish',
	},
	{
		label: __( 'Draft', 'quizpress' ),
		value: 'draft',
	},
	{
		label: __( 'Pending', 'quizpress' ),
		value: 'pending',
	},
	{
		label: __( 'Trash', 'quizpress' ),
		value: 'trash',
	},
];

const Quizzes = () => {
	const quizzes = useSelector( ( state ) => state.quizzes );
	const [ dataFetchingStatus, setDataFetchingStatus ] = useState( false );
	const [ onSearchLoader, setOnSearchLoader ] = useState( false );
	const [ selectedItems, setSelectedItems ] = 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 quizStatus = location.get( 'status' );
	const quizPerPage = location.get( 'quizPerPage' ) ?? 10;
	const searchText = location.get( 'search' );
	const [ status, setStatus ] = useState( quizStatus ? quizStatus : 'all' );

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

		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 publishAction =
		status !== 'trash'
			? [
					{
						suffix: 'trash',
						label: __( 'Trash', 'quizpress' ),
						onClick: () =>
							setSnackbarOption( {
								value: 'trash',
								message: __(
									'Are you sure, you want to move these item to trash!',
									'quizpress'
								),
							} ),
					},
			  ]
			: [];
	const trashAction =
		status === 'trash'
			? [
					{
						suffix: 'restore',
						label: __( 'Restore', 'quizpress' ),
						onClick: () =>
							setSnackbarOption( {
								value: 'restore',
								message: __(
									'Are you sure, you want to restore these items?',
									'quizpress'
								),
							} ),
					},
					{
						suffix: 'delete',
						label: __( 'Delete Permanently', 'quizpress' ),
						onClick: () =>
							setSnackbarOption( {
								value: 'delete',
								message: __(
									'Are you sure, you want to delete these items?',
									'quizpress'
								),
							} ),
					},
			  ]
			: [];

	const snackbarOptions = [ ...publishAction, ...trashAction ];

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

	const snackbarActionHandler = ( option ) => {
		if ( status !== 'trash' && option === 'trash' ) {
			selectedItems.forEach( ( item ) => {
				dispatch( moveQuizToTrash( item ) );
			} );
			handleReset();
		} else if ( option === 'restore' ) {
			selectedItems.forEach( ( item ) => {
				dispatch( restoreQuiz( item ) );
			} );
			handleReset();
		} else {
			selectedItems.forEach( ( item ) => {
				dispatch( deleteQuiz( item.id ) );
				handleReset();
			} );
		}
	};

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

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

	useEffect( () => {
		( async () => {
			if (
				! quizzes.data.length ||
				( quizzes.data && quizzes.data.length <= 1 )
			) {
				setDataFetchingStatus( true );
				dispatch( fetchQuizzes( { status } ) ).finally( () => {
					setDataFetchingStatus( false );
				} );
			}
		} )();
	}, [] );

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

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

	const handleItemsPage = ( itemsPerPage = 10, page = 1 ) => {
		dispatch( updateQuizItemPerPage( itemsPerPage ) );
		handleTableDataFetch( page, itemsPerPage );
		handleNavigate( status );
	};

	const restoreHandler = ( item ) => {
		// eslint-disable-next-line
		dispatch(restoreQuiz(item));
	};

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

	const columns = [
		{
			name: __( 'ID', 'quizpress' ),
			cell: ( row ) => <span>{ row.id }</span>,
		},
		{
			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-quizzes&action=edit&id=${ row.id }&path=name` }
							>
								<span
									className="quizpress-table-title quizpress-tooltip"
									data-tooltip={ sliceString(
										hideHtmlTags(
											row?.title?.raw ??
												row.title?.rendered
										),
										80
									) }
									dangerouslySetInnerHTML={ {
										__html: sliceString(
											row?.title?.raw ??
												row.title?.rendered,
											16
										),
									} }
								></span>
							</Link>
						</div>
					</div>
				);
			},
		},
		{
			name: __( 'Short Code', 'quizpress' ),
			cell: ( row ) => (
				<Flex
					color="var(--quizpress-primary) !important"
					onClick={ () => {
						copyToClipboard(
							`[quizpress_quiz quiz_id="${ row.id }"]`
						);
						dispatch(
							showNotification( {
								message: __(
									'Copied Successfully',
									'quizpress'
								),
								isShow: true,
								type: 'success',
							} )
						);
					} }
					alignItems="end"
					cursor="pointer"
				>
					<Span maxWidth="min-content">{ `[quizpress_quiz quiz_id="${ row.id }"]` }</Span>
					<Span className="quizpress-icon quizpress-icon--copy quizpress-primary" />
				</Flex>
			),
		},
		{
			name: __( 'Type', 'quizpress' ),
			cell: ( row ) => (
				<span>
					{ row?.meta?.quizpress_quiz_product_type === 'paid'
						? __( 'Paid', 'quizpress' )
						: __( 'Free', 'quizpress' ) }
				</span>
			),
		},
		{
			name: __( 'Questions', 'quizpress' ),
			cell: ( row ) => (
				<span>{ row?.meta?.quizpress_quiz_questions?.length }</span>
			),
		},
		{
			name: __( 'Last Modified', 'quizpress' ),
			cell: ( row ) => (
				<div>
					<span>
						{ formatDateTime( row.modified, 'MMM DD, YYYY' ) }
					</span>
					<br />
					<span className="quizpress-table-time">
						{ formatDateTime( row.modified, 'hh:mm A' ) }
					</span>
				</div>
			),
		},
		{
			name: __( 'Status', 'quizpress' ),
			cell: ( row ) => {
				const quizStatusHandler = ( itemStatus ) => {
					// eslint-disable-next-line
					if (itemStatus === 'trash') {
						dispatch( moveQuizToTrash( row ) );
					} else {
						dispatch(
							updateQuiz( {
								params: {
									...row,
									status: itemStatus,
								},
								questions: row.questions,
							} )
						);
					}
				};

				const scheduleStatus = [
					{
						label: __( 'Draft', 'quizpress' ),
						value: 'draft',
					},
					{
						label: __( 'Pending', 'quizpress' ),
						value: 'pending',
					},
					{
						label: __( 'Trash', 'quizpress' ),
						value: 'trash',
					},
				];

				const restStatus =
					row.status !== 'future'
						? [
								{
									label: __( 'Published', 'quizpress' ),
									value: 'publish',
								},
						  ]
						: [];
				return (
					<StatusOptions
						value={ row?.status }
						options={ {
							items: [ ...scheduleStatus, ...restStatus ],
						} }
						onChangeHandler={ quizStatusHandler }
					/>
				);
			},
		},
		{
			name: __( 'Analytics', 'quizpress' ),
			cell: ( row ) => (
				<Button
					variant="outline"
					fontWeight="500"
					fontSize="0.87rem"
					onClick={ () => {
						navigate(
							`${ route_path }admin.php?page=quizpress-quizzes&action=leaderboard&id=${ row.id }`
						);
					} }
				>
					<Span className="quizpress-icon quizpress-icon--chart-line" />
					{ __( 'Analytics', 'quizpress' ) }
				</Button>
			),
		},
		{
			name: __( 'Action', 'quizpress' ),
			cell: ( row ) => {
				const publishedActions =
					row.status !== 'trash'
						? [
								{
									type: 'button',
									suffix: 'trash',
									label: __( 'Trash', 'quizpress' ),
									hasBorder: true,
									icon: (
										<span className="quizpress-icon quizpress-icon--trash" />
									),
									onClick: () =>
										dispatch( moveQuizToTrash( row ) ),
								},
						  ]
						: [];
				const trashActions =
					row.status === 'trash'
						? [
								{
									type: 'button',
									label: __( 'Restore', 'quizpress' ),
									icon: (
										<span className="quizpress-icon quizpress-icon--reset"></span>
									),
									onClick: () => restoreHandler( row ),
								},
								{
									type: 'button',
									suffix: 'trash',
									label: __( 'Delete', 'quizpress' ),
									icon: (
										<span className="quizpress-icon quizpress-icon--trash" />
									),
									onClick: () => deleteHandler( row ),
								},
						  ]
						: [];
				return (
					<div className="quizpress-table-item-control">
						<OptionMenu
							options={ [
								{
									type: 'button',
									label: __( 'Edit', 'quizpress' ),
									icon: (
										<span className="quizpress-icon  quizpress-icon--square-pen" />
									),
									onClick: () => {
										// if (is_admin) {
										navigate(
											`${ route_path }admin.php?page=quizpress-quizzes&action=edit&id=${ row.id }&path=name`
										);
										// } else {
										// 	openModalHandler(row.id);
										// }
									},
								},
								{
									type: 'button',
									hasBorder: true,
									label: __( 'View Analytics', 'quizpress' ),
									icon: (
										<span className="quizpress-icon quizpress-icon--eye"></span>
									),
									onClick: () => {
										navigate(
											`${ route_path }admin.php?page=quizpress-quizzes&action=leaderboard&id=${ row.id }`
										);
									},
								},
								...publishedActions,
								...trashActions,
								{
									type: 'button',
									suffix: 'trash',
									label: __( 'Delete Attempts', 'quizpress' ),
									icon: (
										<span className="quizpress-icon quizpress-icon--trash"></span>
									),
									onClick: () => {
										if (
											window.confirm(
												__(
													'Are you sure, you want to delete attempts?',
													'quizpress'
												)
											)
										) {
											makeRequest(
												'admin/delete_quiz_attempts',
												{
													quiz_id: row.id,
												}
											).then( function ( res ) {
												if ( Number( res ) !== 0 ) {
													dispatch(
														showNotification( {
															message: __(
																'Attempts deleted successfully',
																'quizpress'
															),
															isShow: true,
															type: 'success',
														} )
													);
												} else {
													dispatch(
														showNotification( {
															message: __(
																'There is no deletable attempts',
																'quizpress'
															),
															isShow: true,
															type: 'error',
														} )
													);
												}
											} );
										}
									},
								},
							] }
						/>
					</div>
				);
			},
		},
	];

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

		return (
			<>
				<div className="quizpress-table__sub-header-left">
					{ statusArray.map( ( item, index ) => (
						<span
							role="presentation"
							className={ `tab ${
								item?.value === status ? 'is-active' : ''
							} ` }
							key={ index }
							onClick={ () => {
								setStatus( item.value );
								dataFetchHandler( item.value );
							} }
						>
							{ item.label }
						</span>
					) ) }
				</div>
				<div className="quizpress-table-sub-header-actions-right">
					<Search
						placeholder={ __( 'Search Items', 'quizpress' ) }
						onSearchHandler={ searchHandler }
						defaultValue={ searchText ? searchText : '' }
					/>
				</div>
			</>
		);
	}, [ status, searchText ] );

	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={ __( 'Quizzes', 'quizpress' ) }
						/>
					</>
				) }
				rightContent={ () => (
					<Button
						{ ...primaryBtn }
						onClick={ () =>
							navigate(
								`${ route_path }admin.php?page=quizpress-quizzes&action=add&path=name`
							)
						}
					>
						{ __( 'Create New', 'quizpress' ) }
						<span className="quizpress-icon quizpress-icon--plus has-quizpress-blue-bg" />
					</Button>
				) }
			/>

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

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

export default Quizzes;
