/* global sprintf */
/**
 * Preset Manager UI Component
 *
 * @package
 * @since   0.1.0
 */

import { useState, useEffect, useCallback } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';
import { Card, CardBody, CardHeader, Button, Modal, Spinner, Icon } from '@wordpress/components';
import apiFetch from '@wordpress/api-fetch';
import { useNotification } from '../../contexts/NotificationContext';

// Icon mapping
const iconMap = {
  edit: 'edit',
  location: 'location',
  cart: 'cart',
  'admin-generic': 'admin-generic',
};

/**
 * Preset Manager UI component
 *
 * @param {Object } props              Component props.
 * @param {boolean} props.inOnboarding Whether shown during onboarding.
 * @return {JSX.Element} Preset manager UI.
 */
const PresetManagerUI = ({ inOnboarding = false }) => {
  const [presets, setPresets] = useState([]);
  const [loading, setLoading] = useState(true);
  const [applying, setApplying] = useState(false);
  const [selectedPreset, setSelectedPreset] = useState(null);
  const [showConfirmModal, setShowConfirmModal] = useState(false);
  const { showNotification } = useNotification();

  // Fetch available presets
  // Memoized fetch to appease exhaustive-deps
  const fetchPresets = useCallback(async () => {
    try {
      const response = await apiFetch({ path: '/prorank-seo/v1/presets', method: 'GET' });

      if (response?.success === true && response?.data !== undefined && response.data !== null) {
        setPresets(response.data.presets ?? []);
      }
    } catch (error) {
      showNotification(__('Failed to load presets. Please try again.', 'prorank-seo'), 'error');
    } finally {
      setLoading(false);
    }
  }, [showNotification]);

  useEffect(() => {
    fetchPresets();
  }, [fetchPresets]);

  // Handle preset selection
  const handleSelectPreset = (preset) => {
    setSelectedPreset(preset);
    setShowConfirmModal(true);
  };

  // Apply selected preset
  const handleApplyPreset = async () => {
    if (selectedPreset === null) {
      return;
    }

    setApplying(true);
    setShowConfirmModal(false);

    try {
      const response = await apiFetch({
        path: `/prorank-seo/v1/presets/apply/${selectedPreset.id}`,
        method: 'POST',
      });

      if (response?.success === true) {
        showNotification(
          response.data?.message ?? __('Preset applied successfully!', 'prorank-seo'),
          'success'
        );

        // Trigger settings refresh if needed
        window.dispatchEvent(new CustomEvent('prorank-settings-updated'));
      } else {
        throw new Error(response.message);
      }
    } catch (error) {
      showNotification(
        error.message ?? __('Failed to apply preset. Please try again.', 'prorank-seo'),
        'error'
      );
    } finally {
      setApplying(false);
      setSelectedPreset(null);
    }
  };

  if (loading !== '') {
    return (
      <div className="prorank-preset-manager__loading">
        <Spinner />
        <p>{__('Loading presets…', 'prorank-seo')}</p>
      </div>
    );
  }

  return (
    <div className="prorank-preset-manager">
      {!inOnboarding && (
        <div className="prorank-preset-manager__header">
          <h3>{__('Quick Setup Presets', 'prorank-seo')}</h3>
          <p className="description">
            {__(
              'Choose a preset configuration optimized for your site type. You can customize these settings later.',
              'prorank-seo'
            )}
          </p>
        </div>
      )}

      <div className="prorank-preset-manager__grid">
        {presets.map((preset) => (
          <Card key={preset.id} className="prorank-preset-card" size="small">
            <CardHeader>
              <div className="prorank-preset-card__header">
                <Icon icon={iconMap[preset.icon] ?? 'admin-generic'} size={24} />
                <h4>{preset.name}</h4>
              </div>
            </CardHeader>
            <CardBody>
              <p className="prorank-preset-card__description">{preset.description}</p>
              <p className="prorank-preset-card__settings-count">
                {sprintf(
                  /* translators: %d: number of settings */
                  __('%d optimized settings', 'prorank-seo'),
                  preset.settings_count ?? 0
                )}
              </p>
              <Button
                variant="primary"
                onClick={() => handleSelectPreset(preset)}
                disabled={applying === true}
                className="prorank-preset-card__apply-button"
              >
                {__('Apply Preset', 'prorank-seo')}
              </Button>
            </CardBody>
          </Card>
        ))}
      </div>

      {showConfirmModal === true && selectedPreset !== null && (
        <Modal
          title={__('Apply Preset?', 'prorank-seo')}
          onRequestClose={() => setShowConfirmModal(false)}
          className="prorank-preset-confirm-modal"
        >
          <p>
            {sprintf(
              /* translators: %s: preset name */
              __(
                'Are you sure you want to apply the "%s" preset? This will update your SEO settings to match the preset configuration.',
                'prorank-seo'
              ),
              selectedPreset.name
            )}
          </p>
          <p>
            <strong>{__('Note:', 'prorank-seo')}</strong>{' '}
            {__('You can always customize these settings later or revert changes.', 'prorank-seo')}
          </p>

          <div className="prorank-preset-confirm-modal__actions">
            <Button variant="tertiary" onClick={() => setShowConfirmModal(false)}>
              {__('Cancel', 'prorank-seo')}
            </Button>
            <Button variant="primary" onClick={handleApplyPreset}>
              {__('Apply Preset', 'prorank-seo')}
            </Button>
          </div>
        </Modal>
      )}

      {applying === true && (
        <div className="prorank-preset-manager__applying-overlay">
          <Spinner />
          <p>{__('Applying preset settings…', 'prorank-seo')}</p>
        </div>
      )}
    </div>
  );
};

export default PresetManagerUI;
