import { registerPlugin } from '@wordpress/plugins';
import { PluginSidebar } from '@wordpress/editor';
import { TextControl, CheckboxControl, __experimentalNumberControl as NumberControl, SelectControl, PanelBody } from '@wordpress/components';
import { useSelect } from '@wordpress/data';
import { useEntityProp } from '@wordpress/core-data';
import { __ } from '@wordpress/i18n';
import './index.scss';

function usePostMeta() {
    const postType = useSelect((s) => s('core/editor').getCurrentPostType(), []);
    const [meta, setMeta] = useEntityProp('postType', postType, 'meta');
    const update = (key, value) => setMeta({ ...(meta || {}), [key]: value });
    return { meta: meta || {}, update };
}

function RecastMetaPanel() {
    const { meta, update } = usePostMeta();
    const isActive = useSelect((select) => {
        const { getActiveGeneralSidebarName } = select('core/edit-post');
        const activeName = getActiveGeneralSidebarName();
        return activeName === 'recast-paywall-meta/recast-paywall-meta-panel';
    }, []);

    return (
        <PluginSidebar
            name="recast-paywall-meta-panel"
            title={ __('Recast Paywall', 'recast-paywall') }
            icon={ (typeof recastPaywallMeta !== 'undefined' && recastPaywallMeta.iconUrl)
                ? <img
                    className="recast-paywall-icon"
                    src={ recastPaywallMeta.iconUrl }
                    alt=""
                    style={{ width: 20, height: 20, filter: isActive ? 'brightness(0) invert(1)' : 'none' }}
                  />
                : undefined }
            className="recast-paywall-meta-panel"
        >
            <PanelBody initialOpen>
            <CheckboxControl
                label={ __('Enable paywall for this post', 'recast-paywall') }
                checked={ !!meta._recast_paywall_enabled }
                onChange={(v) => update('_recast_paywall_enabled', !!v)}
            />
            <div style={{ opacity: meta._recast_paywall_enabled ? 1 : 0.5, pointerEvents: meta._recast_paywall_enabled ? 'auto' : 'none' }}>
                <SelectControl
                    label={ __('Mode', 'recast-paywall') }
                    value={ meta._recast_gating_mode || 'post' }
                    options={[
                        { label: __('Post (entire article)', 'recast-paywall'), value: 'post' },
                        { label: __('Block (only selected blocks)', 'recast-paywall'), value: 'block' },
                    ]}
                    onChange={(v) => update('_recast_gating_mode', v)}
                />

                <NumberControl
                    label={ __('Price', 'recast-paywall') }
                    value={ meta._recast_price ?? 0 }
                    onChange={(v) => update('_recast_price', Number(v))}
                    min={0}
                />

                <SelectControl
                    label={ __('Status', 'recast-paywall') }
                    value={ meta._recast_status || '' }
                    options={[
                        { label: 'PRESALE', value: 'PRESALE' },
                        { label: 'PURCHASEABLE', value: 'PURCHASEABLE' },
                        { label: 'UNPURCHASEABLE', value: 'UNPURCHASEABLE' },
                    ]}
                    onChange={(v) => update('_recast_status', v)}
                />

                <TextControl
                    label={ __('Geo availability', 'recast-paywall') }
                    value={ meta._recast_geo_availability || '' }
                    onChange={(v) => update('_recast_geo_availability', v)}
                    help={ __('Use ISO 3166-1 alpha-2 codes (e.g., US, GB, CA, AU). Leave empty for global availability.', 'recast-paywall') }
                />

                <NumberControl
                    label={ __('Affiliate share %', 'recast-paywall') }
                    value={ meta._recast_affiliate_share_pct ?? 0 }
                    onChange={(v) => update('_recast_affiliate_share_pct', Number(v))}
                    min={0}
                    max={100}
                />
            </div>
            <p style={{ marginBottom: '16px', fontSize: '13px', color: '#646970' }}>
                { __('Manage your content paywall settings. ', 'recast-paywall') }
                {meta._recast_inventory_item_id ? (
    
                    <small>
                        <a 
                            href="https://business.recast.tv/inventory" 
                            target="_blank" 
                            rel="noopener noreferrer"
                            style={{ color: '#0073aa' }}
                        >
                            { __(`${meta._recast_inventory_item_id} →`, 'recast-paywall') }
                        </a>
                        <br />
                        { __('Last synced: ', 'recast-paywall') }
                        {meta._recast_last_synced_at ? meta._recast_last_synced_at : __('Not synced', 'recast-paywall')}
                    </small>
                ) : __('Not synced', 'recast-paywall')}
            </p>
            </PanelBody>
        </PluginSidebar>
    );
}

registerPlugin('recast-paywall-meta', { render: RecastMetaPanel });


