import React, { useState } from 'react';
import { __ } from '@wordpress/i18n';
import { Modal, RadioControl, Button } from '@wordpress/components';
import apiFetch from '@wordpress/api-fetch';
import PresetManagerUI from '../components/PresetManagerUI';

/**
 * Welcome Modal component for initial onboarding
 *
 * @param {Object  } props         Component props
 * @param {boolean } props.isOpen  Whether modal is open
 * @param {Function} props.onClose Callback when modal closes
 * @param {string  } props.apiUrl  REST API base URL
 * @param {string  } props.nonce   REST API nonce
 */
const WelcomeModal = ({ isOpen, onClose, apiUrl, nonce }) => {
  const [siteType, setSiteType] = useState('blog');
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState(null);
  const [step, setStep] = useState(1); // 1: initial, 2: preset selection;

  const siteTypeOptions = [
    { value: 'blog', label: __('Blog / Content Site', 'prorank-seo') },
    { value: 'shop', label: __('eCommerce Shop', 'prorank-seo') },
    { value: 'business', label: __('Business/Agency', 'prorank-seo') },
  ];

  const handleSubmit = async () => {
    if (step === 1) {
      // Move to preset selection step
      setStep(2);
    } else {
      // Complete onboarding
      setIsSubmitting(true);
      setError(null);

      try {
        // Set up API fetch
        apiFetch.use(apiFetch.createNonceMiddleware(nonce));
        apiFetch.use(apiFetch.createRootURLMiddleware(apiUrl));

        // Save onboarding settings
        await apiFetch({
          path: '/prorank-seo/v1/onboarding/complete',
          method: 'POST',
          data: {
            site_type: siteType,
          },
        });

        // Clear the modal flag
        await apiFetch({
          path: '/prorank-seo/v1/settings',
          method: 'POST',
          data: {
            prorank_show_onboarding_modal: false,
          },
        });

        // Close modal and reload
        onClose();
        window.location.reload();
      } catch (err) {
        setError(__('An error occurred. Please try again.', 'prorank-seo'));
        setIsSubmitting(false);
      }
    }
  };

  const handleSkip = async () => {
    setIsSubmitting(true);

    try {
      // Set up API fetch
      apiFetch.use(apiFetch.createNonceMiddleware(nonce));
      apiFetch.use(apiFetch.createRootURLMiddleware(apiUrl));

      // Just clear the modal flag
      await apiFetch({
        path: '/prorank-seo/v1/settings',
        method: 'POST',
        data: {
          prorank_show_onboarding_modal: false,
        },
      });

      onClose();
      window.location.reload();
    } catch (err) {
      onClose();
      window.location.reload();
    }
  };

  if (!isOpen) {
    return null;
  }

  return (
    <Modal
      title={
        step === 1
          ? __('Welcome to ProRank SEO!', 'prorank-seo')
          : __('Choose Your Configuration', 'prorank-seo')
      }
      onRequestClose={handleSkip}
      className="prorank-seo-welcome-modal"
      isDismissible={false}
      shouldCloseOnClickOutside={false}
    >
      <div className="prorank-seo-welcome-content">
        {step === 1 ? (
          <>
            <p style={{ fontSize: '16px', marginBottom: '24px' }}>
              {__(
                "Let's get your SEO journey started! Please tell us about your website:",
                'prorank-seo'
              )}
            </p>

            <div style={{ marginBottom: '24px' }}>
              <RadioControl
                label={__('What type of website do you have?', 'prorank-seo')}
                selected={siteType}
                options={siteTypeOptions}
                onChange={setSiteType}
              />
            </div>

          </>
        ) : (
          <>
            <p style={{ fontSize: '16px', marginBottom: '24px' }}>
              {__(
                'Choose a preset configuration optimized for your site type. You can customize these settings later.',
                'prorank-seo'
              )}
            </p>
            <PresetManagerUI inOnboarding={true} />
          </>
        )}

        {error === true && (
          <div
            style={{
              marginBottom: '16px',
              padding: '12px',
              backgroundColor: '#ffebe8',
              border: '1px solid #c3160c',
              borderRadius: '4px',
              color: '#000',
            }}
          >
            {error}
          </div>
        )}

        <div
          style={{
            display: 'flex',
            justifyContent: 'flex-end',
            gap: '12px',
            marginTop: '24px',
            paddingTop: '20px',
            borderTop: '1px solid #ddd',
          }}
        >
          {step === 2 && (
            <Button variant="tertiary" onClick={() => setStep(1)} disabled={isSubmitting === true}>
              {__('Back', 'prorank-seo')}
            </Button>
          )}
          <Button variant="tertiary" onClick={handleSkip} disabled={isSubmitting === true}>
            {__('Skip for now', 'prorank-seo')}
          </Button>

          <Button
            variant="primary"
            onClick={handleSubmit}
            disabled={isSubmitting === true}
            isBusy={isSubmitting === true}
          >
            {step === 1 ? __('Next', 'prorank-seo') : __('Complete Setup', 'prorank-seo')}
          </Button>
        </div>
      </div>
    </Modal>
  );
};

export default WelcomeModal;
