import { useCallback, useEffect, useState } from 'react';
import { fetchSettings, saveSettings, sendTestEmail } from '../api';
import { useSave } from '../hooks/useSave';
import { showToast } from '../toast';
import type { Settings } from '../types';
import { EmailDesignPreview } from './AdminPreviews';
import { ColorControl } from './ColorControl';
import { SaveButton } from './SaveButton';
import { __ } from "@wordpress/i18n";
const EMAIL_DEFAULTS = {
  restock_email_subject: __('{product_name} is back in stock!', 'stockbeacon-product-waitlists-for-woocommerce'),
  restock_email_heading: __("Great news — it's back!", 'stockbeacon-product-waitlists-for-woocommerce'),
  restock_email_body: __('The product you were waiting for is now available. Grab it before it sells out again!', 'stockbeacon-product-waitlists-for-woocommerce'),
  restock_email_cta_text: __('Shop Now', 'stockbeacon-product-waitlists-for-woocommerce')
};
export function FreeEmailEditor() {
  const [loaded, setLoaded] = useState(false);
  const [subject, setSubject] = useState(EMAIL_DEFAULTS.restock_email_subject);
  const [heading, setHeading] = useState(EMAIL_DEFAULTS.restock_email_heading);
  const [body, setBody] = useState(EMAIL_DEFAULTS.restock_email_body);
  const [ctaText, setCtaText] = useState(EMAIL_DEFAULTS.restock_email_cta_text);
  const [emailAccentColor, setEmailAccentColor] = useState('#2563eb');
  const [emailBoxShadowEnabled, setEmailBoxShadowEnabled] = useState(false);
  const [emailHeadingSize, setEmailHeadingSize] = useState(30);
  const [emailBodySize, setEmailBodySize] = useState(16);
  const [emailButtonSize, setEmailButtonSize] = useState(15);
  const [emailFooterSize, setEmailFooterSize] = useState(12);
  const [testEmailTo, setTestEmailTo] = useState('');
  const [testEmailSending, setTestEmailSending] = useState(false);
  const applySettings = useCallback((s: Settings) => {
    setSubject(String(s.restock_email_subject ?? EMAIL_DEFAULTS.restock_email_subject));
    setHeading(String(s.restock_email_heading ?? EMAIL_DEFAULTS.restock_email_heading));
    setBody(String(s.restock_email_body ?? EMAIL_DEFAULTS.restock_email_body));
    setCtaText(String(s.restock_email_cta_text ?? EMAIL_DEFAULTS.restock_email_cta_text));
    setEmailAccentColor(String(s.email_accent_color || s.form_accent_color || '#2563eb'));
    setEmailBoxShadowEnabled(s.email_box_shadow_enabled === true);
    setEmailHeadingSize(Number(s.email_heading_font_size || 30));
    setEmailBodySize(Number(s.email_body_font_size || 16));
    setEmailButtonSize(Number(s.email_button_font_size || 15));
    setEmailFooterSize(Number(s.email_footer_font_size || 12));
  }, []);
  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 () => {
    await saveSettings({
      restock_email_subject: subject.trim(),
      restock_email_heading: heading.trim(),
      restock_email_body: body.trim(),
      restock_email_cta_text: ctaText.trim(),
      email_accent_color: emailAccentColor,
      email_box_shadow_enabled: emailBoxShadowEnabled,
      email_heading_font_size: emailHeadingSize,
      email_body_font_size: emailBodySize,
      email_button_font_size: emailButtonSize,
      email_footer_font_size: emailFooterSize
    });
  }, __('Email content saved.', 'stockbeacon-product-waitlists-for-woocommerce'), __('Could not save email content.', 'stockbeacon-product-waitlists-for-woocommerce'));
  const handleSendTestEmail = async () => {
    const to = testEmailTo.trim();
    if (!to || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(to)) {
      showToast(__('Enter a valid email address.', 'stockbeacon-product-waitlists-for-woocommerce'), 'error');
      return;
    }
    setTestEmailSending(true);
    try {
      await sendTestEmail(to, {
        email_type: 'restock',
        restock_email_subject: subject,
        restock_email_heading: heading,
        restock_email_body: body,
        restock_email_cta_text: ctaText,
        email_accent_color: emailAccentColor,
        email_box_shadow_enabled: emailBoxShadowEnabled,
        email_heading_font_size: emailHeadingSize,
        email_body_font_size: emailBodySize,
        email_button_font_size: emailButtonSize,
        email_footer_font_size: emailFooterSize
      });
      showToast(__('Test email sent.', 'stockbeacon-product-waitlists-for-woocommerce'));
    } catch (err: unknown) {
      showToast(err instanceof Error ? err.message : __('Could not send test email.', 'stockbeacon-product-waitlists-for-woocommerce'), 'error');
    } finally {
      setTestEmailSending(false);
    }
  };
  const previewSettings: Settings = {
    restock_email_subject: subject,
    restock_email_heading: heading,
    restock_email_body: body,
    restock_email_cta_text: ctaText,
    email_accent_color: emailAccentColor,
    email_background_color: '#f1f5f9',
    email_card_background_color: '',
    email_box_shadow_enabled: emailBoxShadowEnabled,
    email_heading_font_size: emailHeadingSize,
    email_body_font_size: emailBodySize,
    email_button_font_size: emailButtonSize,
    email_footer_font_size: emailFooterSize
  };
  return <div className="stockbeacon-free-editor stockbeacon-settings-card--wide">
			<div className="stockbeacon-free-editor__inner">
				<div className="stockbeacon-free-editor__settings">
					<section className="stockbeacon-settings-card stockbeacon-settings-card--wide" aria-labelledby="stockbeacon-free-email-h">
						<div className="stockbeacon-settings-card__head">
							<h3 id="stockbeacon-free-email-h">{__("Restock email content", "stockbeacon-product-waitlists-for-woocommerce")}</h3>
							<p>{__("The email customers receive when their waitlisted product comes back in stock. Use", "stockbeacon-product-waitlists-for-woocommerce") + " "}<code>{'{product_name}'}</code>{" " + __("and", "stockbeacon-product-waitlists-for-woocommerce") + " "}<code>{'{product_url}'}</code>{" " + __("as placeholders.", "stockbeacon-product-waitlists-for-woocommerce")}</p>
						</div>
						<div className="stockbeacon-settings-card__body">
							<div className="stockbeacon-settings-field">
								<label className="stockbeacon-settings-label" htmlFor="stockbeacon-fe-subject">{__("Subject line", "stockbeacon-product-waitlists-for-woocommerce")}</label>
								<input type="text" className="regular-text" id="stockbeacon-fe-subject" autoComplete="off" disabled={!loaded} value={subject} onChange={e => setSubject(e.target.value)} />
							</div>
							<div className="stockbeacon-settings-field">
								<label className="stockbeacon-settings-label" htmlFor="stockbeacon-fe-heading">{__("Email heading", "stockbeacon-product-waitlists-for-woocommerce")}</label>
								<input type="text" className="regular-text" id="stockbeacon-fe-heading" autoComplete="off" disabled={!loaded} value={heading} onChange={e => setHeading(e.target.value)} />
							</div>
							<div className="stockbeacon-settings-field">
								<label className="stockbeacon-settings-label" htmlFor="stockbeacon-fe-body">{__("Body text", "stockbeacon-product-waitlists-for-woocommerce")}</label>
								<textarea className="large-text" rows={3} id="stockbeacon-fe-body" disabled={!loaded} value={body} onChange={e => setBody(e.target.value)} />
							</div>
							<div className="stockbeacon-settings-field">
								<label className="stockbeacon-settings-label" htmlFor="stockbeacon-fe-cta">{__("CTA button text", "stockbeacon-product-waitlists-for-woocommerce")}</label>
								<input type="text" className="regular-text" id="stockbeacon-fe-cta" autoComplete="off" disabled={!loaded} value={ctaText} onChange={e => setCtaText(e.target.value)} />
							</div>
							<div className="stockbeacon-settings-field">
								<label className="stockbeacon-settings-label" htmlFor="stockbeacon-fe-accent">{__("Accent color", "stockbeacon-product-waitlists-for-woocommerce")}</label>
								<ColorControl inputId="stockbeacon-fe-accent" label={__("Email accent color", "stockbeacon-product-waitlists-for-woocommerce")} disabled={!loaded} value={emailAccentColor} onChange={setEmailAccentColor} />
							</div>
							<div className="stockbeacon-settings-field">
								<label className="stockbeacon-settings-check" htmlFor="stockbeacon-fe-shadow">
									<input type="checkbox" id="stockbeacon-fe-shadow" disabled={!loaded} checked={emailBoxShadowEnabled} onChange={e => setEmailBoxShadowEnabled(e.target.checked)} />
									<span>{__("Show box shadow on the email card.", "stockbeacon-product-waitlists-for-woocommerce")}</span>
								</label>
							</div>
							<div className="stockbeacon-settings-sub stockbeacon-settings-sub--compact">
								<h4 className="stockbeacon-settings-sub__title">{__("Text sizing", "stockbeacon-product-waitlists-for-woocommerce")}</h4>
								<div className="stockbeacon-settings-field">
									<label className="stockbeacon-settings-label" htmlFor="stockbeacon-fe-heading-size">{__("Heading size", "stockbeacon-product-waitlists-for-woocommerce")}</label>
									<div className="stockbeacon-slider-row">
										<input id="stockbeacon-fe-heading-size" type="range" min={18} max={48} disabled={!loaded} value={emailHeadingSize} onChange={e => setEmailHeadingSize(Number(e.target.value))} />
										<input type="number" min={18} max={48} disabled={!loaded} value={emailHeadingSize} onChange={e => setEmailHeadingSize(Number(e.target.value))} aria-label={__("Email heading font size", "stockbeacon-product-waitlists-for-woocommerce")} />
									</div>
								</div>
								<div className="stockbeacon-settings-field">
									<label className="stockbeacon-settings-label" htmlFor="stockbeacon-fe-body-size">{__("Body size", "stockbeacon-product-waitlists-for-woocommerce")}</label>
									<div className="stockbeacon-slider-row">
										<input id="stockbeacon-fe-body-size" type="range" min={12} max={24} disabled={!loaded} value={emailBodySize} onChange={e => setEmailBodySize(Number(e.target.value))} />
										<input type="number" min={12} max={24} disabled={!loaded} value={emailBodySize} onChange={e => setEmailBodySize(Number(e.target.value))} aria-label={__("Email body font size", "stockbeacon-product-waitlists-for-woocommerce")} />
									</div>
								</div>
								<div className="stockbeacon-settings-field">
									<label className="stockbeacon-settings-label" htmlFor="stockbeacon-fe-button-size">{__("Button size", "stockbeacon-product-waitlists-for-woocommerce")}</label>
									<div className="stockbeacon-slider-row">
										<input id="stockbeacon-fe-button-size" type="range" min={12} max={22} disabled={!loaded} value={emailButtonSize} onChange={e => setEmailButtonSize(Number(e.target.value))} />
										<input type="number" min={12} max={22} disabled={!loaded} value={emailButtonSize} onChange={e => setEmailButtonSize(Number(e.target.value))} aria-label={__("Email button font size", "stockbeacon-product-waitlists-for-woocommerce")} />
									</div>
								</div>
								<div className="stockbeacon-settings-field">
									<label className="stockbeacon-settings-label" htmlFor="stockbeacon-fe-footer-size">{__("Footer size", "stockbeacon-product-waitlists-for-woocommerce")}</label>
									<div className="stockbeacon-slider-row">
										<input id="stockbeacon-fe-footer-size" type="range" min={10} max={16} disabled={!loaded} value={emailFooterSize} onChange={e => setEmailFooterSize(Number(e.target.value))} />
										<input type="number" min={10} max={16} disabled={!loaded} value={emailFooterSize} onChange={e => setEmailFooterSize(Number(e.target.value))} aria-label={__("Email footer font size", "stockbeacon-product-waitlists-for-woocommerce")} />
									</div>
								</div>
							</div>
							<div className="stockbeacon-settings-sub stockbeacon-settings-sub--compact">
								<h4 className="stockbeacon-settings-sub__title">{__("Send test email", "stockbeacon-product-waitlists-for-woocommerce")}</h4>
								<div className="stockbeacon-inline-action-row">
									<input type="email" className="regular-text" placeholder={__("you@example.com", "stockbeacon-product-waitlists-for-woocommerce")} autoComplete="email" value={testEmailTo} onChange={e => setTestEmailTo(e.target.value)} />
									<button type="button" className="button" disabled={testEmailSending} onClick={handleSendTestEmail}>
										{testEmailSending ? __('Sending…', 'stockbeacon-product-waitlists-for-woocommerce') : __('Send test', 'stockbeacon-product-waitlists-for-woocommerce')}
									</button>
								</div>
							</div>
						</div>
						<div className="stockbeacon-settings-card__foot">
							<SaveButton state={state} onClick={execute}>{__("Save email content", "stockbeacon-product-waitlists-for-woocommerce")}</SaveButton>
						</div>
					</section>
				</div>
				<div className="stockbeacon-free-editor__preview">
					<div className="stockbeacon-free-preview">
						<div className="stockbeacon-free-preview__label">{__("Live preview", "stockbeacon-product-waitlists-for-woocommerce")}</div>
						<div className="stockbeacon-free-preview__canvas stockbeacon-free-preview__canvas--email">
							<EmailDesignPreview settings={previewSettings} />
						</div>
					</div>
				</div>
			</div>
		</div>;
}
