import { useState, useEffect, useRef } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import { showAlert } from '../../../utils/alertHelper';
import { setActiveTabWithParam } from '../../../utils';
import { IoChevronDownOutline } from 'react-icons/io5';
import { RiSearch2Line } from 'react-icons/ri';
import { FiCopy } from 'react-icons/fi';
import { PiPencilSimpleLineDuotone, PiTrash, PiEye } from 'react-icons/pi';
import Pagination from '../Pagination';

import { getShortCodeIcon } from '../../../utils/common';

const ShortCodes = (props) => {
	const { currentTab, setCurrentTab, setShortCodeConfig, setShortCodeTitle } = props;
	const [shortCodes, setShortCodes] = useState({});
	const [itemsPerPage, setItemsPerPage] = useState(10);
	const itemsPerPageOptions = [5, 10, 20];
	const [page, setPage] = useState(1);
	const [searchTerm, setSearchTerm] = useState('');
	const [itemsPerPageDropdownOpen, setItemsPerPageDropdownOpen] = useState(false);
	const dropdownRef = useRef(null);
	const { accounts, activeAccount } = EDBIData;

	useEffect(() => {
		const handleClickOutside = (event) => {
			if (dropdownRef.current && !dropdownRef.current.contains(event.target)) {
				setItemsPerPageDropdownOpen(false);
			}
		};

		document.addEventListener('mousedown', handleClickOutside);
		return () => {
			document.removeEventListener('mousedown', handleClickOutside);
		};
	}, []);

	const fetchShortCodes = () => {
		wp.ajax
			.post('edbi_get_shortcodes', {
				account_id: activeAccount?.id,
				nonce: EDBIData?.ajaxNonce,
			})
			.then((response) => {
				setShortCodes(response);
			})
			.catch((error) => {
				console.error(error);
				showAlert({
					title: __('Error', 'easy-dropbox-integration'),
					text: __(
						'An error occurred while fetching ShortCodes',
						'easy-dropbox-integration'
					),
					icon: 'error',
					showCancelButton: false,
					confirmButtonText: 'Ok',
				});
			});
	};

	useEffect(() => {
		if (currentTab === 'shortcodes') {
			fetchShortCodes();
		}

		return () => {};
	}, []);

	const removeShortCode = (shortcode) => {
		showAlert({
			title: 'Remove Shortcode',
			text: 'Are you sure you want to remove this Shortcode?',
			icon: 'warning',
			showCancelButton: true,
			confirmButtonText: 'Remove',
			confirmButtonColor: '#d33',
			cancelButtonText: 'No',
			reverseButtons: true,
		}).then((result) => {
			if (result.isConfirmed) {
				wp.ajax
					.post('edbi_delete_shortcode', {
						nonce: EDBIData?.ajaxNonce,
						id: shortcode,
					})
					.then((response) => {
						// remove the shortcode from the list and update the state
						const newShortCodes = { ...shortCodes };
						delete newShortCodes[shortcode];
						setShortCodes(newShortCodes);
						fetchShortCodes();

						showAlert({
							title: __('Success', 'easy-dropbox-integration'),
							text: __('Shortcode removed successfully', 'easy-dropbox-integration'),
							icon: 'success',
							showCancelButton: false,
							confirmButtonText: 'Ok',
						});
					})
					.catch((error) => {
						console.error(error);

						showAlert({
							title: __('Error', 'easy-dropbox-integration'),
							text: __(
								'An error occurred while removing Shortcode',
								'easy-dropbox-integration'
							),
							icon: 'error',
							showCancelButton: false,
							confirmButtonText: 'Ok',
						});
					});
			}
		});
	};

	const duplicateShortCode = (shortcode) => {
		wp.ajax
			.post('edbi_duplicate_shortcode', {
				nonce: EDBIData?.ajaxNonce,
				id: shortcode,
			})
			.then((response) => {
				setShortCodes({
					...shortCodes,
					[response.data.id]: response.data,
				});
				fetchShortCodes();

				showAlert({
					title: __('Success', 'easy-dropbox-integration'),
					text: __('Shortcode duplicated successfully', 'easy-dropbox-integration'),
					icon: 'success',
					showCancelButton: false,
					confirmButtonText: 'Ok',
				});
			})
			.catch((error) => {
				console.error(error);
				showAlert({
					title: __('Error', 'easy-dropbox-integration'),
					text: __(
						'An error occurred while duplicating Shortcode',
						'easy-dropbox-integration'
					),
					icon: 'error',
					showCancelButton: false,
					confirmButtonText: 'Ok',
				});
			});
	};

	const capitalizer = (str) => {
		if (!str) return '';
		return str.charAt(0).toUpperCase() + str.slice(1);
	};

	const shortCodeList = Object.values(shortCodes);

	const filteredShortCodeList = shortCodeList.filter((item) => {
		const search = searchTerm.toLowerCase();
		return (
			item.id.toString().includes(search) ||
			item.title.toLowerCase().includes(search) ||
			item.type.toLowerCase().includes(search)
		);
	});

	const indexOfLastItem = page * itemsPerPage;
	const indexOfFirstItem = indexOfLastItem - itemsPerPage;
	const currentItems = filteredShortCodeList.slice(indexOfFirstItem, indexOfLastItem);

	function hexToRgba(hex, alpha = 0.1) {
		// Remove hash if present
		hex = hex.replace('#', '');
		// Parse r, g, b
		const bigint = parseInt(hex, 16);
		const r = (bigint >> 16) & 255;
		const g = (bigint >> 8) & 255;
		const b = bigint & 255;
		return `rgba(${r}, ${g}, ${b}, ${alpha})`;
	}
	return (
		<div className='edbi-shortcodes'>
			<div className='edbi-shortcodes__header'>
				<h3 className='edbi-shortcodes__header__title'>
					{__('ShortCodes', 'easy-dropbox-integration')}
					<span>
						({Object.keys(shortCodes).length} {__(' Items', 'easy-dropbox-integration')}
						)
					</span>
				</h3>

				<div className='edbi-shortcodes__header__actions'>
					<h3>{__('Item Per Page', 'easy-dropbox-integration')}</h3>
					<div style={{ position: 'relative' }} ref={dropdownRef}>
						<button
							onClick={() => setItemsPerPageDropdownOpen(!itemsPerPageDropdownOpen)}
							className='edbi-shortcodes__header__actions__btn'
						>
							<span style={{ opacity: '.8' }}>
								{__(itemsPerPage, 'easy-dropbox-integration')}
							</span>
							<IoChevronDownOutline style={{ opacity: '0.7' }} />
						</button>
						{itemsPerPageDropdownOpen && (
							<div className='edbi-shortcodes__header__actions__dropdown'>
								{itemsPerPageOptions.map((option, index) => (
									<div
										key={index}
										className='edbi-shortcodes__header__actions__dropdown__item'
										onClick={() => {
											setItemsPerPage(option);
											setItemsPerPageDropdownOpen(false);
										}}
										style={{
											borderBottom:
												index !== itemsPerPageOptions.length - 1
													? '1px solid rgba(38, 47, 64, 0.1)'
													: 'none',
										}}
									>
										{__(option, 'easy-dropbox-integration')}
									</div>
								))}
							</div>
						)}
					</div>
					<form className='edbi-shortcodes__header__actions__form'>
						<input
							type='text'
							placeholder={__(
								'Search by ID, Title, or Type...',
								'easy-dropbox-integration'
							)}
							value={searchTerm}
							onChange={(e) => setSearchTerm(e.target.value)}
						/>
						<button
							onClick={(e) => e.preventDefault()}
							className='edbi-shortcodes__header__actions__form__button'
						>
							<RiSearch2Line className='edbi-search__icon' />
						</button>
					</form>
				</div>
			</div>
			<div className='edbi-shortcodes__container'>
				<table className='edbi-shortcodes__table'>
					<thead className='edbi-shortcodes__table__head'>
						<tr>
							<th className='edbi-shortcodes__table__head__checkbox'>
								<label className='chk-label'>
									<input
										type='checkbox'
										// checked={bulkMode}
										// onChange={toggleBulkMode}
									/>
									<span className='custom-circle' aria-hidden='true'>
										<svg viewBox='0 0 24 24' aria-hidden='true'>
											<path d='M5 12.5l4 4L19 7.5'></path>
										</svg>
									</span>
								</label>{' '}
								{__('ID', 'easy-dropbox-integration')}
							</th>
							<th>{__('Title', 'easy-dropbox-integration')}</th>
							<th>{__('Type', 'easy-dropbox-integration')}</th>
							<th>
								<div className='edbi-sort__shortcode'>
									{__('ShortCode', 'easy-dropbox-integration')}
									{/* <FaCaretDown className='edbi-sort__icon' /> */}
								</div>
							</th>
							{/* <th>
								<div className='edbi-sort__shortcode'>
									{__('Location', 'easy-dropbox-integration')}
									<FaCaretDown className='edbi-sort__icon' />
								</div>
							</th> */}
							<th>{__('Created', 'easy-dropbox-integration')}</th>
							<th>{__('Status', 'easy-dropbox-integration')}</th>
							<th>{__('Actions', 'easy-dropbox-integration')}</th>
						</tr>
					</thead>
					<tbody className='edbi-shortcodes__table__body'>
						{Object.keys(shortCodes).length === 0 ? (
							<tr>
								<td colSpan={7} className='edbi-shortcodes__table__empty'>
									{__('No ShortCodes found', 'easy-dropbox-integration')}
								</td>
							</tr>
						) : (
							<>
								{currentItems.map((item) => {
									const { icon, color } = getShortCodeIcon(item.type);
									return (
										<tr className='edbi-shortcodes__table__row' key={item.id}>
											<td>
												<div className='edbi-shortcodes__table__head__checkbox'>
													<label className='chk-label'>
														<input
															type='checkbox'
															// checked={bulkMode}
															// onChange={toggleBulkMode}
														/>
														<span
															className='custom-circle'
															aria-hidden='true'
														>
															<svg
																viewBox='0 0 24 24'
																aria-hidden='true'
															>
																<path d='M5 12.5l4 4L19 7.5'></path>
															</svg>
														</span>
													</label>
													<h4>{item.id}</h4>
												</div>
											</td>
											<td>
												<h4>{item.title}</h4>
											</td>
											<td>
												<div className='edbi-shortcodes__table__row__type'>
													<div
														style={{
															backgroundColor: hexToRgba(color),
														}}
														className='edbi-shortcodes__table__row__type__icon__wrapper'
													>
														<div className='edbi-shortcodes__table__row__type__icon'>
															{icon}
														</div>
													</div>
													<h4>
														{item?.type
															?.replace('-', ' ')
															.toLowerCase()
															.replace(/(?<= )[^\s]|^./g, (a) =>
																a.toUpperCase()
															)}
													</h4>
												</div>
											</td>
											<td>
												<div
													className='edbi-shortcodes__table__row__shortcode'
													title='Click to copy shortcode'
													onClick={() => {
														navigator.clipboard.writeText(
															`[easy_dropbox_integration id="${item.id}"]`
														);
														showAlert({
															title: __(
																'Shortcode Copied',
																'easy-dropbox-integration'
															),
															icon: 'success',
															position: 'top',
															toast: true,
															showConfirmButton: false,
															timer: 1500,
														});
													}}
												>
													<FiCopy />
													[easy_dropbox_integration id="{item.id}"]
												</div>
											</td>
											{/* <td className='edbi-shortcodes__table__row__location'>
												<h4>{__('0', 'easy-dropbox-integration')}</h4>
											</td> */}
											<td>
												<h4>{item.created_at}</h4>
											</td>
											<td>
												<div
													className='edbi-shortcodes__table__row__status'
													style={{
														backgroundColor:
															item.status === 'active'
																? '#5820e51a'
																: '#5c637e1a',
														color:
															item.status === 'active'
																? '#5820e5'
																: '#5c637e',
													}}
												>
													<div
														className='edbi-shortcodes__table__row__status__indicator'
														style={{
															backgroundColor:
																item.status === 'active'
																	? '#5820e5'
																	: '#5c637e',
														}}
													/>

													<h4 className='edbi-shortcodes__table__row__status__text'>
														{capitalizer(item.status)}
													</h4>
												</div>
											</td>
											<td>
												<div className='edbi-shortcodes__table__row__actions'>
													<button
														className='edbi-shortcodes__table__row__actions__button edbi-edit'
														title={__(
															'Edit',
															'easy-dropbox-integration'
														)}
														onClick={() => {
															setShortCodeTitle(item.title);
															setShortCodeConfig(
																JSON.parse(item.config)
															);
															setActiveTabWithParam(
																'edit',
																setCurrentTab,
																item.id
															);
														}}
													>
														<PiPencilSimpleLineDuotone />
													</button>
													<button
														className='edbi-shortcodes__table__row__actions__button edbi-delete'
														title={__(
															'Delete',
															'easy-dropbox-integration'
														)}
														onClick={() => removeShortCode(item.id)}
													>
														<PiTrash />
													</button>
													<button
														className='edbi-shortcodes__table__row__actions__button edbi-preview'
														title={__(
															'Preview',
															'easy-dropbox-integration'
														)}
														onClick={() => {
															const previewUrl = `${EDBIData?.siteUrl}edbi-modules/${item.id}/`;
															window.open(previewUrl, '_blank');
														}}
													>
														<PiEye />
													</button>
													<button
														className='edbi-shortcodes__table__row__actions__button edbi-duplicate'
														title={__(
															'Duplicate',
															'easy-dropbox-integration'
														)}
														onClick={() => duplicateShortCode(item.id)}
													>
														<FiCopy />
													</button>
												</div>
											</td>
										</tr>
									);
								})}
							</>
						)}
					</tbody>
				</table>
			</div>
			<div className='edbi-shortcodes__footer'>
				<Pagination
					totalItems={Object.keys(shortCodes).length}
					itemsPerPage={itemsPerPage}
					onPageChange={(page) => setPage(page)}
				/>
			</div>
		</div>
	);
};

export default ShortCodes;
