import React, { useEffect, useRef } from 'react';
import { useLocation } from 'react-router-dom';
import { useSettings } from '../contexts/SettingsContext.jsx';
import { useNotices } from '../contexts/NoticesContext.jsx';
import Modal from './Modal.jsx';
import SyncProgress from './SyncProgress.jsx';

const FloatingSaveBar = () => {
  const location = useLocation();
  const isSettingsPage = location.pathname === '/settings';
  const notices = useNotices();

  const {
    saveChangeCount,
    isLoading,
    isSyncing,
    syncProgress,
    syncMessage,
    saveChanges,
    showDiscardPopup,
    setShowDiscardPopup,
    discardChanges,
    showDisableBulkEditPopup,
    setShowDisableBulkEditPopup,
    updateOption,
  } = useSettings();

  // Report the sync result once it finishes (or a save fails) as a toast.
  const lastReported = useRef('');
  useEffect(() => {
    if (isSyncing || !syncMessage) {
      if (!syncMessage) lastReported.current = '';
      return;
    }
    if (lastReported.current === syncMessage) return;
    lastReported.current = syncMessage;
    const failed = /fail|error/i.test(syncMessage);
    if (failed) {
      notices.error(syncMessage);
    } else {
      notices.success(syncMessage);
    }
  }, [isSyncing, syncMessage, notices]);

  const keepBulkEdit = () => {
    updateOption('bulk_edit_option2', true);
    setShowDisableBulkEditPopup(false);
  };

  return (
    <>
      {isSyncing && <SyncProgress title="Syncing to Google Sheet" progress={syncProgress} message={syncMessage || 'Preparing...'} />}

      {/* Sticky Save Bar — Only visible on Settings tab */}
      {isSettingsPage && saveChangeCount > 0 && (
        <div className="ssgsw_button_container" role="region" aria-label="Unsaved changes">
          <button
            type="button"
            onClick={saveChanges}
            disabled={isLoading || isSyncing}
            aria-busy={isLoading || isSyncing}
            className="ssgsw_save_button"
          >
            {isLoading || isSyncing ? (
              <span className="osgsw-btn-busy">
                <span className="osgsw-spinner" aria-hidden="true" />
                {isLoading && !isSyncing ? 'Saving...' : 'Syncing...'}
              </span>
            ) : (
              'Save Changes'
            )}
          </button>
          <button
            type="button"
            className="ssgsw_save_close"
            onClick={() => setShowDiscardPopup(true)}
            disabled={isLoading || isSyncing}
          >
            Discard Changes
          </button>
        </div>
      )}

      {showDiscardPopup && (
        <Modal
          warning
          title="Discard All Changes"
          description="You are about to discard all unsaved changes. All of your settings will be reset to the point where you last saved. Are you sure you want to do this?"
          onClose={() => setShowDiscardPopup(false)}
        >
          <button type="button" className="ssgsw_save_close1" onClick={() => setShowDiscardPopup(false)}>
            No, continue editing
          </button>
          <button type="button" className="ssgsw_save_changes" onClick={discardChanges}>
            Yes, discard changes
          </button>
        </Modal>
      )}

      {showDisableBulkEditPopup && (
        <Modal
          warning
          title="Wait"
          description="We recommend keeping this feature enabled at all times. It will help you to swiftly update your data and seamlessly sync it with WooCommerce. Disabling this feature may expose you to unintended changes while editing multiple orders on Google Sheets. Do you still want to disable it?"
          onClose={keepBulkEdit}
        >
          <button
            type="button"
            className="ssgsw_save_changes ssgsw_save_changes23"
            onClick={() => { updateOption('bulk_edit_option2', false); setShowDisableBulkEditPopup(false); }}
          >
            Disable at my risk
          </button>
          <button type="button" className="ssgsw_save_close1 osgsw-modal-primary" onClick={keepBulkEdit}>
            Keep Enabled
          </button>
        </Modal>
      )}
    </>
  );
};

export default FloatingSaveBar;
