import Widget from "../widgets/Widget"
import { Offcanvas, Dropdown, Input, Switch } from "../offcanvas"
import { useState, useEffect } from "@wordpress/element"
import { toast } from 'react-toastify'
import axios from 'axios'
import { Notice } from "@wordpress/components"
import { RawHTML } from "@wordpress/element"
import { __ } from '@wordpress/i18n'

/* Concept-theme row icons */
const ico = (paths) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" dangerouslySetInnerHTML={{ __html: paths }} />
);
const I = {
    bell: ico('<path d="M18 9a6 6 0 1 0-12 0c0 7-3 8-3 8h18s-3-1-3-8"/><path d="M10.5 21a2 2 0 0 0 3 0"/>'),
    pin: ico('<path d="M20 10c0 6-8 12-8 12s-8-6-8-12a8 8 0 0 1 16 0Z"/><circle cx="12" cy="10" r="3"/>'),
    tag: ico('<path d="M20.59 13.41l-7.17 7.17a2 2 0 0 1-2.83 0L2 12V2h10l8.59 8.59a2 2 0 0 1 0 2.82z"/><circle cx="7" cy="7" r="1.2"/>'),
    bag: ico('<path d="M6 2 4 6v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V6l-2-4Z"/><path d="M4 6h16M9 10a3 3 0 0 0 6 0"/>'),
    clock: ico('<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>'),
    timer: ico('<circle cx="12" cy="13" r="8"/><path d="M12 13V9.5M9 2h6"/>'),
    user: ico('<circle cx="12" cy="8" r="4"/><path d="M4 21a8 8 0 0 1 16 0"/>'),
    info: ico('<circle cx="12" cy="12" r="9"/><path d="M12 11v5M12 8h.01"/>'),
};

export default function SaleNotiFication({ video, id, docs }) {

    const hasPro = Boolean(storebuild?.is_pro_active);
    const proNoticeProduct = __('Use <a target="_blank" href="https://storebuild.shop/pricing/">StoreBuild Pro</a> To add more products in notification.', 'shopbuild');

    const [saleNotification, setSaleNotification] = useState(false)
    const [productListErr, setProductListErr] = useState(false);
    const [isManual, setIsManualProducts] = useState(storebuild.settings._storebuild_sale_notification.storebuild_real_or_manual)
    const [saleNotificationSettings, setSaleNotificationSettings] = useState(storebuild.settings._storebuild_sale_notification)
    const [manualProductsLists, setManualProductsList] = useState(storebuild.settings._storebuild_sale_notification.storebuild_manual_products)
    const [enableSaleNotification, setEnableSaleNotification] = useState(storebuild.settings._storebuild_sale_notification.storebuild_enable_sale_notification)

    const handleSaveNotificationSettings = (e) => {
        e.preventDefault()
        const form_data = new FormData()
        form_data.append('action', 'storebuild_save')
        form_data.append('security', storebuild.nonce)
        form_data.append('_storebuild_sale_notification', JSON.stringify(saleNotificationSettings))
        axios.post(storebuild.ajax_url, form_data)
            .then(res => {
                toast.success(res.data?.data?.message)
            })
            .catch(err => {
                console.log(err)
                toast.error(res.data?.data?.message)
            })
    }

    /**
    * 
    * @param notification setttings 
    */
    const handleNotificationChange = (e) => {
        e.preventDefault()
        if (e.target.value === 'manual') {
            setIsManualProducts('manual')
        } else {
            setIsManualProducts('real')
        }
        setSaleNotificationSettings({ ...saleNotificationSettings, [e.target.name]: e.target.value })
    }

    useEffect(() => {
        setSaleNotificationSettings({ ...saleNotificationSettings, ['storebuild_enable_sale_notification']: enableSaleNotification })
    }, [enableSaleNotification])

    const handleManualProductsChange = (val) => {
        const newProductsList = val.length ? manualProductsLists.filter(product => product.value != val.value) : val;
        if (val.length >= 2 && !hasPro) {
            setProductListErr(true);
            return;
        } else {
            setManualProductsList(prev => [...prev, ...val])
            setSaleNotificationSettings({ ...saleNotificationSettings, ['storebuild_manual_products']: val })
        }
    }

    return (
        <>
            <Widget
                title='Sale Notification'
                description='Your order notification to view your custom for better selling.'
                toggle={false}
                settings={true}
                onChange={() => setSaleNotification(saleNotification => !saleNotification)}
                isPro={false}
                active={true}
            />
            <Offcanvas
                open={saleNotification}
                onClose={() => setSaleNotification(saleNotification => !saleNotification)}
                heading='Sale Notification'
                badge={__('for E-commerce', 'shopbuild')}
                subtitle={__('Show real-time or fake sales popups on your shop page to build trust and boost sales.', 'shopbuild')}
                onSave={handleSaveNotificationSettings}
                video={video}
                id={id}
                docs={docs}
            >
                <div className="strb-offcanvas-option">
                    <Switch
                        id='storebuild_enable_sale_notification'
                        title='Enable Sale Notification'
                        text='Show or hide sale notifications on the shop page.'
                        icon={I.bell}
                        defaultValue={enableSaleNotification}
                        onChange={() => setEnableSaleNotification(enableSaleNotification => !enableSaleNotification)}
                    />
                    <Dropdown
                        id={'storebuild_notification_position'}
                        title='Notification Position'
                        text='Choose where the notification will appear on the screen.'
                        icon={I.pin}
                        data={[
                            { value: 'bottom_left', label: 'Bottom Left' },
                            { value: 'bottom_right', label: 'Bottom Right' },
                            { value: 'top_right', label: 'Top Right' },
                            { value: 'top_left', label: 'Top Left' },
                        ]}
                        selected={saleNotificationSettings.storebuild_notification_position}
                        onChange={handleNotificationChange}
                    />
                    <Dropdown
                        id='storebuild_real_or_manual'
                        title='Notification Type'
                        text='Choose between real customer activity or fake (random) notifications.'
                        icon={I.tag}
                        data={[
                            { value: 'real', label: 'Real' },
                            { value: 'manual', label: 'Manual' }
                        ]}
                        selected={saleNotificationSettings.storebuild_real_or_manual}
                        onChange={handleNotificationChange}
                    />
                    {(isManual != 'manual') && <div className="strb-oc-notice">
                        <span className="strb-oc-notice-ic">{I.info}</span>
                        <span>{__('Real notifications use actual recent orders from your store.', 'shopbuild')}</span>
                    </div>}

                    {(isManual == 'manual') && <div class="strb-offcanvas-section-title">
                        <h3>Notification products</h3>
                    </div>}
                    {(isManual == 'manual') && <Dropdown
                        id='storebuild_manual_products'
                        title='Products Lists'
                        text='Choose multiple products for notification.'
                        icon={I.bag}
                        data={storebuild.storebuild_products}
                        selected={manualProductsLists}
                        isMulti={true}
                        onChange={handleManualProductsChange}
                        isOptionDisabled={() => productListErr}
                    />}
                    {productListErr && <Notice status="warning" isDismissible={false}>
                        <RawHTML>{proNoticeProduct}</RawHTML>
                    </Notice>}
                    {(isManual == 'manual') && <div class="strb-offcanvas-section-title">
                        <h3>Fake buyer info</h3>
                    </div>}
                    {(isManual == 'manual') && <Input
                        id='storebuild_fname_of_buyer'
                        title='Name of a buyer'
                        text='Salim Rana'
                        defaultValue={saleNotificationSettings.storebuild_fname_of_buyer}
                        type='text'
                        onChange={handleNotificationChange}
                    />}
                    {(isManual == 'manual') && <Input
                        id='storebuild_lname_of_buyer'
                        title='Name of a buyer'
                        text='Salim Rana'
                        defaultValue={saleNotificationSettings.storebuild_lname_of_buyer}
                        type='text'
                        onChange={handleNotificationChange}
                    />}
                    {(isManual == 'manual') && <Input
                        id='storebuild_city_of_buyer'
                        title='City'
                        text='Mirpur'
                        defaultValue={saleNotificationSettings.storebuild_city_of_buyer}
                        type='text'
                        onChange={handleNotificationChange}
                    />}
                    {(isManual == 'manual') && <Input
                        id='storebuild_state_of_buyer'
                        title='State'
                        text='Dhaka'
                        defaultValue={saleNotificationSettings.storebuild_state_of_buyer}
                        type='text'
                        onChange={handleNotificationChange}
                    />}
                    {(isManual == 'manual') && <Input
                        id='storebuild_country_of_buyer'
                        title='Country'
                        text='Bangladesh'
                        defaultValue={saleNotificationSettings.storebuild_country_of_buyer}
                        type='text'
                        onChange={handleNotificationChange}
                    />}
                </div>
                <div className="strb-offcanvas-option">
                    <Input
                        id='storebuild_number_of_products'
                        title='Products Limit'
                        text='Set the maximum number of products to show in the notification.'
                        icon={I.bag}
                        hint='Recommended: 3–10 products'
                        defaultValue={saleNotificationSettings.storebuild_number_of_products}
                        type='number'
                        min={1}
                        onChange={handleNotificationChange}
                    />
                    <Dropdown
                        id='storebuild_how_old_product'
                        title='How Old Product?'
                        text='Choose how recent the orders should be for real notifications.'
                        icon={I.clock}
                        hint="Orders older than this won't be used."
                        data={[
                            { value: '1 day', label: '1 Day' },
                            { value: '3 days', label: '3 Days' },
                            { value: '5 days', label: '5 Days' },
                            { value: '1 week', label: '1 Week' },
                            { value: '2 week', label: '2 Weeks' },
                            { value: '1 month', label: '1 Month' },
                        ]}
                        selected={saleNotificationSettings.storebuild_how_old_product}
                        onChange={handleNotificationChange}
                    />
                    <Input
                        id='storebuild_first_load_time'
                        title='First Loading Time'
                        text='Delay before the first notification appears on page load.'
                        icon={I.timer}
                        hint='Time in seconds'
                        defaultValue={saleNotificationSettings.storebuild_first_load_time}
                        type='number'
                        onChange={handleNotificationChange}
                    />
                    <Input
                        id='storebuild_notification_showtime'
                        title='Notification Duration'
                        text='How long each notification stays visible.'
                        icon={I.timer}
                        hint='Time in seconds'
                        defaultValue={saleNotificationSettings.storebuild_notification_showtime}
                        type='number'
                        onChange={handleNotificationChange}
                    />
                    <Input
                        id='storebuild_notification_interval'
                        title='Notification Interval'
                        text='Gap between one notification and the next.'
                        icon={I.timer}
                        hint='Time in seconds'
                        defaultValue={saleNotificationSettings.storebuild_notification_interval}
                        type='number'
                        onChange={handleNotificationChange}
                    />
                </div>
            </Offcanvas>
        </>
    )
}