import { Link, useNavigate, useLocation } from 'react-router-dom';
import React, { useState, useEffect } from 'react';
import {
	admin_url,
	// getAddonActiveStatus,
	route_path,
	// sliceString,
	is_admin,
	makeRequest,
	useQuery,
	handleSliceError,
	handleSliceSuccess,
	// is_pro,
	// capitalizeFirstLetter,
	// hideHtmlTags,
} from '@QPUtils/helper';
import { useDispatch, useSelector } from 'react-redux';
// import SnackbarAction from '@Components/BulkAction/SnackbarAction';
//import Search from '@Components/Search';
import { __ } from '@wordpress/i18n';
//import StatusOptions from '@Components/StatusOptions';
import moment from 'moment';
import ListTable from '@QPComponents/ListTable';
import Search from '@QPComponents/Search';
import './styles.scss';
import OptionMenu from '@QPComponents/OptionMenu';
import {
	createCategory,
	deleteCategory,
	duplicateCategory,
	fetchCategories,
	updateCategoryCurrentPage,
	updateCategoryItemPerPage,
} from '@QPRedux/Slices/quizCategorySlice/quizCategorySlice';
import SnackbarAction from '@QPComponents/BulkAction/SnackbarAction';
import { showNotification } from '@QPRedux/Slices/notificationSlice/notificationSlice';
import { appName } from './helper';

const CategoryTable = ( { deleteHandler = () => {} } ) => {
	const [ dataFetchingStatus, setDataFetchingStatus ] = useState( false );
	const categories = useSelector( ( state ) => state.categories );
	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 categoryPerPage = location.get( 'coursePerPage' );
	const searchText = location.get( 'search' );
	const idPayload = ( row ) => actionIdPayload( row, post_type );

	const handleNavigate = ( itemsPerPage = '', page = 1, text = '' ) => {
		let url = `${ route_path }admin.php?page=${ appName }-question&path=category`;

		if ( page !== '' && page !== null && page !== 'null' ) {
			const hasQuestionMark = url.includes( '?' );
			url = `${ url }${
				! hasQuestionMark ? '?' : '&'
			}currentPage=${ page }`;
		}
		if (
			itemsPerPage !== '' &&
			itemsPerPage !== null &&
			itemsPerPage !== 'null'
		) {
			const hasQuestionMark = url.includes( '?' );
			url = `${ url }${
				! hasQuestionMark ? '?' : '&'
			}perPage=${ itemsPerPage }`;
		}

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

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

	const snackbarActionHandler = () => {
		selectedItems.forEach( ( item ) => {
			deleteHandler( item?.id );
		} );
		handleReset();
	};

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

	useEffect( () => {
		( async () => {
			if (
				! categories.data.length ||
				( categories.data && categories.data.length <= 1 )
			) {
				setDataFetchingStatus( true );

				if ( categoryPerPage !== null ) {
					dispatch( updateCategoryItemPerPage( categoryPerPage ) );
				}

				dispatch(
					fetchCategories( {
						status: '',
						page: categories.currentPage || 1,
						per_page: categoryPerPage || 10,
					} )
				).finally( () => {
					setDataFetchingStatus( false );
				} );
			}
		} )();
	}, [ categories.currentPage, categoryPerPage ] );

	const categoryDeleteHandler = ( item ) => {
		if (
			window.confirm(
				__(
					'Are you sure you want to permanently delete selected course category?',
					'quizpress'
				)
			)
		) {
			dispatch( deleteCategory( item.id ) );
		}
	};

	const duplicateCategoryHandler = ( item ) => {
		setDataFetchingStatus( true );
		const payload = {
			...item,
			name: `${ item.name } (Copy)`,
			slug: `${ item.slug }-copy`,
		};

		if ( item.parent_id ) {
			payload.parent_id = item.parent_id;
		}
		dispatch( createCategory( payload ) ).finally( () => {
			setDataFetchingStatus( false );
		} );
	};

	const columns = [
		{
			name: __( 'Name', 'quizpress' ),
			cell: ( row ) => {
				return (
					<>
						<p>{ row.name }</p>
					</>
				);
			},
		},
		{
			name: __( 'Description', 'quizpress' ),
			cell: ( row ) => (
				<>
					<p>{ row.description }</p>
				</>
			),
		},
		{
			name: __( 'Slug', 'quizpress' ),
			cell: ( row ) => (
				<>
					<p>{ row.name }</p>
				</>
			),
		},
		{
			name: __( 'Action', 'quizpress' ),
			cell: ( row ) => {
				return (
					<div className="quizpress-table-item-control">
						<OptionMenu
							options={ [
								{
									type: 'button',
									label: __( 'Edit', 'quizpress' ),
									icon: (
										<span className="quizpress-icon quizpress-icon--edit" />
									),
									onClick: () => {
										navigate(
											`${ route_path }${ route_path }admin.php?page=quizpress-question&path=category&id=${ row.id }`
										);
									},
								},
								{
									type: 'button',
									label: __( 'Duplicate', 'quizpress' ),
									icon: (
										<span className="quizpress-icon quizpress-icon--copy-two" />
									),
									onClick: () =>
										duplicateCategoryHandler( row ),
								},
								{
									type: 'button',
									suffix: 'trash',
									label: __( 'Delete', 'quizpress' ),
									icon: (
										<span className="quizpress-icon quizpress-icon--trash-delete" />
									),
									onClick: () => categoryDeleteHandler( row ),
								},
							] }
						/>
					</div>
				);
			},
		},
	];

	const subHeaderComponentMemo = React.useMemo( () => {
		const searchHandler = ( value ) => {
			setOnSearchLoader( true );

			dispatch(
				fetchCategories( {
					page: 1,
					per_page: categories.itemPerPage || 10,
					search: value,
				} )
			).finally( () => {
				setOnSearchLoader( false );
				handleNavigate( value, 1, categories.itemPerPage || 10 );
			} );
		};

		return (
			<>
				<div className="quizpress-table__sub-header-actions-left quizpress-table__sub-header-actions-left--with-search">
					<div className="quizpress-table__sub-header-actions-left"></div>
					<div>
						<Search
							placeholder={ __( 'Search Category', 'quizpress' ) }
							onSearchHandler={ searchHandler }
							defaultValue={ searchText || '' }
						/>
					</div>
				</div>
			</>
		);
	}, [ searchText, categories.itemPerPage ] );

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

	const handlePageChange = ( page = 1, perPage = 10 ) => {
		dispatch( updateCategoryCurrentPage( page ) );
		handleTableDataFetch( page, perPage, location.get( 'search' ) || '' );
		handleNavigate( page, perPage, location.get( 'search' ) || '' );
	};

	const handleItemsPage = ( itemsPerPage = 10, page = 1 ) => {
		dispatch( updateCategoryItemPerPage( itemsPerPage ) );
		handleTableDataFetch(
			page,
			itemsPerPage,
			location.get( 'search' ) || ''
		);
		handleNavigate( page, itemsPerPage, location.get( 'search' ) || '' );
	};

	return (
		<>
			<ListTable
				columns={ columns }
				data={ categories?.data ?? [] }
				showSubHeader={ true }
				subHeaderComponent={ subHeaderComponentMemo }
				isRowSelectable={ true }
				showColumnFilter={ false }
				noDataText={ __(
					'Please, create Courses to see the available list here.',
					'quizpress'
				) }
				getSelectRowValue={ ( selectedRow ) => {
					setSelectedItems( selectedRow );
					setResetSelectedItems( false );
				} }
				showPagination={ categories.totalItems >= 10 }
				onChangePage={ handlePageChange }
				onChangeItemsPerPage={ handleItemsPage }
				totalItems={ categories.totalItems }
				dataFetchingStatus={ dataFetchingStatus || onSearchLoader }
				resetSelected={ resetSelectedItems }
				rowsPerPage={ categories.itemPerPage }
				currentPageNumber={ categories.currentPage }
				suffix="category-table"
			/>

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