import { DataViews, filterSortAndPaginate } from '@wordpress/dataviews/wp';
import { useState, useEffect, useMemo } from '@wordpress/element';
import { useDispatch, useSelect } from '@wordpress/data';
import { store as coreDataStore } from '@wordpress/core-data';
import {
	Button,
	__experimentalHStack as HStack,
	SelectControl,
	ToggleControl,
	SearchControl,
	Icon,
	Modal,
	DropdownMenu,
	SnackbarList,
} from '@wordpress/components';
import apiFetch from '@wordpress/api-fetch';
import {
	moreVertical,
	next,
	previous,
	arrowUp,
	arrowDown,
	edit,
	trash,
} from '@wordpress/icons';
import { getURLParams, isWazChat, updateURLParams } from '../../utils';
import useBlock from '../../hooks/useBlock';
import { __ } from '@wordpress/i18n';

export const WazChatFormTable = () => {
	const [ page, setPage ] = useState( 1 );
	const [ perPage ] = useState( 10 );
	const [ searchTerm, setSearchTerm ] = useState( '' );
	const [ sortConfig, setSortConfig ] = useState( {
		key: 'title',
		direction: 'asc',
	} );
	const [ isUpdating, setIsUpdating ] = useState( false );
	const [ isConfirmDeleteOpen, setIsConfirmDeleteOpen ] = useState( false );
	const [ chatFormToDelete, setChatFormToDelete ] = useState( null );
	const [ notices, setNotices ] = useState( [] );

	const { initData, setInitData } = useBlock();

	// Fetch all posts data using WordPress Data API
	const { allPosts, isLoading } = useSelect( ( select ) => {
		return {
			allPosts: select( coreDataStore ).getEntityRecords(
				'postType',
				'wazchat_856_chatform',
				{
					per_page: -1,
					status: 'any',
				}
			),
			isLoading: select( coreDataStore ).isResolving(
				'getEntityRecords',
				[
					'postType',
					'wazchat_856_chatform',
					{ per_page: -1, status: 'any' },
				]
			),
		};
	}, [] );

	const { invalidateResolution } = useDispatch( coreDataStore );

	// Function to refetch the data
	const refreshData = () => {
		invalidateResolution( 'getEntityRecords', [
			'postType',
			'wazchat_856_chatform',
			{ per_page: -1, status: 'any' },
		] );
	};

	// Create notice function
	const createNotice = ( status, text ) => {
		const id = Date.now().toString();
		setNotices( ( prev ) => [ ...prev, { id, status, content: text } ] );

		// Auto-dismiss after 3 seconds
		setTimeout( () => {
			setNotices( ( prev ) =>
				prev.filter( ( notice ) => notice.id !== id )
			);
		}, 3000 );
	};

	// Handler for dismissing notices
	const onDismissNotice = ( id ) => {
		setNotices( ( prev ) => prev.filter( ( notice ) => notice.id !== id ) );
	};

	const handleStatusToggle = async ( post ) => {
		if ( isUpdating ) {
			return;
		}

		setIsUpdating( true );
		const newStatus = post.status === 'publish' ? 'draft' : 'publish';

		try {
			await apiFetch( {
				path: `/wp/v2/wazchat_856_chatform/${ post.id }`,
				method: 'POST',
				data: {
					status: newStatus,
				},
			} );
			createNotice( 'success', 'ChatForm status updated successfully.' );
			refreshData();
		} catch ( error ) {
			console.error( 'Failed to update post status:', error );
			createNotice( 'error', 'Failed to update chatform status.' );
		} finally {
			setIsUpdating( false );
		}
	};

	const handleEditClick = ( chatForm ) => {
		// updateURLParams("post", chatForm.id);
		// updateURLParams("add-new", true);
		console.log( 'edit', chatForm.id );
		updateURLParams( {
			page: 'wazchat',
			path: 'chat-forms',
			'add-new': true,
			post: chatForm.id,
		} );
		setInitData( {
			...initData,
			refresh: ! initData?.refresh,
		} );
	};

	const handleViewClick = ( chatForm ) => {
		window.open( chatForm.link, '_blank' );
	};

	const handleDeleteClick = ( chatForm ) => {
		setChatFormToDelete( chatForm );
		setIsConfirmDeleteOpen( true );
	};

	const handleDelete = async () => {
		if ( ! chatFormToDelete ) {
			return;
		}

		setIsUpdating( true );
		try {
			await apiFetch( {
				path: `/wp/v2/wazchat_856_chatform/${ chatFormToDelete.id }`,
				method: 'DELETE',
			} );
			setIsConfirmDeleteOpen( false );
			setChatFormToDelete( null );
			createNotice( 'success', 'ChatForm deleted successfully.' );
		} catch ( error ) {
			console.error( 'Failed to delete chatform:', error );
			createNotice( 'error', 'Failed to delete chatform.' );
		} finally {
			setIsUpdating( false );
		}
	};

	// Filter and sort posts
	const processedPosts = allPosts
		? [ ...allPosts ]
				.filter( ( post ) => {
					if ( ! searchTerm ) {
						return true;
					}
					const searchLower = searchTerm.toLowerCase();
					return post.title.rendered
						.toLowerCase()
						.includes( searchLower );
				} )
				.sort( ( a, b ) => {
					if ( ! sortConfig.key ) {
						return 0;
					}

					let aValue, bValue;

					switch ( sortConfig.key ) {
						case 'title':
							aValue = a.title.rendered.toLowerCase();
							bValue = b.title.rendered.toLowerCase();
							break;
						case 'chats':
							aValue = a.meta.wazchat_form_submissions || 0;
							bValue = b.meta.wazchat_form_submissions || 0;
							break;
						default:
							return 0;
					}

					if ( aValue < bValue ) {
						return sortConfig.direction === 'asc' ? -1 : 1;
					}
					if ( aValue > bValue ) {
						return sortConfig.direction === 'asc' ? 1 : -1;
					}
					return 0;
				} )
		: [];

	// Calculate pagination
	const totalItems = processedPosts?.length || 0;
	const totalPages = Math.ceil( totalItems / perPage );
	const paginatedPosts = processedPosts?.slice(
		( page - 1 ) * perPage,
		page * perPage
	);

	const handleSort = ( key ) => {
		setSortConfig( ( prevConfig ) => ( {
			key,
			direction:
				prevConfig.key === key && prevConfig.direction === 'asc'
					? 'desc'
					: 'asc',
		} ) );
	};

	const handlePreviousPage = () => {
		if ( page > 1 ) {
			setPage( page - 1 );
		}
	};

	const handleNextPage = () => {
		if ( page < totalPages ) {
			setPage( page + 1 );
		}
	};

	useEffect( () => {
		setPage( 1 );
	}, [ searchTerm ] );

	const pageOptions = Array.from( { length: totalPages || 0 }, ( _, i ) => ( {
		label: String( i + 1 ),
		value: String( i + 1 ),
	} ) );

	const SortIcon = ( { columnKey } ) => {
		if ( sortConfig.key !== columnKey ) {
			return null;
		}
		return (
			<Icon
				icon={ sortConfig.direction === 'asc' ? arrowUp : arrowDown }
			/>
		);
	};

	// if (isLoading) {
	// 	return <div>{__("Loading...", "wazchat")}</div>;
	// }

	// Define default layouts
	const defaultLayouts = {
		table: {},
	};
	const [ view, setView ] = useState( {
		type: 'table',
		perPage: 10,
		page: 1,
		layout: defaultLayouts.table.layout,
		fields: [ 'title.rendered', 'status', 'chats', 'actions' ],
		sort: {
			field: 'title.rendered',
			direction: 'asc',
		},
		search: '',
		supportedLayouts: [ 'table' ], // Add this line
		filters: [], // Initialize as empty array
	} );

	const fields = useMemo(
		() => [
			{
				id: 'title.rendered',
				label: __( 'Title', 'wazchat' ),
				getValue: ( { item } ) => item.title.rendered,
				// render: ({ item }) => item.title.rendered,
				render: ( { item } ) => (
					<a
						className="awsm-wc-dataview-link"
						onClick={ () => handleEditClick( item ) }
					>
						{ item.title.rendered }
					</a>
				),
				enableSorting: true,
				enableGlobalSearch: true,
			},
			// {
			// 	id: "status",
			// 	label: __("Status", "wazchat"),
			// 	getValue: ({ item }) => item.status,
			// 	render: ({ item }) => (
			// 		<ToggleControl
			// 			__nextHasNoMarginBottom
			// 			checked={item.status === "publish"}
			// 			onChange={() => handleStatusToggle(item)}
			// 		/>
			// 	),
			// 	enableSorting: false,
			// 	filterBy: {
			// 		operators: ["isAny"],
			// 		options: [
			// 			{ label: "Published", value: "publish" },
			// 			{ label: "Draft", value: "draft" },
			// 		],
			// 	},
			// },
			{
				id: 'chats',
				label: __( 'Chats', 'wazchat' ),
				getValue: ( { item } ) =>
					item.meta?.wazchat_form_submissions || 0,
				render: ( { item } ) =>
					item.meta?.wazchat_form_submissions || 0,
				enableSorting: true,
			},
			{
				id: 'actions',
				label: __( 'Actions', 'wazchat' ),
				getValue: () => '',
				render: ( { item } ) => (
					<DropdownMenu
						icon={ moreVertical }
						label="More options"
						controls={ [
							{
								title: 'Edit',
								icon: edit,
								onClick: () => handleEditClick( item ),
							},
							...( isWazChat
								? [
										{
											title: 'Delete',
											icon: trash,
											onClick: () =>
												handleDeleteClick( item ),
										},
								  ]
								: [] ),
						] }
					/>
				),
				enableSorting: false,
			},
		],
		[ handleStatusToggle, handleEditClick, handleDeleteClick ]
	);

	const { data: shownData, paginationInfo } = useMemo( () => {
		return filterSortAndPaginate( allPosts, view, fields );
	}, [ view, allPosts ] );

	useEffect( () => {
		refreshData();
	}, [] );

	return (
		<div className={ 'awsm-wc-chat-form-table' }>
			<DataViews
				isLoading={ isLoading }
				getItemId={ ( item ) => item.id.toString() }
				paginationInfo={ paginationInfo }
				data={ shownData }
				view={ view }
				fields={ fields }
				onChangeView={ setView }
				defaultLayouts={ defaultLayouts }
			/>
		</div>
	);
};
