import { useCallback, useEffect, useState } from 'react';
import { fetchSettings, saveSettings } from '../../api';
import { useSave } from '../../hooks/useSave';
import type { AdminData, Settings } from '../../types';
import { ContextualUpsell } from '../ContextualUpsell';
import { SaveButton } from '../SaveButton';
import { __ } from "@wordpress/i18n";

export function EmailSettingsPanel() {
  const adminData: Partial<AdminData> = window.stockbeaconAdmin ?? {};
  const isPremium = !!adminData.isPremium;
  const defaultFromName = String(adminData.siteTitle || '').trim();
  const defaultReplyToEmail = String(adminData.adminEmail || '').trim();
  const [loaded, setLoaded] = useState(false);
  const [fromName, setFromName] = useState(defaultFromName);
  const [replyTo, setReplyTo] = useState(defaultReplyToEmail);
  const [throttle, setThrottle] = useState(5);
  
  const applySettings = useCallback((s: Settings) => {
    setFromName(String(s.email_from_name ?? '').trim() || defaultFromName);
    setReplyTo(String(s.email_reply_to ?? '').trim() || defaultReplyToEmail);
    setThrottle(Math.max(1, Math.min(120, Number(s.throttle_per_minute ?? 5))));
    
  }, [defaultFromName, defaultReplyToEmail]);
  useEffect(() => {
    let alive = true;
    fetchSettings().then(s => {
      if (alive) applySettings(s);
    }).catch(() => undefined).finally(() => {
      if (alive) setLoaded(true);
    });
    return () => {
      alive = false;
    };
  }, [applySettings]);
  const {
    state,
    execute
  } = useSave(async () => {
    const payload: Partial<Settings> = {
      email_from_name: fromName.trim(),
      email_reply_to: replyTo.trim(),
      throttle_per_minute: throttle
    };
    
    await saveSettings(payload);
  }, __('Email settings saved.', 'stockbeacon-product-waitlists-for-woocommerce'), __('Could not save email settings.', 'stockbeacon-product-waitlists-for-woocommerce'));
  return <section className="stockbeacon-settings-card stockbeacon-settings-card--wide" aria-labelledby="stockbeacon-email-settings-title">
			<div className="stockbeacon-settings-card__head">
				<h3 id="stockbeacon-email-settings-title">{__("Email, notifications & delivery", "stockbeacon-product-waitlists-for-woocommerce")}</h3>
				<p>{__("Configure sender identity, signup limits, notification timing, reminders, and SMTP delivery.", "stockbeacon-product-waitlists-for-woocommerce")}</p>
			</div>
			<div className="stockbeacon-settings-card__body">
				<div className="stockbeacon-settings-panel-grid">
					<div className="stockbeacon-settings-sub stockbeacon-settings-sub--surface">
						<h4 className="stockbeacon-settings-sub__title">{__("Basics", "stockbeacon-product-waitlists-for-woocommerce")}</h4>
						<div className="stockbeacon-settings-two">
							<div className="stockbeacon-settings-field">
								<label className="stockbeacon-settings-label" htmlFor="stockbeacon-email-from-name">{__("From name", "stockbeacon-product-waitlists-for-woocommerce")}</label>
								<input type="text" className="regular-text" id="stockbeacon-email-from-name" disabled={!loaded} placeholder={__("My Shop", "stockbeacon-product-waitlists-for-woocommerce")} autoComplete="organization" value={fromName} onChange={e => setFromName(e.target.value)} />
							</div>
							<div className="stockbeacon-settings-field">
								<label className="stockbeacon-settings-label" htmlFor="stockbeacon-email-reply-to">{__("Reply-To", "stockbeacon-product-waitlists-for-woocommerce")}</label>
								<input type="email" className="regular-text" id="stockbeacon-email-reply-to" disabled={!loaded} placeholder={__("support@example.com", "stockbeacon-product-waitlists-for-woocommerce")} autoComplete="email" value={replyTo} onChange={e => setReplyTo(e.target.value)} />
							</div>
						</div>
						<div className="stockbeacon-settings-two">
							<div className="stockbeacon-settings-field">
								<label className="stockbeacon-settings-label" htmlFor="stockbeacon-throttle-per-minute">{__("Max signups per IP per minute", "stockbeacon-product-waitlists-for-woocommerce")}</label>
								<input type="number" className="small-text" id="stockbeacon-throttle-per-minute" disabled={!loaded} min={1} max={120} step={1} value={throttle} onChange={e => setThrottle(Number(e.target.value))} />
								<p className="stockbeacon-settings-help">{__("Helps reduce automated or abusive signups.", "stockbeacon-product-waitlists-for-woocommerce")}</p>
							</div>
							
						</div>
					</div>

					
					{!isPremium && <div className="stockbeacon-settings-sub stockbeacon-settings-sub--surface">
							<h4 className="stockbeacon-settings-sub__title">{__("Pro delivery controls", "stockbeacon-product-waitlists-for-woocommerce")}</h4>
							<ContextualUpsell title={__("Advanced restock email delivery", "stockbeacon-product-waitlists-for-woocommerce")}>{__("Unlock confirmation emails, low-stock waitlists, delayed sends, quiet-hour delivery, reminders, admin alerts, cleanup controls, and custom SMTP settings for more reliable notifications.", "stockbeacon-product-waitlists-for-woocommerce")}</ContextualUpsell>
						</div>}
				</div>
			</div>
			<div className="stockbeacon-settings-card__foot">
				<SaveButton state={state} onClick={execute}>{__("Save email settings", "stockbeacon-product-waitlists-for-woocommerce")}</SaveButton>
			</div>
		</section>;
}
