import { useState, useEffect } from '@wordpress/element';
import { createPortal } from 'react-dom';
import { __ } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';
import { useLicense } from '../../contexts/LicenseContext';
import { useNotification } from '../../contexts/NotificationContext';

const RedirectEditPanel = ({ redirect, onClose, defaultRedirectType = '301' }) => {
  const [formData, setFormData] = useState({
    source_url: redirect?.source_url || '',
    target_url: redirect?.target_url || '',
    type: redirect?.type || defaultRedirectType,
    status: redirect?.status || 'active',
    is_regex: redirect?.is_regex || false,
  });
  const [saving, setSaving] = useState(false);
  const [errors, setErrors] = useState({});
  const { isTierActive } = useLicense();
  const { showNotification } = useNotification();

  const isPro = isTierActive('pro');
  const isEdit = Boolean(redirect?.id);

  // Keep form data in sync when opening the modal with different redirect drafts.
  useEffect(() => {
    setFormData({
      source_url: redirect?.source_url || '',
      target_url: redirect?.target_url || '',
      type: redirect?.type || defaultRedirectType,
      status: redirect?.status || 'active',
      is_regex: redirect?.is_regex || false,
    });
    setErrors({});
  }, [redirect, defaultRedirectType]);

  // Lock body scroll when modal is open
  useEffect(() => {
    document.body.style.overflow = 'hidden';
    return () => {
      document.body.style.overflow = '';
    };
  }, []);

  // Close on escape key
  useEffect(() => {
    const handleEscape = (e) => {
      if (e.key === 'Escape' && !saving) {
        onClose();
      }
    };
    document.addEventListener('keydown', handleEscape);
    return () => document.removeEventListener('keydown', handleEscape);
  }, [saving, onClose]);

  const validateForm = () => {
    const newErrors = {};

    if (!formData.source_url.trim()) {
      newErrors.source_url = __('Source URL is required', 'prorank-seo');
    }

    if (!formData.target_url.trim()) {
      newErrors.target_url = __('Target URL is required', 'prorank-seo');
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = async () => {
    if (!validateForm()) return;

    setSaving(true);
    try {
      const method = isEdit ? 'PUT' : 'POST';
      const path = isEdit ? `/prorank-seo/v1/redirects/${redirect.id}` : '/prorank-seo/v1/redirects';

      await apiFetch({
        path,
        method,
        data: formData,
      });

      showNotification(
        isEdit
          ? __('Redirect updated successfully', 'prorank-seo')
          : __('Redirect created successfully', 'prorank-seo'),
        'success'
      );
      onClose();
    } catch (error) {
      showNotification(error.message || __('Failed to save redirect', 'prorank-seo'), 'error');
    } finally {
      setSaving(false);
    }
  };

  const overlayStyle = {
    position: 'fixed',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    backgroundColor: 'rgba(0, 0, 0, 0.6)',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    zIndex: 999999,
    padding: '20px',
  };

  const modalStyle = {
    backgroundColor: '#fff',
    borderRadius: '8px',
    boxShadow: '0 20px 60px rgba(0, 0, 0, 0.3)',
    width: '100%',
    maxWidth: '500px',
    maxHeight: '90vh',
    overflow: 'auto',
  };

  const headerStyle = {
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: '16px 20px',
    borderBottom: '1px solid #e5e7eb',
  };

  const bodyStyle = {
    padding: '20px',
  };

  const footerStyle = {
    display: 'flex',
    justifyContent: 'flex-end',
    gap: '12px',
    padding: '16px 20px',
    borderTop: '1px solid #e5e7eb',
    backgroundColor: '#f9fafb',
  };

  const inputStyle = {
    width: '100%',
    padding: '8px 12px',
    border: '1px solid #d1d5db',
    borderRadius: '6px',
    fontSize: '14px',
    marginTop: '4px',
  };

  const labelStyle = {
    display: 'block',
    fontSize: '14px',
    fontWeight: '500',
    color: '#374151',
    marginBottom: '16px',
  };

  const buttonStyle = {
    padding: '8px 16px',
    borderRadius: '6px',
    fontSize: '14px',
    fontWeight: '500',
    cursor: 'pointer',
    border: 'none',
  };

  const modalContent = (
    <div
      style={overlayStyle}
      onClick={(e) => {
        if (e.target === e.currentTarget && !saving) {
          onClose();
        }
      }}
    >
      <div style={modalStyle} onClick={(e) => e.stopPropagation()}>
        {/* Header */}
        <div style={headerStyle}>
          <h2 style={{ margin: 0, fontSize: '18px', fontWeight: '600' }}>
            {isEdit ? __('Edit Redirect', 'prorank-seo') : __('Add New Redirect', 'prorank-seo')}
          </h2>
          <button
            type="button"
            onClick={onClose}
            disabled={saving}
            style={{
              background: 'none',
              border: 'none',
              fontSize: '24px',
              cursor: 'pointer',
              color: '#6b7280',
              padding: '4px',
            }}
          >
            ×
          </button>
        </div>

        {/* Body */}
        <div style={bodyStyle}>
          <label style={labelStyle}>
            {__('Source URL', 'prorank-seo')}
            <input
              type="text"
              value={formData.source_url}
              onChange={(e) => setFormData({ ...formData, source_url: e.target.value })}
              placeholder="/old-page"
              style={{
                ...inputStyle,
                borderColor: errors.source_url ? '#ef4444' : '#d1d5db',
              }}
            />
            {errors.source_url && (
              <span style={{ color: '#ef4444', fontSize: '12px', marginTop: '4px', display: 'block' }}>
                {errors.source_url}
              </span>
            )}
          </label>

          <label style={labelStyle}>
            {__('Target URL', 'prorank-seo')}
            <input
              type="text"
              value={formData.target_url}
              onChange={(e) => setFormData({ ...formData, target_url: e.target.value })}
              placeholder="/new-page"
              style={{
                ...inputStyle,
                borderColor: errors.target_url ? '#ef4444' : '#d1d5db',
              }}
            />
            {errors.target_url && (
              <span style={{ color: '#ef4444', fontSize: '12px', marginTop: '4px', display: 'block' }}>
                {errors.target_url}
              </span>
            )}
          </label>

          <label style={labelStyle}>
            {__('Redirect Type', 'prorank-seo')}
            <select
              value={formData.type}
              onChange={(e) => setFormData({ ...formData, type: e.target.value })}
              style={inputStyle}
            >
              <option value="301">{__('301 Moved Permanently', 'prorank-seo')}</option>
              <option value="302">{__('302 Found (Temporary)', 'prorank-seo')}</option>
              <option value="307">{__('307 Temporary Redirect', 'prorank-seo')}</option>
              <option value="308">{__('308 Permanent Redirect', 'prorank-seo')}</option>
            </select>
          </label>

          <label style={{ ...labelStyle, display: 'flex', alignItems: 'center', gap: '8px' }}>
            <input
              type="checkbox"
              checked={formData.status === 'active'}
              onChange={(value) => {
                const isChecked = typeof value === 'boolean' ? value : value?.target?.checked;
                setFormData({
                  ...formData,
                  status: isChecked ? 'active' : 'inactive',
                });
              }}
              style={{ width: '16px', height: '16px' }}
            />
            {__('Active', 'prorank-seo')}
          </label>

          {isPro && (
            <label style={{ ...labelStyle, display: 'flex', alignItems: 'center', gap: '8px' }}>
              <input
                type="checkbox"
                checked={formData.is_regex}
                onChange={(value) => {
                  const isChecked = typeof value === 'boolean' ? value : value?.target?.checked;
                  setFormData({ ...formData, is_regex: isChecked });
                }}
                style={{ width: '16px', height: '16px' }}
              />
              {__('Use Regular Expression', 'prorank-seo')}
            </label>
          )}
        </div>

        {/* Footer */}
        <div style={footerStyle}>
          <button
            type="button"
            onClick={onClose}
            disabled={saving}
            style={{
              ...buttonStyle,
              backgroundColor: '#fff',
              border: '1px solid #d1d5db',
              color: '#374151',
            }}
          >
            {__('Cancel', 'prorank-seo')}
          </button>
          <button
            type="button"
            onClick={handleSubmit}
            disabled={saving}
            style={{
              ...buttonStyle,
              backgroundColor: '#f97316',
              color: '#fff',
              opacity: saving ? 0.7 : 1,
            }}
          >
            {saving
              ? __('Saving…', 'prorank-seo')
              : isEdit
              ? __('Update Redirect', 'prorank-seo')
              : __('Add Redirect', 'prorank-seo')}
          </button>
        </div>
      </div>
    </div>
  );

  // Render to body using portal
  return createPortal(modalContent, document.body);
};

export default RedirectEditPanel;
