import { createSignal, createMemo, onMount, Show, For } from 'solid-js';
import { Text, Button } from '@components';
import { useLicense, useModal } from '@util/context';
import * as packedge from '../../shared/packedge.js';

export default function License() {
	const { license, isLocked, maskedKey, state: licenseState, setState: setLicenseState, activate: activateLicense, deactivate: deactivateLicense, fetchPlans: fetchLicensePlans } = useLicense();
	const { fire, toast } = useModal();

	const [plans, setPlans] = createSignal([]);
	const [justActivated, setJustActivated] = createSignal(false);
	const [loadingPlans, setLoadingPlans] = createSignal(false);
	const [planTier, setPlanTier] = createSignal('personal'); // personal or agency

	const siteUrl = window.ajaxpress_admin_vars?.site?.url || '';
	const returnUrl = `${siteUrl}/wp-admin/options-general.php?page=ajaxpress#/license`;

	// Get yearly and lifetime plans for current tier
	const yearlyPlan = createMemo(() => {
		const slug = planTier() === 'personal' ? 'ap-single-yearly' : 'ap-agency-yearly';
		return plans().find(p => p.slug === slug);
	});

	const lifetimePlan = createMemo(() => {
		const slug = planTier() === 'personal' ? 'ap-single-lifetime' : 'ap-agency-lifetime';
		return plans().find(p => p.slug === slug);
	});

	const currentTierFeatures = createMemo(() => {
		const isPersonal = planTier() === 'personal';
		return [
			{ label: isPersonal ? '1 site' : '100 sites', yearly: true, lifetime: true },
			{ label: 'All features unlocked', yearly: true, lifetime: true },
			{ label: 'Lifetime updates', yearly: true, lifetime: true },
			{ label: 'Premium support', yearly: '1 year', lifetime: '5 years' },
		];
	});

	const originalPrice = (plan) => {
		const prices = {
			'ap-single-yearly': 196,
			'ap-single-lifetime': 990,
			'ap-agency-yearly': 1996,
			'ap-agency-lifetime': 6990,
		};
		return prices[plan.slug] || plan.price;
	};

	const focus = () => {
		setTimeout(() => {
			const inputkey = document.querySelector('input.inputkey');
			if (inputkey) inputkey.focus();
		}, 50);
	};

	const fetchPlans = async () => {
		if (!navigator.onLine) {
			return;
		}

		setLoadingPlans(true);
		const result = await fetchLicensePlans();
		if (result.success && result.plans) {
			setPlans(result.plans);
		}
		setLoadingPlans(false);
	};

	const activate = async () => {
		let result = await activateLicense();

		if (result.success) {
			setJustActivated(true);
			return;
		}

		return fire({
			cancel: false,
			title: 'License Error!',
			content: result.message || 'The license key you entered is invalid, please try again with valid license. Please contact ArrayStory for further details.'
		}).then(focus);
	};

	const deactivate = async () => {
		const confirmed = await fire({
			title: 'Are you sure',
			content: 'Are you really want to deactivate the license?',
			ok: 'Yes, deactivate',
			okVariant: 'danger',
		});

		if (confirmed) {
			let result = await deactivateLicense();

			if (result.success) {
				toast('License deactivated!');
				// Fetch pricing plans after deactivation
				fetchPlans();
				// Focus input field
				focus();
			}
		}
	};

	const formatDate = (dateStr) => {
		if (!dateStr || dateStr === 'never') return 'Never';
		const date = new Date(dateStr);
		return date.toLocaleDateString('en-US', {
			year: 'numeric',
			month: 'long',
			day: 'numeric'
		});
	};

	onMount(async () => {
		focus();

		// Post-purchase return from PackEdge checkout: auto-activate the key, or
		// show a notice if the license is still being provisioned.
		const purchase = packedge.consumeActivationFromUrl();

		if (purchase && purchase.key && isLocked()) {
			setLicenseState('key', purchase.key);
			setLicenseState('error', '');
			setTimeout(async () => {
				await activate();
			}, 50);
		} else if (purchase && purchase.pending) {
			toast('Payment received! Your license is being provisioned and will activate shortly - it has also been emailed to you.');
		}

		if (isLocked()) {
			fetchPlans();
		}
	});

	return (
		<section class="ap-space-y-8 ap-max-w-5xl ap-mx-auto">
			{/* Header */}
			{/* <div class="ap-space-y-2 ap-pb-4">
				<h1 class="ap-text-2xl ap-font-semibold ap-text-slate-800">License</h1>
				<p class="ap-text-slate-600">Manage your AjaxPress license and unlock premium features</p>
			</div> */}

			{/* License Card */}
			<div class="ap-max-w-2xl ap-mx-auto">
				<div class="ap-bg-white ap-rounded-xl ap-ring-1 ap-ring-slate-200 ap-p-4">
					<form
						class="ap-flex ap-items-center ap-gap-3"
						onSubmit={(e) => {
							e.preventDefault();
							isLocked() ? activate() : deactivate();
						}}
					>
						<div class="ap-flex ap-items-center ap-gap-2 ap-flex-shrink-0">
							<div
								class="ap-w-2.5 ap-h-2.5 ap-rounded-full"
								classList={{
									'ap-bg-red-500': isLocked(),
									'ap-bg-green-500': !isLocked()
								}}
							/>
							<span class="ap-text-sm ap-font-medium ap-text-slate-600">
								{isLocked() ? 'Inactive' : 'Active'}
							</span>
						</div>
						<Show
							when={isLocked()}
							fallback={
								<Text
									class="ap-flex-1"
									value={maskedKey()}
									disabled
									size="sm"
								/>
							}
						>
							<Text
								autocomplete="license-key"
								type="text"
								class="ap-flex-1 inputkey"
								placeholder="Enter your license key"
								value={licenseState.key}
								onInput={(e) => setLicenseState('key', e.target.value)}
								disabled={licenseState.isLoading}
								size="sm"
							/>
						</Show>
						<Button
							type="submit"
							disabled={isLocked() && !licenseState.key?.trim()}
							loading={licenseState.isLoading}
							variant={isLocked() ? 'primary' : 'danger'}
							class="ap-flex-shrink-0"
							size="sm"
						>
							{isLocked() ? 'Activate' : 'Deactivate'}
						</Button>
					</form>
				</div>
			</div>

			{/* Welcome Notice */}
			<Show when={justActivated() && !isLocked()}>
				<div class="ap-max-w-2xl ap-mx-auto">
					<div class="ap-bg-white ap-ring-1 ap-ring-slate-200 ap-rounded-xl ap-p-5 ap-relative">
						<button
							onClick={() => setJustActivated(false)}
							class="ap-absolute ap-top-3 ap-right-3 ap-text-slate-400 hover:ap-text-slate-600 ap-transition"
						>
							<svg class="ap-w-4 ap-h-4" fill="currentColor" viewBox="0 0 20 20">
								<path fill-rule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd" />
							</svg>
						</button>
						<div class="ap-flex ap-flex-col ap-items-center ap-text-center ap-py-2">
							<div class="ap-w-12 ap-h-12 ap-bg-green-100 ap-rounded-full ap-flex ap-items-center ap-justify-center ap-mb-4">
								<svg class="ap-w-6 ap-h-6 ap-text-green-600" fill="currentColor" viewBox="0 0 20 20">
									<path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
								</svg>
							</div>
							<h4 class="ap-font-semibold ap-text-lg ap-text-slate-800">Welcome to AjaxPress Pro!</h4>
							<p class="ap-text-sm ap-text-slate-600 ap-mt-2 ap-max-w-sm">Your license has been activated successfully. All premium features are now unlocked.</p>
							<a href={atob('aHR0cHM6Ly9hcnJheXN0b3J5LmNvbS9zdXBwb3J0')} target="_blank" class="ap-text-sm ap-text-indigo-600 hover:ap-text-indigo-700 ap-mt-3 ap-font-medium">Get priority support →</a>
						</div>
					</div>
				</div>
			</Show>

			{/* Error Messages */}
			<Show when={licenseState.error}>
				<div class="ap-max-w-2xl ap-mx-auto">
					<div class="ap-bg-red-50 ap-ring-1 ap-ring-red-200 ap-rounded-lg ap-text-red-600 ap-text-sm ap-px-4 ap-py-3 ap-flex ap-items-center ap-justify-between ap-gap-3">
						<div class="ap-flex ap-items-center ap-gap-2">
							<svg class="ap-w-4 ap-h-4 ap-flex-shrink-0" fill="currentColor" viewBox="0 0 20 20">
								<path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clip-rule="evenodd" />
							</svg>
							<span>
								<Show when={licenseState.error === 'offline'}>
									Please check your internet connection.
								</Show>
								<Show when={licenseState.error === 'inactive'}>
									Your license is invalid or has been deactivated.
								</Show>
							</span>
						</div>
						<button
							onClick={() => setLicenseState('error', '')}
							class="ap-text-red-400 hover:ap-text-red-600 ap-transition"
						>
							<svg class="ap-w-4 ap-h-4" fill="currentColor" viewBox="0 0 20 20">
								<path fill-rule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd" />
							</svg>
						</button>
					</div>
				</div>
			</Show>

			{/* Pricing Plans */}
			<Show when={isLocked()}>
				<div data-tour="pricing" class="ap-max-w-2xl ap-mx-auto ap-mt-8">
					<Show when={loadingPlans()}>
						<div class="ap-flex ap-items-center ap-justify-center ap-py-12">
							<svg class="ap-animate-spin ap-h-6 ap-w-6 ap-text-indigo-600" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
								<circle class="ap-opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
								<path class="ap-opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
							</svg>
						</div>
					</Show>

					<Show when={!loadingPlans() && plans().length > 0}>
						<div class="ap-space-y-6">
							{/* Header with Toggle */}
							<div class="ap-flex ap-items-center ap-justify-between">
								<h3 class="ap-font-semibold ap-text-lg ap-text-slate-800">Choose Your Plan</h3>
								<div class="ap-inline-flex ap-gap-1 ap-p-1 ap-bg-slate-100 ap-rounded-lg">
									<button
										onClick={() => setPlanTier('personal')}
										class="ap-px-4 ap-py-1.5 ap-rounded-md ap-text-sm ap-font-medium ap-transition-all ap-duration-200"
										classList={{
											'ap-bg-white ap-text-indigo-600 ap-shadow-sm ap-ring-1 ap-ring-slate-200': planTier() === 'personal',
											'ap-text-slate-500 hover:ap-text-slate-700': planTier() !== 'personal'
										}}
									>
										Personal
									</button>
									<button
										onClick={() => setPlanTier('agency')}
										class="ap-px-4 ap-py-1.5 ap-rounded-md ap-text-sm ap-font-medium ap-transition-all ap-duration-200"
										classList={{
											'ap-bg-white ap-text-indigo-600 ap-shadow-sm ap-ring-1 ap-ring-slate-200': planTier() === 'agency',
											'ap-text-slate-500 hover:ap-text-slate-700': planTier() !== 'agency'
										}}
									>
										Agency
									</button>
								</div>
							</div>

							{/* Pricing Table */}
							<div class="ap-bg-white ap-rounded-xl ap-ring-1 ap-ring-slate-200 ap-overflow-hidden">
								{/* Table Header with Prices */}
								<div class="ap-grid ap-grid-cols-[1fr,1fr,1fr] ap-bg-slate-50 ap-border-b ap-border-slate-200">
									<div class="ap-p-4 ap-flex ap-items-center ap-justify-center">
										<span class="ap-text-xs ap-text-slate-400 ap-uppercase ap-tracking-wide">What's included</span>
									</div>
									<div class="ap-p-4 ap-text-center ap-border-l ap-border-slate-200">
										<div class="ap-text-xs ap-text-slate-500 ap-uppercase ap-tracking-wide ap-mb-1">Yearly</div>
										<Show when={yearlyPlan()}>
											<span class="ap-text-sm ap-text-slate-400 ap-line-through">${originalPrice(yearlyPlan())}</span>
											<div class="ap-text-2xl ap-font-bold ap-text-slate-800">${yearlyPlan().price}<span class="ap-text-sm ap-font-normal ap-text-slate-400">/yr</span></div>
										</Show>
									</div>
									<div class="ap-p-4 ap-text-center ap-border-l ap-border-slate-200 ap-bg-indigo-50">
										<div class="ap-text-xs ap-text-indigo-600 ap-uppercase ap-tracking-wide ap-mb-1">Lifetime</div>
										<Show when={lifetimePlan()}>
											<span class="ap-text-sm ap-text-slate-400 ap-line-through">${originalPrice(lifetimePlan())}</span>
											<div class="ap-text-2xl ap-font-bold ap-text-indigo-600">${lifetimePlan().price}</div>
										</Show>
									</div>
								</div>

								{/* Feature Rows */}
								<For each={currentTierFeatures()}>
									{(feature) => (
										<div class="ap-grid ap-grid-cols-[1fr,1fr,1fr] ap-border-b ap-border-slate-100 last:ap-border-b-0">
											<div class="ap-px-4 ap-py-3 ap-text-sm ap-text-slate-600">{feature.label}</div>
											<div class="ap-px-4 ap-py-3 ap-text-center ap-border-l ap-border-slate-100">
												<Show when={feature.yearly} fallback={<span class="ap-text-slate-300">-</span>}>
													<Show when={typeof feature.yearly === 'string'} fallback={
														<svg class="ap-w-5 ap-h-5 ap-text-green-500 ap-mx-auto" fill="currentColor" viewBox="0 0 20 20">
															<path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
														</svg>
													}>
														<span class="ap-text-sm ap-text-slate-600 ap-font-medium">{feature.yearly}</span>
													</Show>
												</Show>
											</div>
											<div class="ap-px-4 ap-py-3 ap-text-center ap-border-l ap-border-slate-100 ap-bg-indigo-50/30">
												<Show when={feature.lifetime} fallback={<span class="ap-text-slate-300">-</span>}>
													<Show when={typeof feature.lifetime === 'string'} fallback={
														<svg class="ap-w-5 ap-h-5 ap-text-indigo-600 ap-mx-auto" fill="currentColor" viewBox="0 0 20 20">
															<path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
														</svg>
													}>
														<span class="ap-text-sm ap-text-indigo-600 ap-font-medium">{feature.lifetime}</span>
													</Show>
												</Show>
											</div>
										</div>
									)}
								</For>

								{/* CTA Row */}
								<div class="ap-grid ap-grid-cols-[1fr,1fr,1fr] ap-border-t ap-border-slate-200 ap-bg-slate-50">
									<div class="ap-p-4 ap-flex ap-items-center ap-justify-center">
										<a href={atob('aHR0cHM6Ly9hcnJheXN0b3J5LmNvbS9zdXBwb3J0')} target="_blank" class="ap-text-xs ap-text-indigo-600 hover:ap-text-indigo-700 hover:ap-underline">Need custom quote?</a>
									</div>
									<div class="ap-p-4 ap-text-center ap-border-l ap-border-slate-200">
										<Show when={yearlyPlan()}>
											<div class="ap-mb-2">
												<span class="ap-bg-orange-500 ap-text-white ap-font-semibold ap-px-1.5 ap-py-0.5 ap-rounded ap-text-[10px]">75% OFF</span>
											</div>
											<Button
												a
												href={yearlyPlan().checkout_link + '&return_url=' + encodeURIComponent(returnUrl)}
												variant="secondary"
												size="sm"
												class="ap-w-full"
											>
												Get Yearly
											</Button>
										</Show>
									</div>
									<div class="ap-p-4 ap-text-center ap-border-l ap-border-slate-200 ap-bg-indigo-50">
										<Show when={lifetimePlan()}>
											<div class="ap-mb-2">
												<span class="ap-bg-red-500 ap-text-white ap-font-semibold ap-px-1.5 ap-py-0.5 ap-rounded ap-text-[10px]">90% OFF</span>
											</div>
											<Button
												a
												href={lifetimePlan().checkout_link + '&return_url=' + encodeURIComponent(returnUrl)}
												size="sm"
												class="ap-w-full ap-whitespace-nowrap"
											>
												Get Lifetime
											</Button>
										</Show>
									</div>
								</div>
							</div>

							{/* Trust Signals */}
							<div class="ap-flex ap-flex-wrap ap-items-center ap-justify-center ap-gap-x-4 ap-gap-y-2 ap-text-xs ap-text-slate-500">
								<span class="ap-flex ap-items-center ap-gap-1">
									<svg class="ap-w-3.5 ap-h-3.5 ap-text-green-500" fill="currentColor" viewBox="0 0 20 20">
										<path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
									</svg>
									14 days money back
								</span>
								<span class="ap-flex ap-items-center ap-gap-1">
									<svg class="ap-w-3.5 ap-h-3.5 ap-text-green-500" fill="currentColor" viewBox="0 0 20 20">
										<path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
									</svg>
									Auto-activation, no hassle
								</span>
								<span class="ap-flex ap-items-center ap-gap-1">
									<svg class="ap-w-3.5 ap-h-3.5 ap-text-green-500" fill="currentColor" viewBox="0 0 20 20">
										<path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
									</svg>
									Secure checkout
								</span>
							</div>
						</div>
					</Show>
				</div>
			</Show>

			{/* License Information */}
			<Show when={!isLocked()}>
				<div class="ap-max-w-2xl ap-mx-auto">
					<div class="ap-bg-white ap-rounded-xl ap-ring-1 ap-ring-slate-200 ap-overflow-hidden">
						<div class="ap-px-5 ap-py-4 ap-bg-slate-50 ap-border-b ap-border-slate-200">
							<h3 class="ap-font-semibold ap-text-slate-800">License Details</h3>
						</div>
						<div class="ap-divide-y ap-divide-slate-100">
							<div class="ap-px-5 ap-py-3 ap-flex ap-items-center ap-justify-between ap-text-sm">
								<span class="ap-text-slate-500">Plan</span>
								<span class="ap-font-medium ap-text-slate-800">{license.plan_name}</span>
							</div>
							<div class="ap-px-5 ap-py-3 ap-flex ap-items-center ap-justify-between ap-text-sm">
								<span class="ap-text-slate-500">Type</span>
								<span class="ap-font-medium ap-text-slate-800 ap-capitalize">{license.plan_type?.replace('_', ' ')}</span>
							</div>
							<div class="ap-px-5 ap-py-3 ap-flex ap-items-center ap-justify-between ap-text-sm">
								<span class="ap-text-slate-500">Activations</span>
								<span class="ap-font-medium ap-text-slate-800">{license.activations || 0} / {license.activation_limit || 'Unlimited'}</span>
							</div>
							<Show when={license.activations_remaining !== undefined}>
								<div class="ap-px-5 ap-py-3 ap-flex ap-items-center ap-justify-between ap-text-sm">
									<span class="ap-text-slate-500">Remaining</span>
									<span class="ap-font-medium ap-text-slate-800">{license.activations_remaining} {license.activations_remaining == 1 ? 'site' : 'sites'}</span>
								</div>
							</Show>
							<div class="ap-px-5 ap-py-3 ap-flex ap-items-center ap-justify-between ap-text-sm">
								<span class="ap-text-slate-500">Expires</span>
								<span class="ap-font-medium ap-text-slate-800">
									{license.expires_at && license.expires_at !== 'never' ? formatDate(license.expires_at) : 'Never'}
								</span>
							</div>
						</div>
						<div class="ap-px-5 ap-py-4 ap-bg-slate-50 ap-border-t ap-border-slate-200 ap-flex ap-items-center ap-justify-end ap-gap-3">
							<Button a href={atob('aHR0cHM6Ly9hcnJheXN0b3J5LmNvbS9hY2NvdW50')} target="_blank" variant="secondary" size="sm">
								Account Dashboard
							</Button>
							<Button a href={atob('aHR0cHM6Ly9hcnJheXN0b3J5LmNvbS9zdXBwb3J0')} target="_blank" size="sm">
								Priority Support
							</Button>
						</div>
					</div>
				</div>
			</Show>
		</section>
	);
}
