/**
 * @file ContactInfoStep.jsx
 * @description Contact information step of the onboarding wizard.
 */

window.ContactInfoStep = function ContactInfoStep({ data, onChange, onNext, onPrev }) {
  const [fieldErrors, setFieldErrors] = React.useState({});
  const [touched, setTouched] = React.useState({});

  // Validation rules matching backend
  const validateField = (field, value) => {
    switch (field) {
      case 'contactName':
        if (!value || value.length < 2) return 'Contact name must be at least 2 characters';
        return null;
      case 'contactEmail': {
        if (!value) return 'Contact email is required';
        const result = window.validateEmailAddress(value);
        if (!result.isValid) return result.error;
        return null;
      }
      case 'technicalContactEmail': {
        if (value) {
          const result = window.validateEmailAddress(value);
          if (!result.isValid) return result.error;
        }
        return null;
      }
      case 'contactPhone': {
        const result = window.validatePhoneNumber(value);
        if (!result.isValid) return result.error;
        return null;
      }
      default:
        return null;
    }
  };

  const validateAllFields = () => {
    const errors = {};
    errors.contactName = validateField('contactName', data.contactName);
    errors.contactEmail = validateField('contactEmail', data.contactEmail);
    errors.contactPhone = validateField('contactPhone', data.contactPhone);
    errors.technicalContactEmail = validateField('technicalContactEmail', data.technicalContactEmail);

    // Filter out null values
    const filteredErrors = {};
    Object.keys(errors).forEach(key => {
      if (errors[key]) filteredErrors[key] = errors[key];
    });
    return filteredErrors;
  };

  const handleChange = (field, value) => {
    onChange({ ...data, [field]: value });
    // Clear error when user starts typing
    if (touched[field]) {
      const error = validateField(field, value);
      setFieldErrors(prev => ({ ...prev, [field]: error }));
    }
  };

  const handleBlur = (field, value) => {
    setTouched(prev => ({ ...prev, [field]: true }));
    const error = validateField(field, value);
    setFieldErrors(prev => ({ ...prev, [field]: error }));
  };

  const validateAndProceed = () => {
    // Mark all fields as touched
    setTouched({
      contactName: true,
      contactEmail: true,
      contactPhone: true,
      technicalContactEmail: true
    });

    // Validate all fields
    const errors = validateAllFields();
    setFieldErrors(errors);

    if (Object.keys(errors).length > 0) {
      return; // Don't proceed if there are validation errors
    }

    onNext();
  };

  const hasErrors = Object.values(fieldErrors).some(e => e);

  return (
    <div className="fade-in">
      <h2 className="text-2xl font-bold text-gray-900 mb-6">Contact Information</h2>
      <p className="text-gray-600 mb-8">Who should we contact for integration support?</p>

      {/* GDPR Transparency Notice */}
      <div className="mb-8 p-4 bg-blue-50 border border-blue-200 rounded-lg">
        <div className="flex items-start">
          <svg className="w-5 h-5 text-blue-600 mr-3 mt-0.5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
          </svg>
          <div>
            <p className="text-blue-800 font-medium text-sm">User Transparency Notice</p>
            <p className="text-blue-700 text-sm mt-1">
              The contact email address will be visible to users in their GDPR data exports and consent history.
              This allows users to contact your organization regarding their data if needed.
            </p>
            <p className="text-blue-600 text-xs mt-2">
              We recommend using a general contact or privacy email (e.g., privacy@yourcompany.com) rather than a personal email.
            </p>
          </div>
        </div>
      </div>

      <div className="space-y-6">
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            Contact Name <span className="text-red-500">*</span>
          </label>
          <input
            type="text"
            value={data.contactName || ''}
            onChange={(e) => handleChange('contactName', e.target.value)}
            onBlur={(e) => handleBlur('contactName', e.target.value)}
            className={`w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 ${
              fieldErrors.contactName && touched.contactName ? 'border-red-500 bg-red-50' : 'border-gray-300'
            }`}
            placeholder="John Smith"
          />
          {fieldErrors.contactName && touched.contactName && (
            <p className="text-red-500 text-sm mt-1">{fieldErrors.contactName}</p>
          )}
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            Contact Email <span className="text-red-500">*</span>
          </label>
          <input
            type="email"
            value={data.contactEmail || ''}
            onChange={(e) => handleChange('contactEmail', e.target.value)}
            onBlur={(e) => handleBlur('contactEmail', e.target.value)}
            className={`w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 ${
              fieldErrors.contactEmail && touched.contactEmail ? 'border-red-500 bg-red-50' : 'border-gray-300'
            }`}
            placeholder="john@example.com"
          />
          {fieldErrors.contactEmail && touched.contactEmail && (
            <p className="text-red-500 text-sm mt-1">{fieldErrors.contactEmail}</p>
          )}
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            Phone Number
          </label>
          <input
            type="tel"
            value={data.contactPhone || ''}
            onChange={(e) => handleChange('contactPhone', e.target.value)}
            onBlur={(e) => handleBlur('contactPhone', e.target.value)}
            className={`w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 ${
              fieldErrors.contactPhone && touched.contactPhone ? 'border-red-500 bg-red-50' : 'border-gray-300'
            }`}
            placeholder="+1 (555) 123-4567"
          />
          {fieldErrors.contactPhone && touched.contactPhone ? (
            <p className="text-red-500 text-sm mt-1">{fieldErrors.contactPhone}</p>
          ) : (
            <p className="text-gray-500 text-sm mt-1">
              Optional. Accepts international formats (e.g. +1 555-123-4567).
            </p>
          )}
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            Technical Contact Email
          </label>
          <input
            type="email"
            value={data.technicalContactEmail || ''}
            onChange={(e) => handleChange('technicalContactEmail', e.target.value)}
            onBlur={(e) => handleBlur('technicalContactEmail', e.target.value)}
            className={`w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 ${
              fieldErrors.technicalContactEmail && touched.technicalContactEmail ? 'border-red-500 bg-red-50' : 'border-gray-300'
            }`}
            placeholder="dev@example.com"
          />
          {fieldErrors.technicalContactEmail && touched.technicalContactEmail ? (
            <p className="text-red-500 text-sm mt-1">{fieldErrors.technicalContactEmail}</p>
          ) : (
            <p className="text-gray-500 text-sm mt-1">
              Optional. Will receive API integration notifications.
            </p>
          )}
        </div>
      </div>

      {hasErrors && (
        <div className="mt-6 p-4 bg-red-50 border border-red-200 rounded-lg">
          <div className="flex items-start">
            <svg className="w-5 h-5 text-red-600 mr-2 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
            <div>
              <p className="text-red-700 font-medium">Please fix the following errors:</p>
              <ul className="text-red-600 text-sm mt-1 list-disc list-inside">
                {Object.values(fieldErrors).filter(e => e).map((error, i) => (
                  <li key={i}>{error}</li>
                ))}
              </ul>
            </div>
          </div>
        </div>
      )}

      <div className="flex justify-between mt-8">
        <button
          onClick={onPrev}
          className="px-6 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50"
        >
          Back
        </button>
        <button
          onClick={validateAndProceed}
          className="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
        >
          Continue
        </button>
      </div>
    </div>
  );
};
