import { useEffect, useState } from 'react';
import {
	Box,
	Button,
	Card,
	Checkbox,
	Dialog,
	DialogActions,
	DialogContent,
	DialogTitle,
	FormControlLabel,
	MenuItem,
	Select,
	Skeleton,
	Typography,
	Divider,
} from '@mui/material';
import { initialState } from '../redux/features/pallets/palletsSlice';
import {
	useGetGlobalSettingsQuery,
	useSaveGlobalSettingsMutation,
} from '../redux/Actions/GlobalSettingsAction';
import {
	useGetPalletsQuery,
	useSavePalletMutation,
	useDeletePalletMutation,
} from '../redux/Actions/PalletsCRUDAction';
import { useDispatch, useSelector } from 'react-redux';
import { setAlert } from '../redux/features/providers/providersSlice';
import { dispatchAlert } from '../redux/Actions/ProvidersAction';
import { useUpdatePalletsPlanMutation } from '../redux/Actions/PlanActions';
import { useGetMultiPalletProductsQuery } from '../redux/Actions/WooCommerceDataAction';
import { Spinner, PalletModal, PalletsTable, MultiPalletItems } from '../components';

const Pallets = () => {
	const admin_obj = eniture_rtsq || {};
	const [palletsSettings, setPalletsSettings] = useState(initialState);
	const [nextSubcribedPackage, setNextSubcribedPackage] = useState('disable');
	const [openPalletModal, setOpenPalletModal] = useState(false);
	const [selectedPallet, setSelectedPallet] = useState(null);
	const [openDeleteModal, setOpenDeleteModal] = useState(false);
	const [palletToDelete, setPalletToDelete] = useState(null);
	const [isMultiPalletItem, setIsMultiPalletItem] = useState(false);
	const [selectedProduct, setSelectedProduct] = useState(null);

	const { data, isLoading, isFetching } = useGetGlobalSettingsQuery(
		{ url: admin_obj?.eniture_rtsq_rest_url, action: 'get_pallets_settings' },
		{ refetchOnMountOrArgChange: true }
	);
	const {
		data: palletsData,
		isLoading: isLoadingPallets,
		isFetching: isFetchingPallets,
	} = useGetPalletsQuery(admin_obj?.eniture_rtsq_rest_url);
	const {
		data: multiPalletProductsData,
		isLoading: isLoadingMultiPalletProducts,
		isFetching: isFetchingMultiPalletProducts,
	} = useGetMultiPalletProductsQuery({ url: admin_obj?.eniture_rtsq_rest_url });
	const [saveGlobalSettings, { isLoading: isSaving }] = useSaveGlobalSettingsMutation();
	const [updatePalletsPlan, { isLoading: isUpdating }] = useUpdatePalletsPlanMutation();
	const [savePallet, { isLoading: isSavingPallet }] = useSavePalletMutation();
	const [deletePallet, { isLoading: isDeletingPallet }] = useDeletePalletMutation();
	const dispatch = useDispatch();
	const { planInfo } = useSelector(state => state.plan);

	useEffect(() => {
		if (isLoading || isFetching) return;

		setPalletsSettings(prevState => ({
			...prevState,
			...data?.data,
		}));

		const nextSubPckg = data?.data?.status?.nextSubcribedPackage?.nextSubscriptionSCAC;
		const nextToBeChargedStatus = data?.data?.status?.nextSubcribedPackage
			? Number(data?.data?.status?.nextSubcribedPackage?.nextToBeChargedStatus)
			: 0;
		setNextSubcribedPackage(nextToBeChargedStatus ? nextSubPckg : 'disable');
	}, [isLoading, isFetching, data?.data]);

	const handleChange = (name, value) => {
		setPalletsSettings(prevState => ({
			...prevState,
			[name]: value,
		}));
	};

	const handlePlanChange = selectedPlan => {
		if (!selectedPlan || selectedPlan === '0') return;

		if (selectedPlan !== 'TR' && planInfo?.name && planInfo?.name?.toLowerCase() === 'trial') {
			dispatch(
				setAlert(
					dispatchAlert(
						true,
						'You must subscribe to the paid plan for the Real-time Shipping Quotes to buy the Add-on',
						'error'
					)
				)
			);

			const nextSubPckg = palletsSettings?.status?.nextSubcribedPackage?.nextSubscriptionSCAC;
			const nextToBeChargedStatus = palletsSettings?.status?.nextSubcribedPackage
				? Number(palletsSettings?.status?.nextSubcribedPackage?.nextToBeChargedStatus)
				: 0;
			setNextSubcribedPackage(nextToBeChargedStatus ? nextSubPckg : 'disable');

			return;
		}

		const payload = {
			action: 'update_pallets_plan',
			url: admin_obj?.eniture_rtsq_rest_url,
			selected_plan: selectedPlan,
		};

		dispatch(setAlert(dispatchAlert(true, 'Updating plan...', 'info')));
		updatePalletsPlan(payload)
			.unwrap()
			.then(resp => {
				dispatch(
					setAlert(dispatchAlert(true, resp?.message, resp.error ? 'error' : 'success'))
				);

				setPalletsSettings(prevState => ({
					...prevState,
					...resp,
				}));
				// if the option is disabled, reset the nextSubcribedPackage state
				if (!resp?.error && selectedPlan === 'disable') setNextSubcribedPackage('disable');
			})
			.catch(error => {
				console.error('Failed to update plan:', error);
				dispatch(setAlert(dispatchAlert(true, 'Failed to update plan', 'error')));
			});
	};

	const handleSubmit = () => {
		const provider_suspensions = {};
		if (Array.isArray(palletsSettings?.ltl_providers)) {
			palletsSettings.ltl_providers.forEach(p => {
				provider_suspensions[p.uuid] = p.suspend_pallets;
			});
		}

		const payload = {
			action: 'save_pallets_settings',
			url: admin_obj?.eniture_rtsq_rest_url,
			eniture_suspend_pallets_use: palletsSettings?.eniture_suspend_pallets_use || false,
			provider_suspensions,
		};

		saveGlobalSettings(payload)
			.unwrap()
			.then(resp => {
				dispatch(
					setAlert(dispatchAlert(true, resp?.message, resp.error ? 'error' : 'success'))
				);
			})
			.catch(error => {
				console.error('Failed to save settings:', error);
				dispatch(setAlert(dispatchAlert(true, 'Failed to save settings', 'error')));
			});
	};

	// Pallet CRUD handlers
	const handleAddNew = () => {
		setSelectedPallet(null);
		setIsMultiPalletItem(false);
		setSelectedProduct(null);
		setOpenPalletModal(true);
	};

	const handleEditPallet = pallet => {
		setSelectedPallet(pallet);
		setIsMultiPalletItem(pallet?.is_multi_item_pallet == 1);
		setSelectedProduct(pallet?.product_id ? { id: pallet.product_id } : null);
		setOpenPalletModal(true);
	};

	const handleDeletePallet = pallet => {
		setPalletToDelete(pallet);
		setOpenDeleteModal(true);
	};

	// Multi-pallet item handlers
	const handleAddMultiPalletItem = product => {
		setSelectedPallet(null);
		setIsMultiPalletItem(true);
		setSelectedProduct(product);
		setOpenPalletModal(true);
	};

	const handleEditMultiPalletItem = pallet => {
		setSelectedPallet(pallet);
		setIsMultiPalletItem(true);
		setSelectedProduct(pallet?.product_id ? { id: pallet.product_id } : null);
		setOpenPalletModal(true);
	};

	const handleDeleteMultiPalletItem = pallet => {
		setPalletToDelete(pallet);
		setOpenDeleteModal(true);
	};

	const handleSavePallet = formData => {
		const payload = {
			url: admin_obj?.eniture_rtsq_rest_url,
			...formData,
		};

		savePallet(payload)
			.unwrap()
			.then(resp => {
				dispatch(
					setAlert(dispatchAlert(true, resp?.message, resp.error ? 'error' : 'success'))
				);
				if (!resp.error) {
					setOpenPalletModal(false);
					setSelectedPallet(null);
				}
			})
			.catch(error => {
				console.error('Failed to save pallet:', error);
				dispatch(setAlert(dispatchAlert(true, 'Failed to save pallet', 'error')));
			});
	};

	const handleToggleAvailable = pallet => {
		savePallet({
			url: admin_obj?.eniture_rtsq_rest_url,
			...pallet,
			is_available: pallet?.is_available == 1 ? 0 : 1,
		})
			.unwrap()
			.then(resp => {
				dispatch(
					setAlert(dispatchAlert(true, resp?.message, resp.error ? 'error' : 'success'))
				);
			})
			.catch(error => {
				console.error('Failed to update pallet availability:', error);
				dispatch(setAlert(dispatchAlert(true, 'Failed to save pallet', 'error')));
			});
	};

	const handleConfirmDelete = () => {
		if (!palletToDelete) return;

		const payload = {
			url: admin_obj?.eniture_rtsq_rest_url,
			id: palletToDelete.id,
		};

		deletePallet(payload)
			.unwrap()
			.then(resp => {
				dispatch(
					setAlert(dispatchAlert(true, resp?.message, resp.error ? 'error' : 'success'))
				);
				if (!resp.error) {
					setOpenDeleteModal(false);
					setPalletToDelete(null);
				}
			})
			.catch(error => {
				console.error('Failed to delete pallet:', error);
				dispatch(setAlert(dispatchAlert(true, 'Failed to delete pallet', 'error')));
			});
	};

	const formatPlanInfo = plan => {
		const hits =
			plan?.pHits && Number(plan.pHits)
				? parseInt(plan.pHits, 10).toLocaleString()
				: plan?.pHits || 0;

		return `${hits}/${plan?.pPeriod?.toLocaleLowerCase().slice(0, 2)} ($${plan?.pCost})`;
	};

	const formatCurrentPlan = () => {
		const planStatus = palletsSettings?.status || null;
		const subPkg = planStatus?.subscribedPackage || null;
		if (!planStatus || !subPkg) return 'Not subscribed';

		if (isPlanExpired()) return 'Your current subscription is expired.';

		const pkgHits =
			subPkg?.packageHits === 'Unlimited'
				? 'Unlimited'
				: parseInt(subPkg?.packageHits || 0, 10).toLocaleString();
		const planInfo = `${pkgHits}/${
			subPkg?.packageDuration?.toLowerCase()?.slice(0, 2) || 0
		} ($${subPkg?.packageCost || 0})`;
		const startDate = planStatus?.subscriptionInfo?.subscriptionTime
			? getFormattedDate(planStatus?.subscriptionInfo?.subscriptionTime)
			: 'N/A';
		const endDate = planStatus?.subscriptionInfo?.expiryTime
			? getFormattedDate(planStatus?.subscriptionInfo?.expiryTime)
			: 'N/A';

		let markup = '';
		for (let i = 0; i < 3; i++) {
			markup += `<Typography variant='body2'>${
				i === 0
					? `${planInfo}`
					: i === 1
					? `Start date: ${startDate}`
					: `End date: ${endDate}`
			}</Typography> <br />`;
		}

		return markup;
	};

	const getFormattedDate = dateStr => {
		const date = new Date(dateStr.replace(' ', 'T'));
		const options = { month: 'short', day: 'numeric', year: 'numeric' };
		let formatted = date.toLocaleDateString('en-US', options);
		formatted = formatted.replace(',', '');

		return formatted;
	};

	const formatCurrentUsage = () => {
		const planStatus = palletsSettings?.status || null;
		if (!planStatus || isPlanExpired()) return 'Not available';

		const subPkgHits = planStatus?.subscribedPackageHitsStatus || {};
		const consumedHitsPrcent = subPkgHits?.consumedHitsPrcent
			? subPkgHits?.consumedHitsPrcent + '%'
			: '';
		return `${subPkgHits?.consumedHits || 0}/${
			subPkgHits?.packageHits || 0
		} ${consumedHitsPrcent}`;
	};

	const isPlanExpired = () => {
		const planStatus = palletsSettings?.status || null;
		const expiryDate = new Date(planStatus?.subscriptionInfo?.expiryTime.replace(' ', 'T'));
		expiryDate.setHours(23, 59, 59, 999);

		const planExpired =
			planStatus &&
			(!Number(planStatus?.subscriptionInfo?.subscriptionStatus) || Date.now() > expiryDate);

		return planExpired;
	};

	return (
		<>
			{isLoading || isFetching ? (
				<Skeleton variant='rectangular' animation='wave' height={500} />
			) : (
				<>
					<Card variant='elevation' sx={{ p: 2, minWidth: 600 }} component={Box}>
					<Typography variant='h6' fontWeight='bold' mb={2}>
						Pallets
					</Typography>

					<Typography
						variant='body2'
						color='textSecondary'
						mb={3}>
						The Pallet Size feature calculates the optimal packaging solution based on your
						standard Pallet size. The solution is available graphically to assist order
						fulfillment. The next subscription begins when the current one expires or is
						depleted, which ever comes first. Refer to the{' '}
						<a href="https://eniture.com/woocommerce-real-time-shipping-quotes/" target="_blank" rel="noopener noreferrer">User's Guide</a>{' '}
						for more detailed information.
					</Typography>

					<Box mb={2}>
						{/* Auto-renew */}
						<Typography variant='body1' fontWeight='bold' mb={1}>
							Auto-renew
						</Typography>
						<Select
							size='small'
							title='Auto-renew'
							defaultValue='disable'
							value={nextSubcribedPackage || 'disable'}
							onChange={e => {
								setNextSubcribedPackage(e.target.value);
								handlePlanChange(e.target.value);
							}}
							sx={{ minWidth: '25vw', width: '25vw' }}
							disabled={isSaving || isUpdating}>
							<MenuItem value='disable'>Disable (default)</MenuItem>
							{Number(palletsSettings?.trialAvailable) && (
								<MenuItem value='TR'>Trial (100/15 days) (Free)</MenuItem>
							)}

							{/* Plans list */}
							{palletsSettings?.ListOfPackages?.Info?.map((plan, index) => (
								<MenuItem key={index} value={plan.pSCAC}>
									{formatPlanInfo(plan)}
								</MenuItem>
							))}
						</Select>

						{/* Plan info */}
						<Box my={2}>
							<Typography variant='body1' fontWeight='bold'>
								Current plan
							</Typography>

							<Typography
								variant='body2'
								dangerouslySetInnerHTML={{ __html: formatCurrentPlan() }}
							/>
						</Box>

						{/* Usage info */}
						<Box my={2}>
							<Typography variant='body1' fontWeight='bold'>
								Current usage
							</Typography>
							<Typography variant='body2'>{formatCurrentUsage()}</Typography>
						</Box>

						<FormControlLabel
							control={<Checkbox />}
							label='Suspend use'
							title='Suspend use'
							checked={palletsSettings?.eniture_suspend_pallets_use || false}
							onChange={e => handleChange('eniture_suspend_pallets_use', e.target.checked)}
						/>

						{Array.isArray(palletsSettings?.ltl_providers) && palletsSettings.ltl_providers.length > 0 && (
							<Box mt={2} sx={{ opacity: palletsSettings?.eniture_suspend_pallets_use ? 0.4 : 1, pointerEvents: palletsSettings?.eniture_suspend_pallets_use ? 'none' : 'auto' }}>
								<Typography variant='body2' fontWeight='bold' mb={1}>
									Use for the following LTL provider integrations &nbsp;<Typography variant='caption' color='text.secondary' component='span'>(Listed by nickname)</Typography>
								</Typography>
								{palletsSettings.ltl_providers.map(provider => (
									<Box key={provider.uuid}>
										<FormControlLabel
											control={
												<Checkbox
													checked={!provider.suspend_pallets}
													onChange={e => {
														handleChange('ltl_providers', palletsSettings.ltl_providers.map(p =>
															p.uuid === provider.uuid
																? { ...p, suspend_pallets: !e.target.checked }
																: p
														));
													}}
												/>
											}
											label={provider.name}
										/>
									</Box>
								))}
							</Box>
						)}
					</Box>

					<Box mt={2} display='flex' justifyContent='flex-end'>
						<Button
							title='Save'
							sx={{ textTransform: 'capitalize' }}
							disabled={isSaving}
							onClick={handleSubmit}
							variant='contained'>
							{isSaving ? <Spinner size={25} /> : 'Save'}
						</Button>
					</Box>
			</Card>

			<Card variant='elevation' sx={{ p: 2, minWidth: 600, mt: 3 }} component={Box}>
					{/* Pallets CRUD Section */}
					<Box>
					<Box display='flex' justifyContent='flex-end' mb={2}>
						<Button
							variant='contained'
							color='primary'
							onClick={handleAddNew}
							sx={{ textTransform: 'capitalize' }}>
							Add Pallet
						</Button>
					</Box>

					<PalletsTable
						pallets={(palletsData?.data || []).filter(pallet => pallet.is_multi_item_pallet != 1)}
						onEdit={handleEditPallet}
						onDelete={handleDeletePallet}
						onToggleAvailable={handleToggleAvailable}
						isToggling={isSavingPallet}
						isLoading={isLoadingPallets || isFetchingPallets}
					/>
				</Box>

				<Divider sx={{ my: 3 }} />

				{/* Multi-pallet Items Section */}
				<MultiPalletItems
					products={multiPalletProductsData?.data || []}
					pallets={palletsData?.data || []}
					onAddPallet={handleAddMultiPalletItem}
					onEditPallet={handleEditMultiPalletItem}
					onDeletePallet={handleDeleteMultiPalletItem}
					isLoading={isLoadingMultiPalletProducts || isFetchingMultiPalletProducts}
				/>

			</Card>

			{/* Pallet Modal */}
			<PalletModal
				open={openPalletModal}
				onClose={() => {
					setOpenPalletModal(false);
					setSelectedPallet(null);
					setIsMultiPalletItem(false);
					setSelectedProduct(null);
				}}
				onSave={handleSavePallet}
				palletData={selectedPallet}
				isSaving={isSavingPallet}
				isMultiPalletItem={isMultiPalletItem}
				selectedProduct={selectedProduct}
			/>

			{/* Delete Confirmation Modal */}
			<Dialog
				open={openDeleteModal}
				onClose={() => {
					setOpenDeleteModal(false);
					setPalletToDelete(null);
				}}
				maxWidth='sm'
				fullWidth>
				<DialogTitle>
					Delete {palletToDelete?.is_multi_item_pallet == 1 ? 'Multi-Pallet Item' : 'Pallet'}
				</DialogTitle>
				<DialogContent>
					<Typography>
						Are you sure you want to delete "{palletToDelete?.nickname}"? This action cannot be undone.
					</Typography>
				</DialogContent>
				<DialogActions>
					<Button
						onClick={() => {
							setOpenDeleteModal(false);
							setPalletToDelete(null);
						}}
						disabled={isDeletingPallet}>
						Cancel
					</Button>
					<Button
						onClick={handleConfirmDelete}
						variant='contained'
						color='error'
						disabled={isDeletingPallet}>
						{isDeletingPallet ? <Spinner size={20} /> : 'Delete'}
					</Button>
				</DialogActions>
			</Dialog>
			</>
		)}
		</>
	);
};

export default Pallets;
