import React, { useContext, useEffect, useState } from 'react';
import Tooltip from '../../../components/core/Tooltip';
import Select, { components } from 'react-select';
import Modal from '../../../components/core/Modal';
import { SettingsContext } from '../../App/SettingsContext';
import Header from '../Header';
import EereSelect from '../fields/EereSelect';
import EcreSelectPro from '../fields/EcreSelectPro';
import Input from '../fields/Input';
import Switcher from '../fields/Switcher';
import TextArea from '../fields/TextArea';
import { translate } from '../../../Helper';
import Loader from '../../../components/core/Loader';

function RewardTab() {
	const {
		rewardCouponTypeOptions, woocommerceProductOptions, woocommerceProductCategoryOptions, CouponTypeProOption, formData, handleSelectChange, handleInputChange, currency, rewardPointExpiryOptions, SubscriptionProOption, isPro, orderStatusOptions, loading, initialFormData
	} = useContext(SettingsContext);

	// Add a state to track if everything is ready to render
	const [isSelectReady, setIsSelectReady] = useState(false);

	// Subscription modal state — lives here so it survives dropdown unmounting
	const [isSubscriptionModalOpen, setIsSubscriptionModalOpen] = useState(false);
	const handleToggleSubscriptionModal = () => setIsSubscriptionModalOpen(prev => !prev);

	const handlePositiveNumberChange = (key) => (event) => {
		// Get the current value from the event
		let { value } = event.target;

		// Remove the negative sign if it is present
		if (value.startsWith('-')) {
			value = value.slice(1); // Remove the negative sign from the beginning
		}

		// Call the original handleInputChange with the sanitized value
		handleInputChange(key)({ target: { value } });
	};

	// Define the effective reward type once for consistent use throughout the component
	const getEffectiveRewardType = () => {
		return isPro
			? formData.rewardType.value
			: (['sign_up_fee', 'sign_up_fee_percent', 'recurring_fee', 'reward_point', 'recurring_percent'].includes(formData.rewardType.value)
				? initialFormData.rewardType.value
				: formData.rewardType.value);
	};

	const effectiveRewardType = getEffectiveRewardType();

	// Use useEffect to set ready state after the initial render
	useEffect(() => {
		if (formData && formData.rewardType && rewardCouponTypeOptions && rewardCouponTypeOptions.length > 0) {
			setIsSelectReady(true);
		}
	}, [formData, formData.rewardType, rewardCouponTypeOptions]);

	// Return loading until everything is ready
	if (loading) {
		return (
			<div className="reward-settings">
				<Header title={translate('reward_settings')} subtitle={translate('reward_settings_subtitle')} />
				<Loader />
			</div>
		);
	}

	// Return loading until everything is ready
	if (!isSelectReady || !effectiveRewardType) {
		return (
			<div className="reward-settings">
				<Header title={translate('reward_settings')} subtitle={translate('reward_settings_subtitle')} />
			</div>
		);
	}

	return (
		<>
			<div className="reward-settings">
				<Header title={translate('reward_settings')} subtitle={translate('reward_settings_subtitle')} />
				{loading ? <Loader /> :
					<div className="reward-type">
						<div className="reward-type__field ecre-mb-8">
							<EcreSelectPro
								id="reward_type"
								label={translate('reward_type')}
								options={rewardCouponTypeOptions}
								value={
									isPro
										? formData.rewardType.value // Use whatever is selected when Pro
										: (['sign_up_fee', 'sign_up_fee_percent', 'recurring_fee', 'reward_point', 'recurring_percent'].includes(formData.rewardType.value)
											? initialFormData.rewardType.value
											: formData.rewardType.value)
								}
								onChange={handleSelectChange('rewardType')}
								width="320"
								classNamePrefix="echorewards-select"
								isSearchable={false}
								placeholder={translate('select_reward_type')}
								tooltip={translate('reward_type_tooltip')}
								components={{ Option: !isPro ? CouponTypeProOption : SubscriptionProOption }}
								isPro={isPro}
								onSubscriptionClick={handleToggleSubscriptionModal}
								isOptionDisabled={(option) => {
									let disabledOptions = ['sign_up_fee', 'sign_up_fee_percent', 'reward_point', 'recurring_fee', 'recurring_percent'];
									if (isPro && !ecreAdmin.is_woocommerce_subscriptions_active) {
										disabledOptions = disabledOptions.filter((opt) => opt !== 'reward_point');
									}
									return disabledOptions.includes(option.value);
								}}
							/>
						</div>

						{effectiveRewardType !== 'reward_point' && (
							<div className="reward-type__screen">
								<div className="form-group ecre-mb-8">
									<Input
										id="reward_discount_percentage"
										label={`${translate('discount_capital')} ${effectiveRewardType === 'sign_up_fee'
											? translate('sign_up_fee')
											: effectiveRewardType === 'sign_up_fee_percent'
												? translate('sign_up_fee')
											: effectiveRewardType === 'recurring_fee'
												? translate('recurring_fee')
											: effectiveRewardType === 'recurring_percent'
												? translate('recurring_fee')
											: translate(effectiveRewardType)
											} ${translate('amount_lower')} ${['sign_up_fee_percent', 'recurring_percent', 'percent'].includes(effectiveRewardType)
												? '(%)'
												: `(${currency})`
											}`}
										tooltip={translate('discount_tooltip')}
										type="number"
										value={formData.rewardDiscount}
										onChange={handleInputChange('rewardDiscount')}
									/>
								</div>

								{effectiveRewardType === 'percent' && (
									<div className="form-group ecre-mb-8">
										<Input
											id="reward_discount_capping"
											label={`${translate('discount_capping')} (${currency})`}
											tooltip={translate('discount_capping_tooltip')}
											type="number"
											value={formData.rewardDiscountCapping}
											onChange={handleInputChange('rewardDiscountCapping')}
										/>
									</div>
								)}

								{(!['reward_point', 'percent', 'fixed', 'sign_up_fee', 'sign_up_fee_percent'].includes(effectiveRewardType)) && isPro && (
									<div className="form-group ecre-mb-8">
										<Switcher
											id="enable_reward_limit_coupon_usage_subscription"
											checked={isPro ? formData.enableRewardLimitSubscriptionCoupon : false}
											onChange={handleInputChange('enableRewardLimitSubscriptionCoupon')}
											label={translate('reward_limit_coupon_usage_subscription_payments')}
											tooltip={translate('limit_the_coupon_usage_for_subscription_payments_tooltip')}
											marginTop='ecre-mt-2'
											isPro={isPro}
										/>

										{formData.enableRewardLimitSubscriptionCoupon && isPro && (
											<Input
												id="reward_limit_subscription_coupon"
												label={`${translate('number_of_payments_coupon_is_valid_for')} (${currency})`}
												type="number"
												value={formData.rewardLimitSubscriptionCoupon}
												onChange={handleInputChange('rewardLimitSubscriptionCoupon')}
												marginTop='ecre-mt-2'
												isPro={isPro}
											/>
										)}
									</div>
								)}

								<div className="form-group ecre-mb-8">
									<Input
										id="reward_minimum_purchase_amount"
										label={`${translate('min_purchase_reward_coupon')} (${currency})`}
										tooltip={translate('min_purchase_reward_tooltip')}
										type="number"
										value={formData.rewardMinimumPurchaseAmount}
										onChange={handleInputChange('rewardMinimumPurchaseAmount')}
									/>
								</div>

								<div className="form-group ecre-mb-8">
									<Switcher
										id="enable_reward_expiry"
										checked={isPro ? formData.enableRewardExpiry : false}
										onChange={handleInputChange('enableRewardExpiry')}
										label={translate('enable_reward_expiry')}
										tooltip={translate('enable_reward_expiry_tooltip')}
										isPro={isPro}
									/>

									{formData.enableRewardExpiry && isPro && (
										<Input
											id="reward_coupon_validity"
											label={translate('reward_coupon_validity')}
											tooltip={translate('reward_coupon_validity_tooltip')}
											type="number"
											value={formData.rewardCouponValidity}
											onChange={handleInputChange('rewardCouponValidity')}
											marginTop='ecre-mt-2'
											isPro={isPro}
										/>
									)}
								</div>

								<div className="form-group ecre-mb-8">
									<Switcher
										id="enable_reward_coupon_usage_limit"
										checked={isPro ? formData.enableRewardCouponUsageLimit : false}
										onChange={handleInputChange('enableRewardCouponUsageLimit')}
										label={translate('reward_coupon_usage_limit')}
										tooltip={translate('reward_coupon_usage_limit_tooltip')}
										isPro={isPro}
									/>
									{formData.enableRewardCouponUsageLimit && isPro && (
										<Input
											id="reward_coupon_usage_limit"
											label={translate('how_many_times_coupon_used')}
											tooltip={translate('reward_coupon_usages_limit')}
											type="number"
											value={formData.rewardCouponUsageLimit}
											onChange={handleInputChange('rewardCouponUsageLimit')}
											marginTop='ecre-mt-2'
											isPro={isPro}
										/>
									)}
								</div>
							</div>
						)}

						<div className="reward-type__screen">
							<div className="form-group ecre-mb-8">
								<EereSelect
									id="reward_order_status"
									label={translate('offer_reward_order_status')}
									options={orderStatusOptions}
									value={formData.rewardOrderStatus.value}
									onChange={handleSelectChange('rewardOrderStatus')}
									width="320"
									classNamePrefix="echorewards-select"
									isSearchable={false}
									placeholder={translate('offer_reward_order_status_placeholder')}
									tooltip={translate('offer_reward_order_status_label')}
									isPro={isPro}
								/>
							</div>
							<div className="form-group ecre-mb-8">
								<Switcher
									id="enable_reward_delay_time"
									checked={isPro ? formData.enableRewardDelayTime : false}
									onChange={handleInputChange('enableRewardDelayTime')}
									label={translate('enable_reward_delay_time')}
									tooltip={translate('enable_reward_delay_time_tooltip')}
									isPro={isPro}
								/>

								{formData.enableRewardDelayTime && isPro && (
									<Input
										id="reward_delay_time"
										label={translate('reward_delay_time_label')}
										tooltip={translate('reward_delay_time_tooltip')}
										type="number"
										value={formData.rewardDelayTime}
										onChange={handleInputChange('rewardDelayTime')}
										marginTop='ecre-mt-2'
										isPro={isPro}
									/>

								)}
							</div>
						</div>


						{effectiveRewardType === 'reward_point' && isPro && (
							<div className="reward-point__screen">
								<div className="form-group ecre-mb-8">
									<Input
										id="reward_point"
										label={`${translate('reward_point_per_referral')} ${effectiveRewardType === 'percent' ? '(%)' : `(${currency})`}`}
										tooltip={translate('reward_point_tooltip')}
										type="number"
										value={formData.rewardPoint}
										onChange={handleInputChange('rewardPoint')}
									/>
								</div>

								<div className="form-group ecre-mb-8">
									<label className="ecre-text-gray-900 ecre-text-sm ecre-font-medium ecre-block ecre-mb-2">
										<span className="ecre-mr-2.5">{translate('redeem_value')}</span>
										<Tooltip className="ecre-align-[-2px]" content={translate('redeem_value_tooltip')} />
									</label>
									<span>{translate('for_each_capital')} </span> {` `}
									<input type="number" value={formData.redeemPoint} className="!ecre-text-gray-900 !ecre-shadow-none !ecre-text-sm !ecre-font-normal ecre-bg-white !ecre-p-[15px] ecre-w-full ecre-max-w-[80px] !ecre-rounded-lg !ecre-border !ecre-border-[#9CA3AF]" onChange={handlePositiveNumberChange('redeemPoint')} min="0" />
									{` `} <span>{`reward points, customers will get (${currency}) `}</span>
									<input type="number" value={formData.redeemDiscount} className="!ecre-text-gray-900 !ecre-shadow-none !ecre-text-sm !ecre-font-normal ecre-bg-white !ecre-p-[15px] ecre-w-full ecre-max-w-[80px] !ecre-rounded-lg !ecre-border !ecre-border-[#9CA3AF]" onChange={handlePositiveNumberChange('redeemDiscount')} min="0" /> {` `} <span>{`discount`}</span>
								</div>

								<div className="form-group ecre-mb-8">
									<Input
										id="reward_point_amount"
										label={`${translate('min_purchase_reward_point')} ${currency})`}
										tooltip={translate('min_purchase_reward_point_tooltip')}
										type="number"
										value={formData.minimumRewardPointAmount}
										onChange={handleInputChange('minimumRewardPointAmount')}
									/>
								</div>

								<div className="form-group ecre-mb-8">
									<Switcher
										id="enable_reward_point_expiry"
										checked={formData.enableRewardPointExpiry}
										onChange={handleInputChange('enableRewardPointExpiry')}
										label={translate('enable_reward_point_expiry')}
										tooltip={translate('redeem_expary_tooltip')}
									/>

									{
										formData.enableRewardPointExpiry && isPro && (
											<Input
												id="redeem_limit"
												label={translate('reward_point_validity')}
												tooltip={translate('reward_point_validity_tooltip')}
												type="number"
												value={formData.rewardPointExpiry}
												onChange={handleInputChange('rewardPointExpiry')}
												marginTop='ecre-mt-2'
											/>
										)
									}

									{
										formData.enableRewardPointExpiry && isPro && (
											<EereSelect
												id="reward_point_expiry_action"
												label='Action when the reward points expires'
												options={rewardPointExpiryOptions}
												value={formData.rewardPointExpiryAction.value}
												onChange={handleSelectChange('rewardPointExpiryAction')}
												width="320"
												classNamePrefix="echorewards-select"
												isSearchable={false}
												placeholder={translate('select_reward_type')}
												tooltip={translate('reward_point_expiry_action_tooltip')}
												marginTop='ecre-mt-4'
												isPro={isPro}
											/>
										)
									}
								</div>

								<div className="form-group ecre-mb-8">
									<Switcher
										id="enable_reward_expiry"
										checked={formData.enableRedeemLimit}
										onChange={handleInputChange('enableRedeemLimit')}
										label={translate('redeem_limit')}
										tooltip={translate('enable_redeem_limit_tooltip')}
									/>

									{formData.enableRedeemLimit && isPro && (
										<Input
											id="redeem_limit"
											label={translate('how_many_times_point_used')}
											tooltip={translate('redeem_limit_tooltip')}
											type="number"
											value={formData.redeemLimit}
											onChange={handleInputChange('redeemLimit')}
											marginTop='ecre-mt-2'
										/>
									)}
								</div>
							</div>
						)}

						{effectiveRewardType !== 'reward_point' && (
							<>
								<div className="form-group ecre-mb-8">
									<EereSelect
										id="reward_include_products"
										label={translate('include_products')}
										options={woocommerceProductOptions}
										value={formData.rewardIncludeProducts}
										onChange={handleSelectChange('rewardIncludeProducts')}
										width="570"
										classNamePrefix="echorewards-select"
										isSearchable={true}
										placeholder={translate('enter_three_characters')}
										isMulti={true}
										tooltip={translate('include_products_tooltip')}
									/>
								</div>

								<div className="form-group ecre-mb-8">
									<EereSelect
										id="reward_exclude_products"
										label={translate('exclude_products')}
										options={woocommerceProductOptions}
										value={formData.rewardExcludeProducts}
										onChange={handleSelectChange('rewardExcludeProducts')}
										width="570"
										classNamePrefix="echorewards-select"
										isSearchable={true}
										placeholder={translate('enter_three_characters')}
										isMulti={true}
										tooltip={translate('exclude_products_tooltip')}
									/>
								</div>

								<div className="form-group ecre-mb-8">
									<EereSelect
										id="reward_include_categories"
										label={translate('include_categories')}
										options={woocommerceProductCategoryOptions}
										value={formData.rewardIncludeCategories}
										onChange={handleSelectChange('rewardIncludeCategories')}
										width="570"
										classNamePrefix="echorewards-select"
										isSearchable={true}
										placeholder={translate('enter_three_characters')}
										isMulti={true}
										tooltip={translate('include_categories_tooltip')}
									/>
								</div>

								<div className="form-group ecre-mb-8">
									<EereSelect
										id="reward_exclude_categories"
										label={translate('exclude_categories')}
										options={woocommerceProductCategoryOptions}
										value={formData.rewardExcludeCategories}
										onChange={handleSelectChange('rewardExcludeCategories')}
										width="570"
										classNamePrefix="echorewards-select"
										isSearchable={true}
										placeholder={translate('enter_three_characters')}
										isMulti={true}
										tooltip={translate('exclude_categories_tooltip')}
									/>
								</div>
							</>
						)}
					</div>}
			</div>
			{/* Subscription modal — rendered outside the dropdown so it survives unmounting */}
			<Modal openModal={isSubscriptionModalOpen} toggleModal={handleToggleSubscriptionModal}>
				{{
					header: <h6 className="title ecre-text-gray-900 ecre-text-base ecre-font-semibold">{translate('subscription_plugin_not_active')}</h6>,
					body: <p className="ecre-text-gray-900 ecre-text-sm ecre-font-normal">
						{translate('this_feature_requires_wooCommerce_subscription')}&nbsp;&nbsp;{translate('please')}&nbsp;
						<a href='https://woocommerce.com/products/woocommerce-subscriptions/' target='_blank' rel='noreferrer'>{translate('get_the_plugin_from_this_link')}</a>
						&nbsp;{translate('and_activate_use_subscription_coupons')}
					</p>,
					footer: (
						<div className="btn-box ecre-justify-end ecre-items-center ecre-gap-2 ecre-flex">
							<button
								onClick={handleToggleSubscriptionModal}
								className="ecre-text-gray-900 ecre-cursor-pointer ecre-text-sm ecre-font-semibold ecre-px-4 ecre-py-2.5 ecre-transition ecre-bg-slate-100 ecre-rounded-lg ecre-border ecre-border-solid ecre-border-slate-100 hover:ecre-border-red-500 hover:ecre-bg-white hover:ecre-text-red-500"
							>
								{translate('cancel')}
							</button>
						</div>
					)
				}}
			</Modal>
		</>
	);
}

export default RewardTab;