import React, { useState, useEffect } from 'react';
import { __ } from '@wordpress/i18n';
import TopBar from '@QPComponents/TopBar';
import QPLabel from '@QPComponents/Labels/QPLabel';
import { Box, Button, Flex, Text } from '@chakra-ui/react';
import { primaryBtn } from '../../../../../assets/scss/chakra/recipe';
import { Formik } from 'formik';
import AddCategoryFormInner from './AddCategoryFormInner';
import CategoryTable from './CategoryTable';
import { categoryFormInitialValues } from './helper';
import { useDispatch, useSelector } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import { route_path, useQuery } from '@QPUtils/helper';
import {
	createCategory,
	deleteCategory,
	getCategory,
	updateCategory,
} from '@QPRedux/Slices/quizCategorySlice/quizCategorySlice';
import { showNotification } from '@QPRedux/Slices/notificationSlice/notificationSlice';

const Category = () => {
	const { data } = useSelector( ( state ) => state.categories );
	const [ loading, setLoading ] = useState( false );

	const dispatch = useDispatch();
	const navigate = useNavigate();
	const location = useQuery();
	const id = location.get( 'id' );

	useEffect( () => {
		if ( id && ! data.length ) {
			setLoading( true );
			dispatch( getCategory( id ) ).finally( () => setLoading( false ) );
		}
	}, [ id, data ] );

	const onSubmitHandler = ( values, { setSubmitting, resetForm } ) => {
		setSubmitting( true );

		if ( ! values?.name ) {
			dispatch(
				showNotification( {
					message: __( 'Name is required', 'quizpress' ),
					isShow: true,
					type: 'error',
				} )
			);
			setSubmitting( false );
			return;
		}

		if ( values?.id ) {
			dispatch( updateCategory( values ) ).finally( () => {
				setSubmitting( false );
				navigate(
					`${ route_path }admin.php?page=quizpress-question&path=category`
				);
				resetForm( {
					values: categoryFormInitialValues( null, [] ),
				} );
			} );
			return;
		}

		dispatch( createCategory( values ) )
			.then( ( { payload } ) => {
				navigate(
					`${ route_path }admin.php?page=quizpress-question&path=category&id=${ payload.id }`
				);
			} )
			.finally( () => {
				setSubmitting( false );
				navigate(
					`${ route_path }admin.php?page=quizpress-question&path=category`
				);
				resetForm( {
					values: categoryFormInitialValues( null, [] ),
				} );
			} );
	};

	const deleteHandler = ( ID ) => {
		dispatch( deleteCategory( ID ) );
	};

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

			<Flex gap={ 6 } className="quizpress-page-content">
				<Flex
					flexDir={ 'column' }
					width={ '40%' }
					padding={ 8 }
					bg={ 'var(--quizpress-background)' }
					maxH="fit-content"
					borderRadius={ '4px' }
					boxShadow="0 0 1px 0 var(--quizpress-border-color), 0 1px 1px 0 var(--quizpress-border-color)"
				>
					<Text as={ 'h1' } className="quizpress-heading">
						{ id
							? __( 'Edit Category', 'quizpress' )
							: __( 'Add New Category', 'quizpress' ) }
					</Text>

					{ loading ? (
						<Text>{ __( 'Loading…', 'quizpress' ) }</Text>
					) : (
						<Formik
							enableReinitialize={ true }
							initialValues={ categoryFormInitialValues(
								id,
								data
							) }
							onSubmit={ onSubmitHandler }
						>
							{ ( { isSubmitting, dirty, handleSubmit } ) => (
								<>
									<AddCategoryFormInner />

									<Box className="quizpress-separator" />
									<Button
										onClick={ handleSubmit }
										{ ...primaryBtn }
										loading={ isSubmitting }
										disabled={ isSubmitting || ! dirty }
									>
										{ id
											? __(
													'Update Category',
													'quizpress'
											  )
											: __(
													'Add Category',
													'quizpress'
											  ) }
									</Button>
								</>
							) }
						</Formik>
					) }
				</Flex>

				<Box minH="fit-content" width={ '100%' }>
					<CategoryTable deleteHandler={ deleteHandler } />
				</Box>
			</Flex>
		</>
	);
};

export default Category;
