/* global sprintf */
/**
 * Settings Snapshot UI Component
 *
 * @package
 * @since   0.1.0
 */

import { useState, useEffect, useCallback } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';
import { Card, CardBody, Button, Modal, TextControl, Spinner } from '@wordpress/components';
import { trash, backup, rotateLeft } from '@wordpress/icons';
import apiFetch from '@wordpress/api-fetch';
import { useNotification } from '../../contexts/NotificationContext';
import './settings-snapshot.css';

/**
 * Settings Snapshot UI component
 *
 * @param {Object } props          Component props
 * @param {boolean} props.embedded Whether embedded in a settings page
 * @return {JSX.Element} Settings snapshot UI
 */
const SettingsSnapshotUI = ({ embedded = false }) => {
  const [snapshots, setSnapshots] = useState([]);
  const [loading, setLoading] = useState(true);
  const [creating, setCreating] = useState(false);
  const [reverting, setReverting] = useState(false);
  const [deleting, setDeleting] = useState(false);
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [showRevertConfirm, setShowRevertConfirm] = useState(false);
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const [selectedSnapshot, setSelectedSnapshot] = useState(null);
  const [snapshotLabel, setSnapshotLabel] = useState('');
  const [maxSnapshots, setMaxSnapshots] = useState(10);
  const { showNotification } = useNotification();

  const fetchSnapshots = useCallback(async () => {
    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/settings/snapshots',
        method: 'GET',
      });

      if (response.success && response.data) {
        setSnapshots(response.data.snapshots || []);
        setMaxSnapshots(response.data.max_snapshots || 10);
      }
    } catch (error) {
      showNotification(__('Error fetching snapshots.', 'prorank-seo'), 'error');
    } finally {
      setLoading(false);
    }
  }, [showNotification]);

  // Fetch snapshots
  useEffect(() => {
    fetchSnapshots();
  }, [fetchSnapshots]);

  // Create snapshot
  const handleCreateSnapshot = async () => {
    setCreating(true);

    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/settings/snapshots',
        method: 'POST',
        data: {
          label: snapshotLabel || null,
        },
      });

      if (response.success !== undefined && response.success !== null) {
        showNotification(
          response.data.message || __('Snapshot created successfully!', 'prorank-seo'),
          'success'
        );

        // Refresh list
        await fetchSnapshots();

        // Reset form
        setSnapshotLabel('');
        setShowCreateModal(false);
      } else {
        throw new Error(response.message);
      }
    } catch (error) {
      showNotification(
        error.message || __('Failed to create snapshot. Please try again.', 'prorank-seo'),
        'error'
      );
    } finally {
      setCreating(false);
    }
  };

  // Revert to snapshot
  const handleRevertSnapshot = async () => {
    if (!selectedSnapshot) return;

    setReverting(true);
    setShowRevertConfirm(false);

    try {
      const response = await apiFetch({
        path: `/prorank-seo/v1/settings/snapshots/revert/${selectedSnapshot.id}`,
        method: 'POST',
      });

      if (response.success !== undefined && response.success !== null) {
        showNotification(
          response.data.message || __('Settings reverted successfully!', 'prorank-seo'),
          'success'
        );

        // Trigger settings refresh
        window.dispatchEvent(new CustomEvent('prorank-settings-updated'));

        // Refresh snapshots list
        await fetchSnapshots();
      } else {
        throw new Error(response.message);
      }
    } catch (error) {
      showNotification(
        error.message || __('Failed to revert settings. Please try again.', 'prorank-seo'),
        'error'
      );
    } finally {
      setReverting(false);
      setSelectedSnapshot(null);
    }
  };

  // Delete snapshot
  const handleDeleteSnapshot = async () => {
    if (!selectedSnapshot) return;

    setDeleting(true);
    setShowDeleteConfirm(false);

    try {
      const response = await apiFetch({
        path: `/prorank-seo/v1/settings/snapshots/${selectedSnapshot.id}`,
        method: 'DELETE',
      });

      if (response.success !== undefined && response.success !== null) {
        showNotification(
          response.data.message || __('Snapshot deleted successfully!', 'prorank-seo'),
          'success'
        );

        // Refresh list
        await fetchSnapshots();
      } else {
        throw new Error(response.message);
      }
    } catch (error) {
      showNotification(
        error.message || __('Failed to delete snapshot. Please try again.', 'prorank-seo'),
        'error'
      );
    } finally {
      setDeleting(false);
      setSelectedSnapshot(null);
    }
  };

  if (loading) {
    return (
      <div className="prorank-settings-snapshot__loading">
        <Spinner />
        <p>{__('Loading settings history…', 'prorank-seo')}</p>
      </div>
    );
  }

  const containerClass = embedded
    ? 'prorank-settings-snapshot prorank-settings-snapshot--embedded'
    : 'prorank-settings-snapshot';

  return (
    <div className={containerClass}>
      {!embedded && (
        <div className="prorank-settings-snapshot__header">
          <h3>{__('Settings History', 'prorank-seo')}</h3>
          <p className="description">
            {__('Create snapshots of your settings and restore them if needed.', 'prorank-seo')}
          </p>
        </div>
      )}

      <div className="prorank-settings-snapshot__actions">
        <Button
          variant="secondary"
          icon={backup}
          onClick={() => setShowCreateModal(true)}
          disabled={creating || reverting}
        >
          {__('Create Snapshot', 'prorank-seo')}
        </Button>

        {snapshots.length >= maxSnapshots && (
          <span className="prorank-settings-snapshot__limit-notice">
            {sprintf(
              /* translators: %d: maximum number of snapshots */
              __('Maximum of %d snapshots. Oldest will be removed automatically.', 'prorank-seo'),
              maxSnapshots
            )}
          </span>
        )}
      </div>

      {snapshots.length === 0 ? (
        <Card>
          <CardBody>
            <p className="prorank-settings-snapshot__empty">
              {__(
                'No snapshots yet. Create your first snapshot to save your current settings.',
                'prorank-seo'
              )}
            </p>
          </CardBody>
        </Card>
      ) : (
        <div className="prorank-settings-snapshot__list">
          {snapshots.map((snapshot) => (
            <Card key={snapshot.id} className="prorank-settings-snapshot__item" size="small">
              <CardBody>
                <div className="prorank-settings-snapshot__item-content">
                  <div className="prorank-settings-snapshot__item-info">
                    <h4>{snapshot.label}</h4>
                    <p className="prorank-settings-snapshot__item-meta">
                      {sprintf(
                        /* translators: 1: formatted date, 2: user name */
                        __('%1$s by %2$s', 'prorank-seo'),
                        snapshot.formatted_date,
                        snapshot.user_name
                      )}
                    </p>
                  </div>
                  <div className="prorank-settings-snapshot__item-actions">
                    <Button
                      variant="secondary"
                      icon={rotateLeft}
                      onClick={() => {
                        setSelectedSnapshot(snapshot);
                        setShowRevertConfirm(true);
                      }}
                      disabled={reverting || deleting}
                      label={__('Revert to this snapshot', 'prorank-seo')}
                    />
                    <Button
                      variant="tertiary"
                      icon={trash}
                      isDestructive
                      onClick={() => {
                        setSelectedSnapshot(snapshot);
                        setShowDeleteConfirm(true);
                      }}
                      disabled={reverting || deleting}
                      label={__('Delete snapshot', 'prorank-seo')}
                    />
                  </div>
                </div>
              </CardBody>
            </Card>
          ))}
        </div>
      )}

      {/* Create Snapshot Modal */}
      {showCreateModal && (
        <Modal
          title={__('Create Settings Snapshot', 'prorank-seo')}
          onRequestClose={() => setShowCreateModal(false)}
          className="prorank-settings-snapshot__modal"
        >
          <p>{__('Save a snapshot of your current settings configuration.', 'prorank-seo')}</p>

          <TextControl
            label={__('Snapshot Label (optional)', 'prorank-seo')}
            value={snapshotLabel}
            onChange={setSnapshotLabel}
            placeholder={__('e.g., Before major changes', 'prorank-seo')}
            help={__('Leave empty to use automatic timestamp label.', 'prorank-seo')}
          />

          <div className="prorank-settings-snapshot__modal-actions">
            <Button
              variant="tertiary"
              onClick={() => {
                setShowCreateModal(false);
                setSnapshotLabel('');
              }}
            >
              {__('Cancel', 'prorank-seo')}
            </Button>
            <Button
              variant="primary"
              icon={backup}
              onClick={handleCreateSnapshot}
              isBusy={creating === true}
              disabled={creating === true}
            >
              {__('Create Snapshot', 'prorank-seo')}
            </Button>
          </div>
        </Modal>
      )}

      {/* Revert Confirmation */}
      {showRevertConfirm && selectedSnapshot && (
        <Modal
          title={__('Confirm Revert', 'prorank-seo')}
          onRequestClose={() => {
            setShowRevertConfirm(false);
            setSelectedSnapshot(null);
          }}
          className="prorank-confirm-modal"
        >
          <p>
            {sprintf(
              /* translators: %s: snapshot label */
              __(
                'Are you sure you want to revert your settings to "%s"? Your current settings will be saved as a new snapshot before reverting.',
                'prorank-seo'
              ),
              selectedSnapshot.label
            )}
          </p>
          <div className="prorank-modal-buttons">
            <Button
              variant="secondary"
              onClick={() => {
                setShowRevertConfirm(false);
                setSelectedSnapshot(null);
              }}
            >
              {__('Cancel', 'prorank-seo')}
            </Button>
            <Button variant="primary" onClick={handleRevertSnapshot}>
              {__('Revert', 'prorank-seo')}
            </Button>
          </div>
        </Modal>
      )}

      {/* Delete Confirmation */}
      {showDeleteConfirm && selectedSnapshot && (
        <Modal
          title={__('Confirm Delete', 'prorank-seo')}
          onRequestClose={() => {
            setShowDeleteConfirm(false);
            setSelectedSnapshot(null);
          }}
          className="prorank-confirm-modal"
        >
          <p>
            {sprintf(
              /* translators: %s: snapshot label */
              __(
                'Are you sure you want to delete the snapshot "%s"? This action cannot be undone.',
                'prorank-seo'
              ),
              selectedSnapshot.label
            )}
          </p>
          <div className="prorank-modal-buttons">
            <Button
              variant="secondary"
              onClick={() => {
                setShowDeleteConfirm(false);
                setSelectedSnapshot(null);
              }}
            >
              {__('Cancel', 'prorank-seo')}
            </Button>
            <Button variant="primary" isDestructive onClick={handleDeleteSnapshot}>
              {__('Delete', 'prorank-seo')}
            </Button>
          </div>
        </Modal>
      )}

      {/* Loading overlay */}
      {(reverting || deleting) && (
        <div className="prorank-settings-snapshot__overlay">
          <Spinner />
          <p>
            {reverting
              ? __('Reverting settings…', 'prorank-seo')
              : __('Deleting snapshot…', 'prorank-seo')}
          </p>
        </div>
      )}
    </div>
  );
};

export default SettingsSnapshotUI;
