import { Offcanvas, Switch } from "../offcanvas";
import { useState } from '@wordpress/element';
import { toast } from 'react-toastify';
import { __ } from '@wordpress/i18n';
import { RawHTML } from "@wordpress/element";
import Widget from "../widgets/Widget";
import apiFetch from '@wordpress/api-fetch';
import { Notice } from '@wordpress/components';

/* ── Inline icons ─────────────────────────────────────────────────────────── */
const ico = (d) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" dangerouslySetInnerHTML={{ __html: d }} />
);
const I = {
    globe:    ico('<circle cx="12" cy="12" r="9"/><path d="M2 12h20M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/>'),
    plus:     ico('<path d="M12 5v14M5 12h14"/>'),
    trash:    ico('<polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"/>'),
    rate:     ico('<path d="M7 16V4m0 0L3 8m4-4 4 4M17 8v12m0 0 4-4m-4 4-4-4"/>'),
    chevron:  ico('<path d="m6 9 6 6 6-6"/>'),
    lock:     ico('<rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/>'),
    enable:   ico('<circle cx="12" cy="12" r="9"/><path d="m9 12 2 2 4-4"/>'),
};

/* ── Single currency accordion row ───────────────────────────────────────── */
function CurrencyRow({ item, isDefault, onUpdate, onRemove }) {
    const [open, setOpen] = useState(false);

    return (
        <div className={`strb-cs-row${open ? ' is-open' : ''}`}>
            <button type="button" className="strb-cs-row-head" onClick={() => setOpen(o => !o)}>
                <span className="strb-cs-code">{item.currency}</span>
                <span className="strb-cs-symbol"><RawHTML>{item.symbol}</RawHTML></span>
                {isDefault && <span className="strb-cs-default-badge">{__('Default', 'shopbuild')}</span>}
                {!isDefault && item.rate && <span className="strb-cs-rate-preview">×{item.rate}</span>}
                <span className="strb-cs-chevron">{I.chevron}</span>
            </button>
            {open && (
                <div className="strb-cs-row-body">
                    {isDefault ? (
                        <div className="strb-cs-default-info">
                            <span className="strb-cs-lock-ic">{I.lock}</span>
                            <span>{__('This is your WooCommerce default currency and cannot be edited here.', 'shopbuild')}</span>
                        </div>
                    ) : (
                        <>
                            <div className="strb-cs-fields">
                                <label className="strb-cs-field">
                                    <span className="strb-cs-field-label">{__('Currency Name', 'shopbuild')}</span>
                                    <input
                                        type="text"
                                        className="strb-cs-input"
                                        value={item.currency}
                                        placeholder="USD"
                                        onChange={(e) => onUpdate(item.currency, e.target.value, 'currency')}
                                    />
                                </label>
                                <label className="strb-cs-field">
                                    <span className="strb-cs-field-label">{__('Symbol', 'shopbuild')}</span>
                                    <input
                                        type="text"
                                        className="strb-cs-input"
                                        value={item.symbol}
                                        placeholder="$"
                                        onChange={(e) => onUpdate(item.currency, e.target.value, 'symbol')}
                                    />
                                </label>
                                <label className="strb-cs-field">
                                    <span className="strb-cs-field-label">{__('Exchange Rate', 'shopbuild')}</span>
                                    <input
                                        type="number"
                                        className="strb-cs-input"
                                        value={item.rate}
                                        placeholder="0.090"
                                        step="0.001"
                                        onChange={(e) => onUpdate(item.currency, e.target.value, 'rate')}
                                    />
                                </label>
                            </div>
                            <button
                                type="button"
                                className="strb-cs-delete-btn"
                                onClick={() => onRemove(item.currency)}
                            >
                                {I.trash}
                                {__('Remove Currency', 'shopbuild')}
                            </button>
                        </>
                    )}
                </div>
            )}
        </div>
    );
}

export default function CurrencySwitcher({ video, id, docs }) {
    const [newCurrency, setNewCurrency] = useState({ currency: '', symbol: '', rate: '' });
    const [currencySwitcher, setCurrencySwitcher] = useState(false);
    const [currencySwitcherSettings, setCurrencySwitcherSettings] = useState(storebuild.settings._storebuild_currency_switcher.storebuild_currency_switcher_list);
    const [currencySwitcherEnable, setCurrencySwitcherEnable] = useState(storebuild.settings._storebuild_currency_switcher.storebuild_enable_module);
    const defaultCurrency = storebuild.default_currency;
    const hasPro = Boolean(storebuild?.is_pro_active);

    const saveSettings = () => {
        apiFetch({
            path: '/wp/v2/settings',
            method: 'POST',
            data: {
                _storebuild_currency_switcher: {
                    storebuild_enable_module: currencySwitcherEnable,
                    storebuild_currency_switcher_list: currencySwitcherSettings
                },
            },
        }).then(() => {
            toast.success(__('Settings saved.', 'shopbuild'));
        }).catch(() => {
            toast.error(__('Failed to save settings.', 'shopbuild'));
        });
    };

    const addCurrencyToList = () => {
        if (!newCurrency.currency || !newCurrency.symbol || newCurrency.rate === '') {
            toast.warn(__('Please fill out all fields.', 'shopbuild'));
            return;
        }
        setCurrencySwitcherSettings(prev => [...prev, { ...newCurrency, position: '', display: false }]);
        setNewCurrency({ currency: '', symbol: '', rate: '' });
    };

    const removeCurrencyFromList = (code) => {
        setCurrencySwitcherSettings(prev => prev.filter(item => item.currency !== code));
    };

    const updateCurrencySettings = (code, value, prop) => {
        setCurrencySwitcherSettings(prev =>
            prev.map(item => item.currency === code ? { ...item, [prop]: value } : item)
        );
    };

    const proNotice = __('Use <a target="_blank" href="https://storebuild.shop/pricing/">StoreBuild Pro</a> to add more currencies to the list.', 'shopbuild');

    return (
        <>
            <Widget
                title='Currency Switcher'
                description='User can switch currency for better selling experience.'
                toggle={false}
                settings={true}
                onChange={() => setCurrencySwitcher(v => !v)}
                isPro={false}
                active={true}
            />
            <Offcanvas
                open={currencySwitcher}
                onClose={() => setCurrencySwitcher(v => !v)}
                heading='Currency Switcher'
                subtitle='Let customers browse and shop in their preferred currency with live rate conversion.'
                onSave={saveSettings}
                video={video}
                id={id}
                docs={docs}
            >
                {/* Enable / Disable */}
                <div className="strb-offcanvas-option">
                    <Switch
                        id='storebuild_enable_module'
                        title='Enable / Disable'
                        text='Show or hide the Currency Switcher on the front end.'
                        icon={I.enable}
                        defaultValue={currencySwitcherEnable}
                        onChange={() => setCurrencySwitcherEnable(v => !v)}
                    />
                </div>

                {/* Currency List */}
                <div className="strb-offcanvas-option strb-cs-card">
                    <div className="strb-cs-section-head">
                        <span className="strb-cs-section-ic">{I.globe}</span>
                        <div>
                            <h4>{__('Currency List', 'shopbuild')}</h4>
                            <p>{__('Manage your active currencies.', 'shopbuild')}</p>
                        </div>
                    </div>
                    <div className="strb-cs-list">
                        <CurrencyRow
                            item={defaultCurrency}
                            isDefault={true}
                            onUpdate={updateCurrencySettings}
                            onRemove={removeCurrencyFromList}
                        />
                        {currencySwitcherSettings.map((item, index) => {
                            if (!hasPro && index >= 2) return null;
                            return (
                                <CurrencyRow
                                    key={index}
                                    item={item}
                                    isDefault={false}
                                    onUpdate={updateCurrencySettings}
                                    onRemove={removeCurrencyFromList}
                                />
                            );
                        })}
                        {!hasPro && currencySwitcherSettings.length >= 2 && (
                            <div className="strb-cs-pro-notice">
                                <Notice status="warning" isDismissible={false}>
                                    <RawHTML>{proNotice}</RawHTML>
                                </Notice>
                            </div>
                        )}
                    </div>
                </div>

                {/* Add New Currency */}
                <div className="strb-offcanvas-option strb-cs-card">
                    <div className="strb-cs-section-head">
                        <span className="strb-cs-section-ic">{I.plus}</span>
                        <div>
                            <h4>{__('Add New Currency', 'shopbuild')}</h4>
                            <p>{__('Enter details to add a new currency to the switcher.', 'shopbuild')}</p>
                        </div>
                    </div>
                    {!hasPro ? (
                        <div className="strb-cs-pro-notice">
                            <Notice status="warning" isDismissible={false}>
                                <RawHTML>{proNotice}</RawHTML>
                            </Notice>
                        </div>
                    ) : (
                        <div className="strb-cs-add-form">
                            <div className="strb-cs-fields">
                                <label className="strb-cs-field">
                                    <span className="strb-cs-field-label">{__('Currency Name', 'shopbuild')}</span>
                                    <input
                                        type="text"
                                        className="strb-cs-input"
                                        value={newCurrency.currency}
                                        placeholder="USD"
                                        onChange={(e) => setNewCurrency(p => ({ ...p, currency: e.target.value }))}
                                    />
                                </label>
                                <label className="strb-cs-field">
                                    <span className="strb-cs-field-label">{__('Symbol', 'shopbuild')}</span>
                                    <input
                                        type="text"
                                        className="strb-cs-input"
                                        value={newCurrency.symbol}
                                        placeholder="$"
                                        onChange={(e) => setNewCurrency(p => ({ ...p, symbol: e.target.value }))}
                                    />
                                </label>
                                <label className="strb-cs-field">
                                    <span className="strb-cs-field-label">{__('Exchange Rate', 'shopbuild')}</span>
                                    <input
                                        type="number"
                                        className="strb-cs-input"
                                        value={newCurrency.rate}
                                        placeholder="0.090"
                                        step="0.001"
                                        onChange={(e) => setNewCurrency(p => ({ ...p, rate: e.target.value }))}
                                    />
                                </label>
                            </div>
                            <button type="button" className="strb-cs-add-btn" onClick={addCurrencyToList}>
                                {I.plus}
                                {__('Add Currency', 'shopbuild')}
                            </button>
                        </div>
                    )}
                </div>
            </Offcanvas>
        </>
    );
}
