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

/* ── 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 = {
    layout:   ico('<rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/>'),
    brand:    ico('<path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/>'),
    enable:   ico('<circle cx="12" cy="12" r="9"/><path d="m9 12 2 2 4-4"/>'),
    elementor:ico('<path d="M12 2L2 7l10 5 10-5-10-5z"/><path d="M2 17l10 5 10-5"/><path d="M2 12l10 5 10-5"/>'),
};

/* ── Template preview SVGs ─────────────────────────────────────────────── */
const TPL_PREVIEWS = {
    default: (
        <svg viewBox="0 0 120 90" xmlns="http://www.w3.org/2000/svg">
            {/* gradient header */}
            <defs>
                <linearGradient id="g1" x1="0%" y1="0%" x2="100%" y2="0%">
                    <stop offset="0%" stopColor="#4f46e5"/>
                    <stop offset="100%" stopColor="#7c3aed"/>
                </linearGradient>
            </defs>
            <rect x="0" y="0" width="120" height="22" rx="4" fill="url(#g1)"/>
            <rect x="8" y="7" width="22" height="7" rx="2" fill="rgba(255,255,255,.6)"/>
            <rect x="75" y="4" width="36" height="7" rx="1" fill="rgba(255,255,255,.9)"/>
            <rect x="83" y="13" width="28" height="2.5" rx="1" fill="rgba(255,255,255,.55)"/>
            {/* billing */}
            <rect x="8" y="28" width="18" height="2" rx="1" fill="#94a3b8"/>
            <rect x="8" y="33" width="40" height="2.5" rx="1" fill="#0f172a"/>
            <rect x="8" y="38" width="32" height="2" rx="1" fill="#cbd5e1"/>
            <rect x="8" y="43" width="28" height="2" rx="1" fill="#cbd5e1"/>
            {/* table header */}
            <rect x="8" y="52" width="104" height="8" rx="2" fill="#0f172a"/>
            <rect x="12" y="55" width="22" height="2" rx="1" fill="rgba(255,255,255,.65)"/>
            <rect x="68" y="55" width="12" height="2" rx="1" fill="rgba(255,255,255,.65)"/>
            <rect x="92" y="55" width="16" height="2" rx="1" fill="rgba(255,255,255,.65)"/>
            {/* rows */}
            <rect x="8" y="61" width="104" height="6" rx="0" fill="#f8fafc"/>
            <rect x="12" y="63.5" width="28" height="2" rx="1" fill="#cbd5e1"/>
            <rect x="92" y="63.5" width="16" height="2" rx="1" fill="#4f46e5"/>
            {/* total */}
            <rect x="68" y="72" width="44" height="14" rx="3" fill="none" stroke="#4f46e5" strokeWidth="1.5"/>
            <rect x="72" y="76" width="16" height="2" rx="1" fill="#94a3b8"/>
            <rect x="72" y="80" width="28" height="4" rx="1" fill="#4f46e5"/>
        </svg>
    ),
    template2: (
        <svg viewBox="0 0 120 90" xmlns="http://www.w3.org/2000/svg">
            {/* big INV text */}
            <rect x="62" y="4" width="50" height="14" rx="2" fill="#ebebeb"/>
            {/* logo */}
            <rect x="8" y="7" width="20" height="6" rx="1" fill="#111"/>
            {/* bold border */}
            <rect x="8" y="22" width="104" height="2.5" fill="#111"/>
            {/* billing */}
            <rect x="8" y="30" width="14" height="1.5" rx="1" fill="#aaa"/>
            <rect x="8" y="35" width="44" height="2.5" rx="1" fill="#111"/>
            <rect x="8" y="40" width="36" height="2" rx="1" fill="#aaa"/>
            <rect x="8" y="45" width="30" height="2" rx="1" fill="#aaa"/>
            {/* table lines only */}
            <rect x="8" y="54" width="104" height="2" fill="#111"/>
            <rect x="12" y="59" width="24" height="1.5" rx="1" fill="#aaa"/>
            <rect x="90" y="59" width="18" height="1.5" rx="1" fill="#aaa"/>
            <rect x="8" y="64" width="104" height="1" fill="#ebebeb"/>
            <rect x="12" y="68" width="32" height="1.5" rx="1" fill="#ccc"/>
            <rect x="90" y="68" width="18" height="1.5" rx="1" fill="#111"/>
            {/* total border */}
            <rect x="8" y="76" width="104" height="2.5" fill="#111"/>
            <rect x="82" y="80" width="26" height="6" rx="1" fill="#111"/>
        </svg>
    ),
    template3: (
        <svg viewBox="0 0 120 90" xmlns="http://www.w3.org/2000/svg">
            {/* dark sidebar */}
            <rect x="0" y="0" width="34" height="90" rx="4" fill="#0f172a"/>
            {/* logo in sidebar */}
            <rect x="6" y="10" width="22" height="6" rx="1" fill="rgba(255,255,255,.55)"/>
            {/* sidebar labels */}
            <rect x="6" y="24" width="12" height="1.5" rx="1" fill="#475569"/>
            <rect x="6" y="28" width="22" height="2.5" rx="1" fill="#e2e8f0"/>
            <rect x="6" y="33" width="18" height="2" rx="1" fill="#94a3b8"/>
            <rect x="6" y="38" width="20" height="2" rx="1" fill="#94a3b8"/>
            <rect x="6" y="43" width="14" height="2" rx="1" fill="#94a3b8"/>
            <rect x="6" y="52" width="12" height="1.5" rx="1" fill="#475569"/>
            <rect x="6" y="56" width="20" height="2" rx="1" fill="#94a3b8"/>
            <rect x="6" y="61" width="18" height="2" rx="1" fill="#94a3b8"/>
            {/* INVOICE title */}
            <rect x="42" y="8" width="46" height="8" rx="2" fill="#0f172a"/>
            <rect x="42" y="18" width="28" height="2" rx="1" fill="#94a3b8"/>
            {/* divider */}
            <rect x="42" y="24" width="72" height="1.5" fill="#f1f5f9"/>
            {/* table header */}
            <rect x="42" y="28" width="72" height="7" rx="1" fill="#0f172a"/>
            <rect x="46" y="30.5" width="18" height="2" rx="1" fill="rgba(255,255,255,.6)"/>
            <rect x="98" y="30.5" width="12" height="2" rx="1" fill="rgba(255,255,255,.6)"/>
            {/* rows */}
            <rect x="46" y="39" width="24" height="2" rx="1" fill="#cbd5e1"/>
            <rect x="98" y="39" width="12" height="2" rx="1" fill="#0ea5e9"/>
            <rect x="42" y="44" width="72" height="1" fill="#f1f5f9"/>
            <rect x="46" y="48" width="28" height="2" rx="1" fill="#cbd5e1"/>
            <rect x="98" y="48" width="12" height="2" rx="1" fill="#0ea5e9"/>
            {/* total box */}
            <rect x="42" y="57" width="72" height="16" rx="3" fill="#0f172a"/>
            <rect x="46" y="63" width="18" height="2" rx="1" fill="#64748b"/>
            <rect x="86" y="61" width="24" height="6" rx="1" fill="#0ea5e9"/>
        </svg>
    ),
};

const TEMPLATES = [
    { id: 'default',   name: __('Clean Pro', 'shopbuild') },
    { id: 'template2', name: __('Minimal', 'shopbuild') },
    { id: 'template3', name: __('Bold Dark', 'shopbuild') },
];

export default function Invoice({ video, id, docs }) {
    const [invoice, setInvoice] = useState(false);
    const [settings, setSettings] = useState({
        invoice_selected_template: 'default',
        ...storebuild.settings._storebuild_invoice_settings,
    });
    const templates   = storebuild.invoice_templates;
    const hasPro      = Boolean(storebuild?.is_pro_active);

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

    const set = (key, val) => setSettings(prev => ({ ...prev, [key]: val }));

    return (
        <>
            <Widget
                title='Invoice'
                description='See your invoices and download from order page.'
                toggle={false}
                settings={true}
                onChange={() => setInvoice(v => !v)}
                isPro={false}
                active={true}
            />
            <Offcanvas
                open={invoice}
                onClose={() => setInvoice(v => !v)}
                heading='Invoice Settings'
                subtitle='Automatically generate and attach downloadable PDF invoices to every customer order.'
                onSave={saveSettings}
                video={video}
                id={id}
                docs={docs}
            >
                {/* Enable / Disable */}
                <div className="strb-offcanvas-option">
                    <Switch
                        id='storebuild_enable_invoice_module'
                        title='Enable / Disable'
                        text='Activate or deactivate the invoice system.'
                        icon={I.enable}
                        defaultValue={settings.enable}
                        onChange={() => set('enable', !settings.enable)}
                    />
                </div>

                {/* Template picker — only when not using Elementor */}
                {!settings.invoice_template_enable && (
                    <div className="strb-offcanvas-option strb-cs-card">
                        <div className="strb-cs-section-head">
                            <span className="strb-cs-section-ic">{I.layout}</span>
                            <div>
                                <h4>{__('Template Style', 'shopbuild')}</h4>
                                <p>{__('Choose a design for your invoice PDF.', 'shopbuild')}</p>
                            </div>
                        </div>
                        <div className="strb-inv-tpl-grid">
                            {TEMPLATES.map(tpl => (
                                <button
                                    key={tpl.id}
                                    type="button"
                                    className={`strb-inv-tpl-card${settings.invoice_selected_template === tpl.id ? ' is-active' : ''}`}
                                    onClick={() => set('invoice_selected_template', tpl.id)}
                                >
                                    {TPL_PREVIEWS[tpl.id]}
                                    <span className="strb-inv-tpl-name">{tpl.name}</span>
                                </button>
                            ))}
                        </div>
                    </div>
                )}

                {/* Business info — only when not using Elementor */}
                {!settings.invoice_template_enable && (
                    <div className="strb-offcanvas-option strb-cs-card">
                        <div className="strb-cs-section-head">
                            <span className="strb-cs-section-ic">{I.brand}</span>
                            <div>
                                <h4>{__('Business Info', 'shopbuild')}</h4>
                                <p>{__('Your details shown on every invoice.', 'shopbuild')}</p>
                            </div>
                        </div>

                        {/* Logo */}
                        <div style={{ padding: '0 22px 16px' }}>
                            <MediaUploader
                                handleChange={(a) => set('invoice_logo', { url: a.url, alt: a.alt })}
                                value={settings.invoice_logo?.url}
                            />
                        </div>

                        <div className="strb-inv-fields">
                            <div className="strb-inv-field">
                                <label>{__('Address', 'shopbuild')}</label>
                                <input
                                    type="text"
                                    value={settings.invoice_address}
                                    placeholder="123 Main St, City"
                                    onChange={(e) => set('invoice_address', e.target.value)}
                                />
                            </div>
                            <div className="strb-inv-field">
                                <label>{__('Phone', 'shopbuild')}</label>
                                <input
                                    type="text"
                                    value={settings.invoice_phone}
                                    placeholder="+1 234 567 890"
                                    onChange={(e) => set('invoice_phone', e.target.value)}
                                />
                            </div>
                            <div className="strb-inv-field strb-inv-field--full">
                                <label>{__('Email', 'shopbuild')}</label>
                                <input
                                    type="email"
                                    value={settings.invoice_email}
                                    placeholder="hello@yourstore.com"
                                    onChange={(e) => set('invoice_email', e.target.value)}
                                />
                            </div>
                            <div className="strb-inv-field strb-inv-field--full">
                                <label>{__('Footer Note', 'shopbuild')}</label>
                                <input
                                    type="text"
                                    value={settings.invoice_footer_note}
                                    placeholder="Thank you for shopping with us."
                                    onChange={(e) => set('invoice_footer_note', e.target.value)}
                                />
                            </div>
                            <div className="strb-inv-field strb-inv-field--full">
                                <label>{__('Terms & Conditions', 'shopbuild')}</label>
                                <textarea
                                    value={settings.invoice_terms}
                                    placeholder="Write your terms and conditions here..."
                                    onChange={(e) => set('invoice_terms', e.target.value)}
                                />
                            </div>
                        </div>
                    </div>
                )}

                {/* Elementor custom template (Pro) */}
                <div className="strb-offcanvas-option strb-cs-card">
                    <div className="strb-cs-section-head">
                        <span className="strb-cs-section-ic">{I.elementor}</span>
                        <div>
                            <h4>{__('Elementor Template', 'shopbuild')}</h4>
                            <p>{__('Use a custom Elementor-built invoice layout.', 'shopbuild')}</p>
                        </div>
                    </div>
                    <div style={{ padding: '0 22px 16px' }}>
                        <Switch
                            id='storebuild_enable_invoice_template'
                            title='Use Elementor Template'
                            text='Overrides the built-in template above.'
                            defaultValue={settings.invoice_template_enable}
                            onChange={() => set('invoice_template_enable', !settings.invoice_template_enable)}
                        />
                        {(settings.invoice_template_enable && hasPro) && (
                            <Dropdown
                                id='storebuild_invoice_template'
                                title='Choose Template'
                                text='Select an Elementor template to use.'
                                data={templates}
                                selected={settings.invoice_template}
                                onChange={(e) => set('invoice_template', e.target.value)}
                            />
                        )}
                    </div>
                </div>

            </Offcanvas>
        </>
    );
}
