import { useState, useEffect } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import axios from 'axios';
import { toast } from 'react-toastify';

const ImportIcon = () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" /><path d="M7 10l5 5 5-5" /><path d="M12 15V3" />
    </svg>
);

const DownloadIcon = () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <path d="M14 3v4a1 1 0 0 0 1 1h4" /><path d="M17 21H7a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7l5 5v11a2 2 0 0 1-2 2Z" /><path d="M12 11v6" /><path d="m9 14 3 3 3-3" />
    </svg>
);

const WarnIcon = () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0Z" /><path d="M12 9v4M12 17h.01" />
    </svg>
);

const EMPTY_RESULTS = { imported: 0, updated: 0, skipped: 0, failed: 0 };

const ImportExport = () => {
    const wooActive = Boolean(storebuild.is_woo_active);
    const downloadUrl = storebuild.sample_data_url;

    const [info, setInfo] = useState(null);
    const [updateExisting, setUpdateExisting] = useState(false);
    const [importing, setImporting] = useState(false);
    const [percent, setPercent] = useState(0);
    const [results, setResults] = useState(EMPTY_RESULTS);
    const [done, setDone] = useState(false);

    // Pull info about the bundled CSV (product count + availability).
    useEffect(() => {
        if (!wooActive) return;
        const form = new FormData();
        form.append('action', 'storebuild_sample_data_info');
        form.append('security', storebuild.import_nonce);
        axios.post(storebuild.ajax_url, form)
            .then(res => { if (res.data?.success) setInfo(res.data.data); })
            .catch(() => {});
    }, [wooActive]);

    // Run one batch and recurse until the server reports "done".
    const runBatch = (position, totals) => {
        const form = new FormData();
        form.append('action', 'storebuild_import_sample_data');
        form.append('security', storebuild.import_nonce);
        form.append('position', position);
        form.append('update_existing', updateExisting ? 1 : 0);

        return axios.post(storebuild.ajax_url, form).then(res => {
            if (!res.data?.success) {
                throw new Error(res.data?.data?.message || __('Import failed.', 'shopbuild'));
            }
            const d = res.data.data;
            const next = {
                imported: totals.imported + (d.imported || 0) + (d.imported_variations || 0),
                updated: totals.updated + (d.updated || 0),
                skipped: totals.skipped + (d.skipped || 0),
                failed: totals.failed + (d.failed || 0),
            };
            setResults(next);
            setPercent(d.percentage || 0);

            if (d.position === 'done') {
                return next;
            }
            return runBatch(d.position, next);
        });
    };

    const startImport = () => {
        if (!wooActive || importing) return;
        setImporting(true);
        setDone(false);
        setPercent(0);
        setResults(EMPTY_RESULTS);

        runBatch(0, EMPTY_RESULTS)
            .then(() => {
                setDone(true);
                toast.success(__('Sample products imported successfully.', 'shopbuild'));
            })
            .catch(err => {
                toast.error(err.message || __('Something went wrong while importing.', 'shopbuild'));
            })
            .finally(() => setImporting(false));
    };

    return (
        <div className="strb-fonts">
            {/* ── Header card ── */}
            <div className="strb-fonts-headcard">
                <div className="strb-fonts-headinfo">
                    <h2>{__('Import / Export', 'shopbuild')}</h2>
                    <p>{__('Populate your store with ready-made demo products, or grab the sample CSV to build your own.', 'shopbuild')}</p>
                </div>
            </div>

            {/* ── WooCommerce required notice ── */}
            {!wooActive && (
                <div className="strb-ie-note">
                    <span className="ic"><WarnIcon /></span>
                    <div>
                        <strong>{__('WooCommerce is required', 'shopbuild')}</strong>
                        <span>{__('Activate WooCommerce to import sample products. You can still download the sample CSV below.', 'shopbuild')}</span>
                    </div>
                </div>
            )}

            <div className="strb-ie-grid">
                {/* ── Import card ── */}
                <div className="strb-ie-card">
                    <div className="strb-ie-head">
                        <span className="strb-ie-ic"><ImportIcon /></span>
                        <div className="strb-ie-meta">
                            <h3>{__('Import Sample Products', 'shopbuild')}</h3>
                            <p>{__('Imports our demo catalog using the native WooCommerce product importer — categories, tags, images, attributes and variations included.', 'shopbuild')}</p>
                        </div>
                    </div>

                    {wooActive && info && (
                        <div className="strb-ie-rows">
                            <strong>{info.rows}</strong> {__('demo products in this dataset', 'shopbuild')}
                        </div>
                    )}

                    <label className="strb-ie-check">
                        <input
                            type="checkbox"
                            checked={updateExisting}
                            disabled={!wooActive || importing}
                            onChange={e => setUpdateExisting(e.target.checked)}
                        />
                        <span>{__('Update existing products (match by ID or SKU)', 'shopbuild')}</span>
                    </label>

                    {(importing || done) && (
                        <div className="strb-ie-progress-wrap">
                            <div className="strb-ie-progress">
                                <div className="strb-ie-progress-bar" style={{ width: `${percent}%` }} />
                            </div>
                            <span className="strb-ie-progress-label">
                                {done ? __('Completed', 'shopbuild') : __('Importing…', 'shopbuild')} {percent}%
                            </span>
                        </div>
                    )}

                    {(importing || done) && (
                        <div className="strb-ie-stats">
                            <div className="strb-ie-stat is-imported"><b>{results.imported}</b><span>{__('Imported', 'shopbuild')}</span></div>
                            <div className="strb-ie-stat is-updated"><b>{results.updated}</b><span>{__('Updated', 'shopbuild')}</span></div>
                            <div className="strb-ie-stat is-skipped"><b>{results.skipped}</b><span>{__('Skipped', 'shopbuild')}</span></div>
                            <div className="strb-ie-stat is-failed"><b>{results.failed}</b><span>{__('Failed', 'shopbuild')}</span></div>
                        </div>
                    )}

                    <div className="strb-ie-foot">
                        <button
                            type="button"
                            className="strb-btn-fill"
                            onClick={startImport}
                            disabled={!wooActive || importing}
                        >
                            <ImportIcon />
                            {importing ? __('Importing…', 'shopbuild') : (done ? __('Import Again', 'shopbuild') : __('Import Sample Products', 'shopbuild'))}
                        </button>
                    </div>
                </div>

                {/* ── Download card ── */}
                <div className="strb-ie-card">
                    <div className="strb-ie-head">
                        <span className="strb-ie-ic is-alt"><DownloadIcon /></span>
                        <div className="strb-ie-meta">
                            <h3>{__('Download Sample CSV', 'shopbuild')}</h3>
                            <p>{__('Get the example product file in standard WooCommerce CSV format. Use it as a starting template or import it manually via WooCommerce → Products → Import.', 'shopbuild')}</p>
                        </div>
                    </div>

                    <ul className="strb-ie-list">
                        <li>{__('WooCommerce-compatible column structure', 'shopbuild')}</li>
                        <li>{__('Simple & variable products with attributes', 'shopbuild')}</li>
                        <li>{__('Categories, tags, pricing & gallery images', 'shopbuild')}</li>
                    </ul>

                    <div className="strb-ie-foot">
                        <a className="strb-btn-ghost" href={downloadUrl} download target="_blank" rel="noreferrer">
                            <DownloadIcon />
                            {__('Download sample-data.csv', 'shopbuild')}
                        </a>
                    </div>
                </div>
            </div>
        </div>
    );
};

export default ImportExport;
