import { useEffect, useState } from 'react';
import { fetchWaitlistRowsForProduct } from '../api';
import type { WaitlistSubscriptionRow } from '../types';
import { maskEmail } from '../utils';


export function ProductWaitlistPanel() {
	const cfg = window.stockbeaconProduct;
	if (!cfg || cfg.context !== 'product') {
		return null;
	}

	const { i18n, productId, dashboardUrl } = cfg;
	const [rows, setRows] = useState<WaitlistSubscriptionRow[] | null>(null);
	const [error, setError] = useState<string | null>(null);
	const [loading, setLoading] = useState(false);

	useEffect(() => {
		if (productId <= 0) {
			setRows([]);
			return;
		}
		let cancelled = false;
		setLoading(true);
		setError(null);
		fetchWaitlistRowsForProduct(productId)
			.then((r) => {
				if (!cancelled) {
					setRows(Array.isArray(r) ? r.slice(0, 10) : []);
				}
			})
			.catch(() => {
				if (!cancelled) {
					setError(i18n.loadError);
				}
			})
			.finally(() => {
				if (!cancelled) {
					setLoading(false);
				}
			});
		return () => {
			cancelled = true;
		};
	}, [productId, i18n.loadError]);

	return (
		<div className="space-y-6 px-0 py-1 text-[13px] leading-relaxed text-[#1d2327]">
			

			<div className="space-y-2">
				<p className="m-0 font-semibold text-[#1d2327]">{i18n.recentSubscribers}</p>
				{productId <= 0 ? (
					<p className="m-0 text-[12px] text-[#646970]">{i18n.noProductYet}</p>
				) : loading ? (
					<p className="m-0 text-[12px] text-[#646970]">{i18n.loading}</p>
				) : error ? (
					<p className="m-0 text-[12px] text-[#b32d2e]" role="alert">
						{error}
					</p>
				) : rows && rows.length === 0 ? (
					<p className="m-0 text-[12px] text-[#646970]">{i18n.noneYet}</p>
				) : (
					<ul className="m-0 max-h-56 list-none space-y-1.5 overflow-y-auto p-0">
						{(rows ?? []).map((row, idx) => {
							const emailRaw = String(row.email ?? '');
							const masked = maskEmail(emailRaw);
							const key = row.id != null ? String(row.id) : `row-${idx}`;
							return (
								<li key={key} className="text-[13px] text-[#1d2327]">
									<span title={emailRaw}>{masked}</span>
									{row.status ? (
										<span className="text-[#646970]"> — {String(row.status)}</span>
									) : null}
								</li>
							);
						})}
					</ul>
				)}
				<p className="m-0 pt-1">
					<a
						href={dashboardUrl}
						className="inline-flex h-8 items-center rounded border border-[#2271b1] bg-[#2271b1] px-3 text-[13px] font-medium text-white no-underline shadow-sm hover:bg-[#135e96] hover:text-white focus:shadow-[0_0_0_1px_#fff,0_0_0_3px_#2271b1]"
					>
						{i18n.openDashboard}
					</a>
				</p>
			</div>
		</div>
	);
}
