import { Button, Modal } from '@wordpress/components';
import { useState } from '@wordpress/element';
import { Icon, info } from '@wordpress/icons';
import Glyph from '../icons/Glyph';

/* Relevant icon + short description per module, keyed by its (title).
   Module components only pass a title to <Widget>, so keying by title lets
   every module card show a meaningful icon + clean one-liner without
   touching each module component. */
const MODULE_META = {
    'Variation Swatches': { icon: 'swatch', desc: 'Image, color & size swatches' },
    'Sale Notification': { icon: 'bell', desc: 'Live sales popups on your store' },
    'Currency Switcher': { icon: 'currency', desc: 'Let customers switch currency' },
    'Invoice': { icon: 'invoice', desc: 'Downloadable order invoices' },
    'Quickview': { icon: 'eye', desc: 'Preview products in a popup' },
    'Quick View': { icon: 'eye', desc: 'Preview products in a popup' },
    'Backorder': { icon: 'box', desc: 'Accept orders for out-of-stock items' },
    'PreOrder': { icon: 'clock', desc: 'Sell products before launch' },
    'Pre-Order': { icon: 'clock', desc: 'Sell products before launch' },
    'Quick Checkout': { icon: 'bolt', desc: 'One-step buy flow' },
    'Floating Cart': { icon: 'cart', desc: 'Floating off-canvas cart' },
    'Fly Cart': { icon: 'cart', desc: 'Floating off-canvas cart' },
    'Mobile Navigation': { icon: 'phone', desc: 'App-style bottom nav bar' },
    'Wishlist': { icon: 'heart', desc: 'Save products for later' },
    'Compare': { icon: 'compare', desc: 'Compare products side-by-side' },
    'Real-Time Cart Notification': { icon: 'bolt', desc: 'Live add-to-cart notifications' },
    'Sale Badge': { icon: 'badge', desc: 'Show a sale badge on products' },
    'Flash Sale Countdown': { icon: 'timer', desc: 'Countdown timer on products' },
    'Cart Cross Sell Popup': { icon: 'gift', desc: 'Recommend products in cart' },
    'Backorders': { icon: 'box', desc: 'Accept orders for out-of-stock items' },
};

/* Per-widget icon + short description, keyed by widget title.
   Widget2 (Widgets tab) only receives title, so lookup by title. */
const WIDGET_META = {
    /* Shop */
    'Product Card':                   { icon: 'wcard',   desc: 'Display product in card style' },
    'Archive Products Grid':          { icon: 'wgrid',   desc: 'Show products in a grid layout' },
    'Archive Products Counts':        { icon: 'chart',   desc: 'Show product count in archive' },
    'Archive Products Ordering':      { icon: 'sort',    desc: 'Products ordering dropdown' },
    'Sidebar Products Search':        { icon: 'search',  desc: 'Product search in sidebar' },
    'Sidebar Products Price Filter':  { icon: 'filter',  desc: 'Filter products by price range' },
    'Sidebar Products Categories':    { icon: 'folder',  desc: 'Browse product categories' },
    'Sidebar Attribute Filter':       { icon: 'sliders', desc: 'Filter by product attributes' },
    'Sidebar Products Tags':          { icon: 'tag',     desc: 'Filter products by tags' },
    'Sidebar Top Rated':              { icon: 'star',    desc: 'Display top rated products' },
    'Sidebar Products Recent':        { icon: 'clock',   desc: 'Show recently viewed products' },
    'Sidebar Ajax Categories':        { icon: 'folder',  desc: 'AJAX-powered category filter' },
    'Sidebar Ajax Attributes':        { icon: 'sliders', desc: 'AJAX attribute filter' },
    'Sidebar Ajax Stock':             { icon: 'box',     desc: 'Filter by stock availability' },
    'Sidebar Ajax Ratings':           { icon: 'star',    desc: 'Filter by product rating' },
    'Shopbuild Ajax Search':          { icon: 'search',  desc: 'Live AJAX search for store' },
    'Horizontal Filters':             { icon: 'filter',  desc: 'Horizontal AJAX filter bar' },
    'Product Hover Overly':           { icon: 'eye',     desc: 'Hover overlay on product cards' },
    'Archive Product Hover Overly':   { icon: 'eye',     desc: 'Hover overlay in product archive' },
    'Marquee Slider':                 { icon: 'wmarq',   desc: 'Animated scrolling marquee ticker' },
    'Product Card List':              { icon: 'wcard',   desc: 'Product card in list layout' },
    'Product Card Advanced':          { icon: 'layers',  desc: 'Advanced product card layout' },
    'Collection Card':                { icon: 'folder',  desc: 'Showcase product collections' },
    'Product Category Image':         { icon: 'wimg',    desc: 'Category with featured image' },
    'Video Popup':                    { icon: 'video',   desc: 'Play product video in a popup' },
    'Sidebar Ajax Availability':      { icon: 'check',   desc: 'AJAX filter by availability' },
    'Sidebar Dynamic Taxonomy':       { icon: 'folder',  desc: 'Dynamic taxonomy filter' },
    'Layout Switcher':                { icon: 'wgrid',   desc: 'Switch grid & list layouts' },
    /* Shop Details (single product) */
    'Single Product Title':           { icon: 'wtext',   desc: 'Product name heading' },
    'Single Product Price':           { icon: 'currency',desc: 'Product price display' },
    'Single Add To Cart':             { icon: 'cart',    desc: 'Add to cart button' },
    'Single Product Thumbnail':       { icon: 'wimg',    desc: 'Product gallery & images' },
    'Single Product Short Description':{ icon: 'wtext',  desc: 'Short product description' },
    'Single Product SKU':             { icon: 'tag',     desc: 'Product SKU identifier' },
    'Single Product Category':        { icon: 'folder',  desc: 'Product category links' },
    'Single Product Tags':            { icon: 'tag',     desc: 'Product tag list' },
    'Single Product Buy Now':         { icon: 'bolt',    desc: 'Instant buy now button' },
    'Single Product Compare':         { icon: 'compare', desc: 'Compare with other products' },
    'Single Product Wishlist':        { icon: 'heart',   desc: 'Save product to wishlist' },
    'Single Product Ratings':         { icon: 'star',    desc: 'Product star rating' },
    'Single Product Related':         { icon: 'wgrid',   desc: 'Related products grid' },
    'Single Product Reviews':         { icon: 'star',    desc: 'Customer reviews list' },
    'Single Product Tabs':            { icon: 'layers',  desc: 'Description & reviews tabs' },
    'Single Product Breadcrumb':      { icon: 'sort',    desc: 'Navigation breadcrumb' },
    'Single Product Stock':           { icon: 'box',     desc: 'Stock availability display' },
    'Single Product Social':          { icon: 'bell',    desc: 'Social share buttons' },
    'Single Product Review Form':     { icon: 'wchk',    desc: 'Submit a product review' },
    'Single Product Review Overview': { icon: 'chart',   desc: 'Review score overview' },
    'Single Product Saletimer':       { icon: 'timer',   desc: 'Sale countdown timer' },
    /* Cart */
    'Cart Table':                     { icon: 'cart',    desc: 'Full cart items table' },
    'Cart Subtotal':                  { icon: 'chart',   desc: 'Cart subtotal & totals' },
    'Cart Coupon':                    { icon: 'badge',   desc: 'Apply a coupon code' },
    'Cart Cross Sell':                { icon: 'gift',    desc: 'Cross-sell product suggestions' },
    /* Checkout */
    'Checkout Billing':               { icon: 'invoice', desc: 'Billing address form' },
    'Checkout Shipping':              { icon: 'truck',   desc: 'Shipping address form' },
    'Checkout Order':                 { icon: 'wcard',   desc: 'Order summary before payment' },
    'Checkout Payment':               { icon: 'currency',desc: 'Payment method selection' },
    'Checkout Coupon':                { icon: 'badge',   desc: 'Apply coupon at checkout' },
    'Checkout Existing Login':        { icon: 'user',    desc: 'Login prompt for returning customers' },
    'Checkout Note':                  { icon: 'wtext',   desc: 'Order notes field' },
    /* Thank You */
    'Order Confirmation':             { icon: 'check',   desc: 'Order confirmation message' },
    'Order Details':                  { icon: 'wcard',   desc: 'Detailed order information' },
    'Order Total':                    { icon: 'chart',   desc: 'Total amount for the order' },
    'Order Payment':                  { icon: 'currency',desc: 'Payment method & summary' },
    'Order Date':                     { icon: 'clock',   desc: 'Date and time of the order' },
    'Order Shipping':                 { icon: 'truck',   desc: 'Shipping method & address' },
    'Order ThankYou Message':         { icon: 'heart',   desc: 'Thank you confirmation message' },
    'Order Overview':                 { icon: 'layers',  desc: 'Summary overview of the order' },
    'Order Number':                   { icon: 'sort',    desc: 'Unique order ID / number' },
    'Order Meta':                     { icon: 'tag',     desc: 'Order metadata and labels' },
    'Order Billing':                  { icon: 'invoice', desc: 'Billing address details' },
    'Order Customer Details':         { icon: 'user',    desc: 'Customer info & contact' },
    'Order Recommendation':           { icon: 'star',    desc: 'Recommended products post-order' },
    /* My Account */
    'My Account':                     { icon: 'user',    desc: 'Full My Account dashboard' },
    'My Account Content':             { icon: 'layers',  desc: 'Main account content area' },
    'My Account Content Box':         { icon: 'box',     desc: 'Account content container block' },
    'My Account User':                { icon: 'user',    desc: 'User profile & avatar display' },
    'My Account Navigation':          { icon: 'sliders', desc: 'Account section navigation menu' },
    'My Account Login':               { icon: 'user',    desc: 'Login form for account access' },
    'My Account Register':            { icon: 'wchk',    desc: 'New customer registration form' },
    'My Account Welcome':             { icon: 'star',    desc: 'Welcome message for logged-in users' },
    'My Account Dashboard Card':      { icon: 'wcard',   desc: 'Summary card on account dashboard' },
    'Logout Button':                  { icon: 'bolt',    desc: 'Sign out from the account' },
    'Login Form':                     { icon: 'user',    desc: 'WooCommerce login form' },
    /* Header */
    'Wishlist Counter':               { icon: 'heart',   desc: 'Wishlist icon with item count' },
    'Compare Counter':                { icon: 'compare', desc: 'Compare icon with count' },
    'Mini Cart':                      { icon: 'cart',    desc: 'Cart icon with item count' },
    'Cart Counter':                   { icon: 'cart',    desc: 'Cart icon with item count' },
    'My Account Link':                { icon: 'user',    desc: 'My account navigation link' },
    'Search Form':                    { icon: 'search',  desc: 'Site search form widget' },
    /* Landing */
    'Comparison Slider':              { icon: 'compare', desc: 'Before/after comparison slider' },
    'Product Slider':                 { icon: 'wmarq',   desc: 'Scrolling product slider' },
    'Product Slider 2':               { icon: 'wmarq',   desc: 'Alternative product slider style' },
    'Hero Slider':                    { icon: 'wimg',    desc: 'Full-width hero image slider' },
    'Home Banner':                    { icon: 'wimg',    desc: 'Promotional home page banner' },
    'Icon Box':                       { icon: 'box',     desc: 'Icon with heading and text' },
    'Fun Fact':                       { icon: 'chart',   desc: 'Animated stats and fun facts' },
    'Instagram':                      { icon: 'wimg',    desc: 'Instagram feed display' },
    'Brand':                          { icon: 'badge',   desc: 'Brand logo showcase' },
    'Category':                       { icon: 'folder',  desc: 'Product category display' },
    'Testimonial':                    { icon: 'heart',   desc: 'Customer testimonials & reviews' },
    'Accordion':                      { icon: 'sliders', desc: 'Expandable FAQ accordion' },
    'Shop Features':                  { icon: 'star',    desc: 'Store feature highlights' },
    'Product Advanced Tab':           { icon: 'layers',  desc: 'Advanced tabbed product layout' },
    /* Offer */
    'Countdown':                      { icon: 'timer',   desc: 'Countdown timer widget' },
    'Offer Banner':                   { icon: 'badge',   desc: 'Promotional offer banner' },
};

/* Concept icon tile glyph shown on every widget/module card. */
const WIcon = () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" width="23" height="23">
        <rect x="3" y="3" width="7" height="7" rx="1.5" />
        <rect x="14" y="3" width="7" height="7" rx="1.5" />
        <rect x="3" y="14" width="7" height="7" rx="1.5" />
        <rect x="14" y="14" width="7" height="7" rx="1.5" />
    </svg>
);

function Widget1({
    id = 'widget_',
    isPro = true,
    title = 'Widget Title',
    description = '',
    settings = false,
    toggle = true,
    onChange = () => {},
    defaultValue = false,
    active = false,
    icon = null
}){
    const [ isOpen, setOpen ] = useState( false );
    const openModal = () => setOpen( true );
    const closeModal = () => setOpen( false );

    const checkIsProEnable = (e) => {
        if(!active){
            e.preventDefault();
            openModal();
        }
    }

    const handleChange = (e) => {
        if(!active){
            e.preventDefault();
            openModal();
        }else{
            onChange(e);
        }
    }
    return (
        <>
        { isOpen && (
            <Modal onRequestClose={ closeModal } title='Need Pro?'>
                <div className="pure-pro-modal-wrapper">
                    <div className="pure-pro-modal-header">
                        <Icon icon={info} size={100} fill='coral'/>
                        <h2>Upgrade to Pro</h2>
                    </div>
                    <div className="pure-pro-modal-content">
                        <p>Upgrade to Pro to unlock this feature.</p>
                        <Button isPrimary href='https://storebuild.shop/pricing/' target='_blank' style={{ backgroundColor: '#5e2eff' }}>
                            Upgrade to Pro
                        </Button>
                    </div>
                </div>
            </Modal>
        ) }
        <div className={"strb-widget-setting-item strb-widget-setting-item-2 strb-d-flex strb-justify-content-between strb-align-items-center strb-flex-wrap" + (isPro ? ' has-pro' : '')} onClick={checkIsProEnable}>
            {isPro && <div className="strb-widget-setting-badge">
                <span>Pro</span>
            </div>}
            <span className="strb-w-ico">{(MODULE_META[title]?.icon ? <Glyph name={MODULE_META[title].icon} /> : icon) || <WIcon/>}</span>
            <div className="strb-widget-setting-content">
                <h3 className="strb-widget-setting-title">{ title }</h3>
                {(MODULE_META[title]?.desc || description) && <span className="strb-widget-desc">{MODULE_META[title]?.desc || description}</span>}
            </div>
            <div className="strb-widget-setting-action">
                {settings && <div className="strb-widget-setting-offcanvas">
                    <button type="button" className="strb-offcanvas-open-btn" onClick={handleChange}>
                    <span>
                        <svg width={18} height={17} viewBox="0 0 18 17" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path opacity="0.76" d="M8.99743 11.2132C10.3223 11.2132 11.3962 10.1104 11.3962 8.74998C11.3962 7.38959 10.3223 6.28677 8.99743 6.28677C7.67261 6.28677 6.59863 7.38959 6.59863 8.74998C6.59863 10.1104 7.67261 11.2132 8.99743 11.2132Z" stroke="currentColor" strokeMiterlimit={10} strokeLinecap="round" strokeLinejoin="round" />
                        <path d="M1 9.47254V8.02746C1 7.17355 1.67966 6.46743 2.51924 6.46743C3.96652 6.46743 4.55822 5.41646 3.83058 4.12738C3.41479 3.38841 3.66267 2.42776 4.3903 2.1008L5.77361 1.18794C6.4053 0.802041 7.22089 1.03194 7.5967 1.68059L7.68466 1.83659C8.4043 3.12567 9.58771 3.12567 10.3153 1.83659L10.4033 1.68059C10.7791 1.03194 11.5947 0.802041 12.2264 1.18794L13.6097 2.1008C14.3373 2.42776 14.5852 3.38841 14.1694 4.12738C13.4418 5.41646 14.0335 6.46743 15.4808 6.46743C16.3123 6.46743 17 7.16533 17 8.02746V9.47254C17 10.3265 16.3203 11.0326 15.4808 11.0326C14.0335 11.0326 13.4418 12.1835 14.1694 13.3726C14.5852 14.1198 14.3373 15.0722 13.6097 15.4992L12.2264 16.3121C11.5947 16.698 10.7791 16.4681 10.4033 15.8194L10.3153 15.6634C9.5957 14.3743 8.41229 14.3743 7.68466 15.6634L7.5967 15.8194C7.22089 16.4681 6.4053 16.698 5.77361 16.3121L4.3903 15.4992C3.66267 15.0722 3.41479 14.1116 3.83058 13.3726C4.55822 12.1835 3.96652 11.0326 2.51924 11.0326C1.67966 11.0326 1 10.3265 1 9.47254Z" stroke="currentColor" strokeMiterlimit={10} strokeLinecap="round" strokeLinejoin="round" />
                        </svg>
                    </span>
                    </button>
                </div>}
                {toggle && <label className="strb-widget-setting-switch" htmlFor={id} onClick={checkIsProEnable}>
                    { defaultValue && <input 
                                    type="checkbox" 
                                    id={id} 
                                    onChange={handleChange} 
                                    checked 
                                    name={id} 
                                    disabled={active? false:true}/>
                    }
                    { !defaultValue && <input 
                                    type="checkbox" 
                                    id={id} 
                                    onChange={handleChange} 
                                    name={id} 
                                    disabled={active? false:true}/>
                    }
                    <span/>
                </label>}
            </div>
        </div>
        </>
    )
}

function Widget2({
    id = 'widget_',
    isPro = true,
    title = 'Widget Title',
    style = 1,
    onChange = () => {},
    defaultValue = false,
    active = false,
    icon = null
}){
    const [ isOpen, setOpen ] = useState( false );
    const openModal = () => setOpen( true );
    const closeModal = () => setOpen( false );

    const checkIsProEnable = (e) => {
        if(!active && isPro){
            e.preventDefault();
            openModal();
        }
    }
    const handleChange = (e) => {
        if(!active && isPro){
            e.preventDefault();
            openModal();
        }else{
            onChange(e);
        }
    }
    return (
        <>
        { isOpen && (
            <Modal onRequestClose={ closeModal } title='Need Pro?'>
                <div className="pure-pro-modal-wrapper">
                    <div className="pure-pro-modal-header">
                        <Icon icon={info} size={100} fill='coral'/>
                        <h2>Upgrade to Pro</h2>
                    </div>
                    <div className="pure-pro-modal-content">
                        <p>Upgrade to Pro to unlock this feature.</p>
                        <Button 
                        isPrimary 
                        href='https://storebuild.shop/pricing/' 
                        target='_blank'
                        className='strb-btn-fill'
                        >
                            Upgrade to Pro
                        </Button>
                    </div>
                </div>
            </Modal>
        ) }
        <div className={"strb-widget-setting-item strb-d-flex strb-justify-content-between strb-align-items-center strb-flex-wrap" + (isPro ? ' has-pro' : '')} onClick={checkIsProEnable}>
            {isPro && <div className="strb-widget-setting-badge">
                <span>Pro</span>
            </div>}
            <span className="strb-w-ico">{(WIDGET_META[title]?.icon ? <Glyph name={WIDGET_META[title].icon} /> : icon) || <WIcon/>}</span>
            <div className="strb-widget-setting-content">
                <h3 className="strb-widget-setting-title">{title}</h3>
                {WIDGET_META[title]?.desc && <span className="strb-widget-desc">{WIDGET_META[title].desc}</span>}
            </div>
            <div className="strb-widget-setting-action">
                <label className="strb-widget-setting-switch" htmlFor={id} onClick={checkIsProEnable}>
                    { defaultValue && <input 
                                    type="checkbox" 
                                    id={id} 
                                    onChange={handleChange} 
                                    checked 
                                    name={id} 
                                    disabled={(isPro && !active)? true:false}/>
                    }
                    { !defaultValue && <input 
                                    type="checkbox" 
                                    id={id} 
                                    onChange={handleChange} 
                                    name={id} 
                                    disabled={(isPro && !active)? true:false}/>
                    }
                    <span/>
                </label>
            </div>
        </div>
        </>
    )
}

function Widget({
    id = 'widget_',
    onChange= () => {},
    widget = 1,
    isPro = true,
    title = 'Widget Title',
    description = '',
    settings = false,
    toggle = true,
    style = 1,
    defaultValue = false,
    active = false,
    icon = null
}) {
  return (
    <>
        {   widget === 1?
            <Widget1
                id={id}
                isPro={isPro}
                title={title}
                description={description}
                settings={settings}
                toggle={toggle}
                onChange={onChange}
                defaultValue={defaultValue}
                active={active}
                icon={icon}
            /> :
            <Widget2
                id={id}
                isPro={isPro}
                title={title}
                style={style}
                onChange={onChange}
                defaultValue={defaultValue}
                active={active}
                icon={icon}
            />
        }
    </>
  )
}

export default Widget