import { useCallback, useEffect, useState } from 'react';
import { fetchSettings, saveSettings } from '../../api';
import { useSave } from '../../hooks/useSave';
import { SaveButton } from '../SaveButton';
import type { Settings } from '../../types';
import { __ } from "@wordpress/i18n";
const POSITIONS = [{
  value: 'before_price',
  label: __('Before price', 'stockbeacon-product-waitlists-for-woocommerce')
}, {
  value: 'after_price',
  label: __('After price', 'stockbeacon-product-waitlists-for-woocommerce')
}, {
  value: 'before_add_to_cart',
  label: __('Before add to cart', 'stockbeacon-product-waitlists-for-woocommerce')
}, {
  value: 'after_add_to_cart',
  label: __('After add to cart', 'stockbeacon-product-waitlists-for-woocommerce')
}, {
  value: 'summary_end',
  label: __('End of product summary', 'stockbeacon-product-waitlists-for-woocommerce')
}];
export function GeneralSettingsPanel() {
  const [loaded, setLoaded] = useState(false);
  const [loadError, setLoadError] = useState(false);
  const [pluginEnabled, setPluginEnabled] = useState(true);
  const [displayPosition, setDisplayPosition] = useState('after_price');
  const [subscriberRetention, setSubscriberRetention] = useState('keep');
  const applySettings = useCallback((s: Settings) => {
    setPluginEnabled(s.plugin_enabled !== false);
    setDisplayPosition(String(s.form_display_position || 'after_price'));
    setSubscriberRetention(s.restock_subscriber_retention === 'remove' ? 'remove' : 'keep');
  }, []);
  useEffect(() => {
    let alive = true;
    fetchSettings().then(s => {
      if (!alive) return;
      applySettings(s);
      setLoadError(false);
    }).catch(() => {
      if (alive) setLoadError(true);
    }).finally(() => {
      if (alive) setLoaded(true);
    });
    return () => {
      alive = false;
    };
  }, [applySettings]);
  const {
    state,
    execute
  } = useSave(async () => {
    await saveSettings({
      plugin_enabled: pluginEnabled,
      form_display_position: displayPosition,
      restock_subscriber_retention: subscriberRetention
    });
  }, __('General settings saved.', 'stockbeacon-product-waitlists-for-woocommerce'), __('Could not save general settings.', 'stockbeacon-product-waitlists-for-woocommerce'));
  return <section className="stockbeacon-settings-card" aria-labelledby="stockbeacon-overview-general-title">
			<div className="stockbeacon-settings-card__head">
				<h3 id="stockbeacon-overview-general-title">{__("General settings", "stockbeacon-product-waitlists-for-woocommerce")}</h3>
				<p>{__("Control whether waitlists are active and where the storefront form appears on product pages.", "stockbeacon-product-waitlists-for-woocommerce")}</p>
			</div>
			<div className="stockbeacon-settings-card__body">
				{loadError && <p className="stockbeacon-settings-help">{__("Live settings are temporarily unavailable. Safe defaults are shown.", "stockbeacon-product-waitlists-for-woocommerce")}</p>}
				<div className="stockbeacon-settings-field">
					<label className="stockbeacon-settings-check" htmlFor="stockbeacon-plugin-enabled">
						<input type="checkbox" id="stockbeacon-plugin-enabled" checked={pluginEnabled} onChange={e => setPluginEnabled(e.target.checked)} disabled={!loaded} />
						<span>{__("Enable waitlist forms and customer signups.", "stockbeacon-product-waitlists-for-woocommerce")}</span>
					</label>
					<p className="stockbeacon-settings-help">{__("Turn this off to temporarily hide storefront forms and reject new waitlist submissions without deleting any subscriber data.", "stockbeacon-product-waitlists-for-woocommerce")}</p>
				</div>
				<div className="stockbeacon-settings-field">
					<label className="stockbeacon-settings-label" htmlFor="stockbeacon-form-display-position">{__("Display form after", "stockbeacon-product-waitlists-for-woocommerce")}</label>
					<div className="stockbeacon-settings-input-wrap">
						<select id="stockbeacon-form-display-position" className="regular-text" value={displayPosition} onChange={e => setDisplayPosition(e.target.value)} disabled={!loaded}>
							{POSITIONS.map(p => <option key={p.value} value={p.value}>{p.label}</option>)}
						</select>
					</div>
					<p className="stockbeacon-settings-help">{__("Applies to simple products. Variable product forms stay below the variation selector so the selected variation can be tracked correctly.", "stockbeacon-product-waitlists-for-woocommerce")}</p>
				</div>
				<div className="stockbeacon-settings-field">
					<span className="stockbeacon-settings-label">{__("Subscriber restock behavior", "stockbeacon-product-waitlists-for-woocommerce")}</span>
					<div className="stockbeacon-settings-two">
						<label className="stockbeacon-settings-check" htmlFor="stockbeacon-general-retention-keep">
							<input type="radio" id="stockbeacon-general-retention-keep" name="stockbeacon-general-retention" value="keep" disabled={!loaded} checked={subscriberRetention === 'keep'} onChange={e => setSubscriberRetention(e.target.value)} />
							<span>{__("Keep subscribers and reactivate them when the product goes out of stock again.", "stockbeacon-product-waitlists-for-woocommerce")}</span>
						</label>
						<label className="stockbeacon-settings-check" htmlFor="stockbeacon-general-retention-remove">
							<input type="radio" id="stockbeacon-general-retention-remove" name="stockbeacon-general-retention" value="remove" disabled={!loaded} checked={subscriberRetention === 'remove'} onChange={e => setSubscriberRetention(e.target.value)} />
							<span>{__("Remove subscribers after their restock email is sent.", "stockbeacon-product-waitlists-for-woocommerce")}</span>
						</label>
					</div>
					<p className="stockbeacon-settings-help">{__("Choose whether waitlist subscribers stay available for future restock cycles or are cleaned up after notification.", "stockbeacon-product-waitlists-for-woocommerce")}</p>
				</div>
			</div>
			<div className="stockbeacon-settings-card__foot">
				<SaveButton state={state} onClick={execute}>{__("Save general settings", "stockbeacon-product-waitlists-for-woocommerce")}</SaveButton>
			</div>
		</section>;
}
