import { useCallback, useEffect, useState } from 'react';
import { fetchSettings, saveSettings } from '../api';
import { FORM_TEXT_DEFAULTS } from '../constants';
import { useSave } from '../hooks/useSave';
import { showToast } from '../toast';
import type { Settings } from '../types';
import { FormDesignPreview } from './AdminPreviews';
import { ColorControl } from './ColorControl';
import { ContextualUpsell } from './ContextualUpsell';
import { SaveButton } from './SaveButton';
import { __ } from "@wordpress/i18n";
export function FreeFormEditor() {
  const [loaded, setLoaded] = useState(false);
  const [formTitle, setFormTitle] = useState(FORM_TEXT_DEFAULTS.form_title);
  const [formDescription, setFormDescription] = useState(FORM_TEXT_DEFAULTS.form_description);
  const [formButtonText, setFormButtonText] = useState(FORM_TEXT_DEFAULTS.form_button_text);
  const [formPlaceholder, setFormPlaceholder] = useState(FORM_TEXT_DEFAULTS.form_placeholder);
  const [formSuccessMessage, setFormSuccessMessage] = useState(FORM_TEXT_DEFAULTS.form_success_message);
  const [showWaitlistCount, setShowWaitlistCount] = useState(true);
  const [themeMode, setThemeMode] = useState('light');
  const [accentColor, setAccentColor] = useState('#2563eb');
  const [buttonColor, setButtonColor] = useState('#2563eb');
  const [backgroundColor, setBackgroundColor] = useState('#ffffff');
  const [textColor, setTextColor] = useState('#0f172a');
  const [descriptionColor, setDescriptionColor] = useState('#64748b');
  const [inputBackgroundColor, setInputBackgroundColor] = useState('#ffffff');
  const [countTextColor, setCountTextColor] = useState('#334155');
  const [boxShadowEnabled, setBoxShadowEnabled] = useState(true);
  const [titleFontSize, setTitleFontSize] = useState(17);
  const [descriptionFontSize, setDescriptionFontSize] = useState(14);
  const [inputFontSize, setInputFontSize] = useState(16);
  const [buttonFontSize, setButtonFontSize] = useState(14);
  const [countFontSize, setCountFontSize] = useState(13);
  const [successFontSize, setSuccessFontSize] = useState(15);
  const applySettings = useCallback((s: Settings) => {
    setFormTitle(String(s.form_title ?? FORM_TEXT_DEFAULTS.form_title));
    setFormDescription(String(s.form_description ?? FORM_TEXT_DEFAULTS.form_description));
    setFormButtonText(String(s.form_button_text ?? FORM_TEXT_DEFAULTS.form_button_text));
    setFormPlaceholder(String(s.form_placeholder ?? FORM_TEXT_DEFAULTS.form_placeholder));
    setFormSuccessMessage(String(s.form_success_message ?? FORM_TEXT_DEFAULTS.form_success_message));
    setShowWaitlistCount(s.show_waitlist_count !== false);
    setThemeMode(s.form_theme_mode === 'dark' ? 'dark' : 'light');
    setAccentColor(String(s.form_accent_color || '#2563eb'));
    setButtonColor(String(s.form_button_color || s.form_accent_color || '#2563eb'));
    const isDarkForm = s.form_theme_mode === 'dark';
    setBackgroundColor(String(isDarkForm && (!s.form_background_color || s.form_background_color === '#ffffff') ? '#101827' : s.form_background_color || '#ffffff'));
    setTextColor(String(isDarkForm && (!s.form_text_color || s.form_text_color === '#0f172a') ? '#f8fafc' : s.form_text_color || '#0f172a'));
    setDescriptionColor(String(isDarkForm && (!s.form_description_color || s.form_description_color === '#64748b') ? '#cbd5e1' : s.form_description_color || '#64748b'));
    setInputBackgroundColor(String(isDarkForm && (!s.form_input_background_color || s.form_input_background_color === '#ffffff') ? '#0f172a' : s.form_input_background_color || '#ffffff'));
    setCountTextColor(String(isDarkForm && (!s.form_count_text_color || s.form_count_text_color === '#334155') ? '#14532d' : s.form_count_text_color || '#334155'));
    setBoxShadowEnabled(s.form_box_shadow_enabled !== false);
    setTitleFontSize(Number(s.form_title_font_size || 17));
    setDescriptionFontSize(Number(s.form_description_font_size || 14));
    setInputFontSize(Number(s.form_input_font_size || 16));
    setButtonFontSize(Number(s.form_button_font_size || 14));
    setCountFontSize(Number(s.form_count_font_size || 13));
    setSuccessFontSize(Number(s.form_success_font_size || 15));
  }, []);
  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({
      form_title: formTitle.trim(),
      form_description: formDescription.trim(),
      form_button_text: formButtonText.trim(),
      form_placeholder: formPlaceholder.trim(),
      form_success_message: formSuccessMessage.trim(),
      show_waitlist_count: showWaitlistCount,
      form_theme_mode: themeMode,
      form_accent_color: accentColor,
      form_button_color: buttonColor,
      form_background_color: backgroundColor,
      form_text_color: textColor,
      form_description_color: descriptionColor,
      form_input_background_color: inputBackgroundColor,
      form_count_text_color: countTextColor,
      form_box_shadow_enabled: boxShadowEnabled,
      form_title_font_size: titleFontSize,
      form_description_font_size: descriptionFontSize,
      form_input_font_size: inputFontSize,
      form_button_font_size: buttonFontSize,
      form_count_font_size: countFontSize,
      form_success_font_size: successFontSize
    });
  }, __('Waitlist form saved.', 'stockbeacon-product-waitlists-for-woocommerce'), __('Could not save waitlist form.', 'stockbeacon-product-waitlists-for-woocommerce'));
  const handleReset = async () => {
    if (!window.confirm(__('Reset waitlist copy and appearance to defaults? This saves immediately.', 'stockbeacon-product-waitlists-for-woocommerce'))) return;
    const defaults = {
      form_title: FORM_TEXT_DEFAULTS.form_title,
      form_description: FORM_TEXT_DEFAULTS.form_description,
      form_button_text: FORM_TEXT_DEFAULTS.form_button_text,
      form_placeholder: FORM_TEXT_DEFAULTS.form_placeholder,
      form_success_message: FORM_TEXT_DEFAULTS.form_success_message,
      show_waitlist_count: true,
      form_theme_mode: 'light',
      form_accent_color: '#2563eb',
      form_button_color: '#2563eb',
      form_background_color: '#ffffff',
      form_text_color: '#0f172a',
      form_description_color: '#64748b',
      form_input_background_color: '#ffffff',
      form_count_text_color: '#334155',
      form_box_shadow_enabled: true,
      form_title_font_size: 17,
      form_description_font_size: 14,
      form_input_font_size: 16,
      form_button_font_size: 14,
      form_count_font_size: 13,
      form_success_font_size: 15
    };
    try {
      await saveSettings(defaults);
      applySettings(defaults);
      showToast(__('Waitlist form reset to defaults.', 'stockbeacon-product-waitlists-for-woocommerce'));
    } catch {
      showToast(__('Could not reset waitlist form.', 'stockbeacon-product-waitlists-for-woocommerce'), 'error');
    }
  };
  const applyThemeMode = (mode: 'light' | 'dark') => {
    setThemeMode(mode);
    if (mode === 'dark') {
      if (backgroundColor === '#ffffff') setBackgroundColor('#101827');
      if (textColor === '#0f172a') setTextColor('#f8fafc');
      if (descriptionColor === '#64748b') setDescriptionColor('#cbd5e1');
      if (inputBackgroundColor === '#ffffff') setInputBackgroundColor('#0f172a');
      if (countTextColor === '#334155') setCountTextColor('#14532d');
      return;
    }
    if (backgroundColor === '#101827') setBackgroundColor('#ffffff');
    if (textColor === '#f8fafc') setTextColor('#0f172a');
    if (descriptionColor === '#cbd5e1') setDescriptionColor('#64748b');
    if (inputBackgroundColor === '#0f172a') setInputBackgroundColor('#ffffff');
    if (countTextColor === '#14532d') setCountTextColor('#334155');
  };
  const previewSettings: Settings = {
    form_title: formTitle,
    form_description: formDescription,
    form_button_text: formButtonText,
    form_placeholder: formPlaceholder,
    form_success_message: formSuccessMessage,
    show_waitlist_count: showWaitlistCount,
    form_theme_mode: themeMode,
    form_accent_color: accentColor,
    form_button_color: buttonColor,
    form_background_color: backgroundColor,
    form_text_color: textColor,
    form_description_color: descriptionColor,
    form_input_background_color: inputBackgroundColor,
    form_count_text_color: countTextColor,
    form_box_shadow_enabled: boxShadowEnabled,
    form_title_font_size: titleFontSize,
    form_description_font_size: descriptionFontSize,
    form_input_font_size: inputFontSize,
    form_button_font_size: buttonFontSize,
    form_count_font_size: countFontSize,
    form_success_font_size: successFontSize,
    form_template: 'card'
  };
  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-form-title-h">
						<div className="stockbeacon-settings-card__head">
							<h3 id="stockbeacon-free-form-title-h">{__("Waitlist form", "stockbeacon-product-waitlists-for-woocommerce")}</h3>
							<p>{__("Customize the copy and accent color customers see on product pages.", "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-ff-title">{__("Form title", "stockbeacon-product-waitlists-for-woocommerce")}</label>
								<input type="text" className="regular-text" id="stockbeacon-ff-title" autoComplete="off" disabled={!loaded} value={formTitle} onChange={e => setFormTitle(e.target.value)} />
							</div>
							<div className="stockbeacon-settings-field">
								<label className="stockbeacon-settings-label" htmlFor="stockbeacon-ff-desc">{__("Form description", "stockbeacon-product-waitlists-for-woocommerce")}</label>
								<textarea className="large-text" rows={2} id="stockbeacon-ff-desc" disabled={!loaded} value={formDescription} onChange={e => setFormDescription(e.target.value)} />
							</div>
							<div className="stockbeacon-settings-two">
								<div className="stockbeacon-settings-field">
									<label className="stockbeacon-settings-label" htmlFor="stockbeacon-ff-btn">{__("Button label", "stockbeacon-product-waitlists-for-woocommerce")}</label>
									<input type="text" className="regular-text" id="stockbeacon-ff-btn" autoComplete="off" disabled={!loaded} value={formButtonText} onChange={e => setFormButtonText(e.target.value)} />
								</div>
								<div className="stockbeacon-settings-field">
									<label className="stockbeacon-settings-label" htmlFor="stockbeacon-ff-ph">{__("Email placeholder", "stockbeacon-product-waitlists-for-woocommerce")}</label>
									<input type="text" className="regular-text" id="stockbeacon-ff-ph" autoComplete="off" disabled={!loaded} value={formPlaceholder} onChange={e => setFormPlaceholder(e.target.value)} />
								</div>
							</div>
							<div className="stockbeacon-settings-field">
								<label className="stockbeacon-settings-label" htmlFor="stockbeacon-ff-success">{__("Success message", "stockbeacon-product-waitlists-for-woocommerce")}</label>
								<textarea className="large-text" rows={2} id="stockbeacon-ff-success" disabled={!loaded} value={formSuccessMessage} onChange={e => setFormSuccessMessage(e.target.value)} />
							</div>
							<div className="stockbeacon-settings-field">
								<label className="stockbeacon-settings-check" htmlFor="stockbeacon-ff-count">
									<input type="checkbox" id="stockbeacon-ff-count" disabled={!loaded} checked={showWaitlistCount} onChange={e => setShowWaitlistCount(e.target.checked)} />
									<span>{__("Show how many people are on the waitlist.", "stockbeacon-product-waitlists-for-woocommerce")}</span>
								</label>
							</div>
							<div className="stockbeacon-settings-field">
								<label className="stockbeacon-settings-check" htmlFor="stockbeacon-ff-shadow">
									<input type="checkbox" id="stockbeacon-ff-shadow" disabled={!loaded} checked={boxShadowEnabled} onChange={e => setBoxShadowEnabled(e.target.checked)} />
									<span>{__("Show box shadow on the waitlist form.", "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-ff-title-size">{__("Title size", "stockbeacon-product-waitlists-for-woocommerce")}</label>
									<div className="stockbeacon-slider-row">
										<input id="stockbeacon-ff-title-size" type="range" min={12} max={32} disabled={!loaded} value={titleFontSize} onChange={e => setTitleFontSize(Number(e.target.value))} />
										<input type="number" min={12} max={32} disabled={!loaded} value={titleFontSize} onChange={e => setTitleFontSize(Number(e.target.value))} aria-label={__("Form title font size", "stockbeacon-product-waitlists-for-woocommerce")} />
									</div>
								</div>
								<div className="stockbeacon-settings-field">
									<label className="stockbeacon-settings-label" htmlFor="stockbeacon-ff-description-size">{__("Description size", "stockbeacon-product-waitlists-for-woocommerce")}</label>
									<div className="stockbeacon-slider-row">
										<input id="stockbeacon-ff-description-size" type="range" min={11} max={24} disabled={!loaded} value={descriptionFontSize} onChange={e => setDescriptionFontSize(Number(e.target.value))} />
										<input type="number" min={11} max={24} disabled={!loaded} value={descriptionFontSize} onChange={e => setDescriptionFontSize(Number(e.target.value))} aria-label={__("Form description font size", "stockbeacon-product-waitlists-for-woocommerce")} />
									</div>
								</div>
								<div className="stockbeacon-settings-field">
									<label className="stockbeacon-settings-label" htmlFor="stockbeacon-ff-input-size">{__("Input size", "stockbeacon-product-waitlists-for-woocommerce")}</label>
									<div className="stockbeacon-slider-row">
										<input id="stockbeacon-ff-input-size" type="range" min={12} max={22} disabled={!loaded} value={inputFontSize} onChange={e => setInputFontSize(Number(e.target.value))} />
										<input type="number" min={12} max={22} disabled={!loaded} value={inputFontSize} onChange={e => setInputFontSize(Number(e.target.value))} aria-label={__("Form input font size", "stockbeacon-product-waitlists-for-woocommerce")} />
									</div>
								</div>
								<div className="stockbeacon-settings-field">
									<label className="stockbeacon-settings-label" htmlFor="stockbeacon-ff-button-size">{__("Button size", "stockbeacon-product-waitlists-for-woocommerce")}</label>
									<div className="stockbeacon-slider-row">
										<input id="stockbeacon-ff-button-size" type="range" min={12} max={22} disabled={!loaded} value={buttonFontSize} onChange={e => setButtonFontSize(Number(e.target.value))} />
										<input type="number" min={12} max={22} disabled={!loaded} value={buttonFontSize} onChange={e => setButtonFontSize(Number(e.target.value))} aria-label={__("Form button font size", "stockbeacon-product-waitlists-for-woocommerce")} />
									</div>
								</div>
								<div className="stockbeacon-settings-field">
									<label className="stockbeacon-settings-label" htmlFor="stockbeacon-ff-count-size">{__("Waitlist count size", "stockbeacon-product-waitlists-for-woocommerce")}</label>
									<div className="stockbeacon-slider-row">
										<input id="stockbeacon-ff-count-size" type="range" min={10} max={18} disabled={!loaded} value={countFontSize} onChange={e => setCountFontSize(Number(e.target.value))} />
										<input type="number" min={10} max={18} disabled={!loaded} value={countFontSize} onChange={e => setCountFontSize(Number(e.target.value))} aria-label={__("Waitlist count font size", "stockbeacon-product-waitlists-for-woocommerce")} />
									</div>
								</div>
								<div className="stockbeacon-settings-field">
									<label className="stockbeacon-settings-label" htmlFor="stockbeacon-ff-success-size">{__("Success message size", "stockbeacon-product-waitlists-for-woocommerce")}</label>
									<div className="stockbeacon-slider-row">
										<input id="stockbeacon-ff-success-size" type="range" min={11} max={24} disabled={!loaded} value={successFontSize} onChange={e => setSuccessFontSize(Number(e.target.value))} />
										<input type="number" min={11} max={24} disabled={!loaded} value={successFontSize} onChange={e => setSuccessFontSize(Number(e.target.value))} aria-label={__("Success message font size", "stockbeacon-product-waitlists-for-woocommerce")} />
									</div>
								</div>
							</div>
							<div className="stockbeacon-settings-field">
								<span className="stockbeacon-settings-label">{__("Theme", "stockbeacon-product-waitlists-for-woocommerce")}</span>
								<div className="stockbeacon-segmented stockbeacon-segmented--two">
									<button type="button" className={themeMode === 'light' ? 'is-active' : ''} disabled={!loaded} onClick={() => applyThemeMode('light')}>{__("Light", "stockbeacon-product-waitlists-for-woocommerce")}</button>
									<button type="button" className={themeMode === 'dark' ? 'is-active' : ''} disabled={!loaded} onClick={() => applyThemeMode('dark')}>{__("Dark", "stockbeacon-product-waitlists-for-woocommerce")}</button>
								</div>
							</div>
							<div className="stockbeacon-settings-field">
								<label className="stockbeacon-settings-label" htmlFor="stockbeacon-ff-accent">{__("Accent color", "stockbeacon-product-waitlists-for-woocommerce")}</label>
								<ColorControl inputId="stockbeacon-ff-accent" label={__("Accent color", "stockbeacon-product-waitlists-for-woocommerce")} disabled={!loaded} value={accentColor} onChange={setAccentColor} />
							</div>
							<div className="stockbeacon-settings-field">
								<label className="stockbeacon-settings-label" htmlFor="stockbeacon-ff-button-color">{__("Button color", "stockbeacon-product-waitlists-for-woocommerce")}</label>
								<ColorControl inputId="stockbeacon-ff-button-color" label={__("Button color", "stockbeacon-product-waitlists-for-woocommerce")} disabled={!loaded} value={buttonColor} onChange={setButtonColor} />
							</div>
							<div className="stockbeacon-settings-two">
								<div className="stockbeacon-settings-field">
									<label className="stockbeacon-settings-label" htmlFor="stockbeacon-ff-background">{__("Form background", "stockbeacon-product-waitlists-for-woocommerce")}</label>
									<ColorControl inputId="stockbeacon-ff-background" label={__("Form background", "stockbeacon-product-waitlists-for-woocommerce")} disabled={!loaded} value={backgroundColor} onChange={setBackgroundColor} fallback="#ffffff" />
								</div>
								<div className="stockbeacon-settings-field">
									<label className="stockbeacon-settings-label" htmlFor="stockbeacon-ff-text-color">{__("Title text", "stockbeacon-product-waitlists-for-woocommerce")}</label>
									<ColorControl inputId="stockbeacon-ff-text-color" label={__("Title text color", "stockbeacon-product-waitlists-for-woocommerce")} disabled={!loaded} value={textColor} onChange={setTextColor} fallback="#0f172a" />
								</div>
								<div className="stockbeacon-settings-field">
									<label className="stockbeacon-settings-label" htmlFor="stockbeacon-ff-description-color">{__("Description text", "stockbeacon-product-waitlists-for-woocommerce")}</label>
									<ColorControl inputId="stockbeacon-ff-description-color" label={__("Description text color", "stockbeacon-product-waitlists-for-woocommerce")} disabled={!loaded} value={descriptionColor} onChange={setDescriptionColor} fallback="#64748b" />
								</div>
								<div className="stockbeacon-settings-field">
									<label className="stockbeacon-settings-label" htmlFor="stockbeacon-ff-input-background">{__("Input background", "stockbeacon-product-waitlists-for-woocommerce")}</label>
									<ColorControl inputId="stockbeacon-ff-input-background" label={__("Input background", "stockbeacon-product-waitlists-for-woocommerce")} disabled={!loaded} value={inputBackgroundColor} onChange={setInputBackgroundColor} fallback="#ffffff" />
								</div>
								<div className="stockbeacon-settings-field">
									<label className="stockbeacon-settings-label" htmlFor="stockbeacon-ff-count-text-color">{__("Waitlist count text", "stockbeacon-product-waitlists-for-woocommerce")}</label>
									<ColorControl inputId="stockbeacon-ff-count-text-color" label={__("Waitlist count text color", "stockbeacon-product-waitlists-for-woocommerce")} disabled={!loaded} value={countTextColor} onChange={setCountTextColor} fallback="#334155" />
								</div>
							</div>
						</div>
						<div className="stockbeacon-settings-card__foot">
							<SaveButton state={state} onClick={execute}>{__("Save form", "stockbeacon-product-waitlists-for-woocommerce")}</SaveButton>
							<button type="button" className="button" onClick={handleReset}>{__("Reset to default", "stockbeacon-product-waitlists-for-woocommerce")}</button>
						</div>
					</section>
				</div>
				<div className="stockbeacon-free-editor__preview">
					<ContextualUpsell title={__("Form templates and automation", "stockbeacon-product-waitlists-for-woocommerce")}>{__("Pro adds form templates, custom CSS, consent controls, double opt-in, success redirects, low-stock capture, and provider sync for marketing lists and tags.", "stockbeacon-product-waitlists-for-woocommerce")}</ContextualUpsell>
					<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--form${themeMode === 'dark' ? ' is-dark' : ''}`}>
							<FormDesignPreview settings={previewSettings} count={3} />
						</div>
					</div>
				</div>
			</div>
		</div>;
}
