import { useEffect, useState } from '@wordpress/element';
import SettingsLayout from '../layout/SettingsLayout';
import { fetchOptions, saveOptions } from '../../api/settings';
import { exportSettings, importSettings } from '../../api/local';
import { showPromiseToast, showToast } from '../../utils';

const UserTools = () => {
    const [options, setOptions] = useState({});
    const [importing, setImporting] = useState(false);

    useEffect(() => {
        const updateOptions = (settings) => setOptions((prev) => ({ ...prev, ...settings }));
        const res = fetchOptions({ updateOptions });
        showPromiseToast(res, 'Loading settings');
    }, []);

    const updateOption = (value, key) => {
        setOptions({ ...options, [key]: value });
    };

    const handleGenerateSecret = () => {
        let newKey = '';
        if (window.crypto?.getRandomValues) {
            const array = new Uint32Array(16);
            window.crypto.getRandomValues(array);
            newKey = Array.from(array, (val) => val.toString(16).padStart(8, '0')).join('');
        } else {
            newKey = Array.from({ length: 64 }, () => Math.floor(Math.random() * 16).toString(16)).join('');
        }
        updateOption(newKey, 'secret_key');

        const res = saveOptions({ options: { secret_key: newKey } });
        showPromiseToast(res, 'Updating secret key', 'New secret saved');
    };

    const handleExportSettings = () => {
        const res = exportSettings().then((data) => {
            const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
            const url = URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = url;
            link.download = 'headlesskey-settings.json';
            link.click();
        });
        showPromiseToast(res, 'Preparing export');
    };

    const handleImportSettings = (event) => {
        const file = event.target.files?.[0];
        if (!file) {
            return;
        }

        setImporting(true);
        const reader = new FileReader();
        reader.onload = () => {
            try {
                const parsed = JSON.parse(reader.result);
                const res = importSettings(parsed.settings || parsed).then(() => {
                    showToast('Settings imported', 'success');
                    setOptions({ ...options, ...(parsed.settings || parsed) });
                }).finally(() => setImporting(false));
                showPromiseToast(res, 'Importing settings');
            } catch (error) {
                showToast('Invalid settings file', 'error');
                setImporting(false);
            }
        };
        reader.readAsText(file);
    };

    return (
        <SettingsLayout>
            <div className="bg-white rounded p-6 space-y-6">
                <div className="flex flex-col gap-1">
                    <h2 className="text-2xl font-bold text-gray-900">Developer Tools</h2>
                    <p className="text-gray-600 text-sm">Manage secrets, migrate settings, and reset plugin data.</p>
                </div>

                <div className="border border-gray-200 rounded-md p-5">
                    <h3 className="text-lg font-semibold text-gray-900">Secret Key</h3>
                    <p className="text-sm text-gray-600">Store in <code>wp-config.php</code> as <code>headlesskey_SECRET_KEY</code>. This UI value is used only if the constant is unavailable.</p>
                    <div className="mt-4 flex flex-col gap-2">
                        <code className="bg-gray-100 rounded px-3 py-2 break-all">{options.secret_key || 'Not set yet'}</code>
                        <div className="flex gap-2">
                            <button
                                type="button"
                                className="rounded-md bg-gray-800 px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-gray-900"
                                onClick={handleGenerateSecret}
                            >
                                Generate Secret
                            </button>
                        </div>
                    </div>
                </div>

                <div className="border border-gray-200 rounded-md p-5 space-y-4">
                    <h3 className="text-lg font-semibold text-gray-900">Export & Import</h3>
                    <div className="flex flex-wrap gap-3">
                        <button
                            type="button"
                            className="rounded-md bg-gray-100 px-3 py-2 text-sm font-semibold text-gray-800 shadow-sm hover:bg-gray-200"
                            onClick={handleExportSettings}
                        >
                            Export Settings (JSON)
                        </button>
                        <label className="rounded-md bg-gray-100 px-3 py-2 text-sm font-semibold text-gray-800 shadow-sm hover:bg-gray-200 cursor-pointer">
                            Import JSON
                            <input
                                type="file"
                                accept="application/json"
                                className="hidden"
                                onChange={handleImportSettings}
                                disabled={importing}
                            />
                        </label>
                    </div>
                </div>
            </div>
        </SettingsLayout>
    );
};

export default UserTools;

