/**
 * @file ConfigurationStep.jsx
 * @description Service configuration step of the onboarding wizard.
 */

window.ConfigurationStep = function ConfigurationStep({ data, onChange, onNext, onPrev }) {
  const [tiers, setTiers] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [fieldErrors, setFieldErrors] = React.useState({});
  const [touched, setTouched] = React.useState({});

  React.useEffect(() => {
    API.getTiers().then(res => {
      setTiers(res.data.tiers);
      setLoading(false);
    }).catch(() => setLoading(false));
  }, []);

  // Auto-generate webhook URL from company website
  const getAutoWebhookUrl = () => {
    if (!data.companyWebsite) return null;
    let baseUrl = data.companyWebsite;
    if (!baseUrl.startsWith('http')) {
      baseUrl = `https://${baseUrl}`;
    }
    baseUrl = baseUrl.replace(/\/$/, '');
    return `${baseUrl}/webhooks/v0uchme`;
  };

  const autoWebhookUrl = getAutoWebhookUrl();

  // Auto-enable webhooks and set the URL when component mounts or company website changes
  React.useEffect(() => {
    if (autoWebhookUrl && (!data.enableWebhooks || !data.webhookUrl)) {
      onChange({ ...data, enableWebhooks: true, webhookUrl: autoWebhookUrl });
    }
  }, [autoWebhookUrl]);

  const validateField = (field, value) => {
    switch (field) {
      case 'ageRequirement':
        if (!value) return 'Please select an age requirement';
        return null;
      case 'quotaTier':
        if (!value) return 'Please select a service tier';
        return null;
      case 'billingCycle':
        if (!value) return 'Please select a billing cycle';
        return null;
      default:
        return null;
    }
  };

  const validateAllFields = () => {
    const errors = {};
    errors.ageRequirement = validateField('ageRequirement', data.ageRequirement);
    errors.quotaTier = validateField('quotaTier', data.quotaTier);
    errors.billingCycle = validateField('billingCycle', data.billingCycle);

    const filteredErrors = {};
    Object.keys(errors).forEach(key => {
      if (errors[key]) filteredErrors[key] = errors[key];
    });
    return filteredErrors;
  };

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

  const validateAndProceed = () => {
    setTouched({
      ageRequirement: true,
      quotaTier: true,
      billingCycle: true
    });

    const errors = validateAllFields();
    setFieldErrors(errors);

    if (Object.keys(errors).length > 0) {
      return;
    }

    onNext();
  };

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

  if (loading) {
    return (
      <div className="flex justify-center items-center py-12">
        <div className="w-8 h-8 border-4 border-gray-200 border-t-blue-600 rounded-full loading-spinner" />
      </div>
    );
  }

  return (
    <div className="fade-in">
      <h2 className="text-2xl font-bold text-gray-900 mb-6">Configuration</h2>
      <p className="text-gray-600 mb-8">Configure your integration settings.</p>

      <div className="space-y-8">
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-3">
            Age Verification Requirement <span className="text-red-500">*</span>
          </label>
          <div className="grid grid-cols-3 gap-4">
            {[
              { value: 'any', label: 'Any Age', desc: 'No age restriction' },
              { value: '18+', label: '18+', desc: 'Must be 18 or older' },
              { value: '21+', label: '21+', desc: 'Must be 21 or older' }
            ].map(option => (
              <button
                key={option.value}
                onClick={() => handleChange('ageRequirement', option.value)}
                className={`p-4 border-2 rounded-lg text-left transition-colors ${
                  data.ageRequirement === option.value
                    ? 'border-blue-500 bg-blue-50'
                    : 'border-gray-200 hover:border-gray-300'
                }`}
              >
                <div className="font-medium text-gray-900">{option.label}</div>
                <div className="text-sm text-gray-500">{option.desc}</div>
              </button>
            ))}
          </div>
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-3">
            Service Tier <span className="text-red-500">*</span>
          </label>
          <div className="space-y-4">
            {tiers.map(tier => (
              <button
                key={tier.name}
                onClick={() => handleChange('quotaTier', tier.name)}
                className={`w-full p-4 border-2 rounded-lg text-left transition-colors ${
                  data.quotaTier === tier.name
                    ? 'border-blue-500 bg-blue-50'
                    : 'border-gray-200 hover:border-gray-300'
                }`}
              >
                <div className="flex justify-between items-start">
                  <div>
                    <div className="font-medium text-gray-900">{tier.displayName}</div>
                    <div className="text-sm text-gray-500">{tier.description}</div>
                  </div>
                  {data.quotaTier === tier.name && (
                    <svg className="w-5 h-5 text-blue-600" fill="currentColor" viewBox="0 0 20 20">
                      <path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
                    </svg>
                  )}
                </div>
                <ul className="mt-2 text-sm text-gray-600 grid grid-cols-2 gap-1">
                  {tier.features.map((feature, i) => (
                    <li key={i} className="flex items-center">
                      <svg className="w-4 h-4 text-green-500 mr-1" fill="currentColor" viewBox="0 0 20 20">
                        <path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
                      </svg>
                      {feature}
                    </li>
                  ))}
                </ul>
              </button>
            ))}
          </div>
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-3">
            Billing Cycle <span className="text-red-500">*</span>
          </label>
          <p className="text-gray-500 text-sm mb-3">
            Choose your billing frequency. Certificates will be valid for the selected period.
          </p>
          <div className="grid grid-cols-2 gap-4">
            {[
              { value: 'monthly', label: 'Monthly', desc: '1-month certificate validity', price: 'Billed monthly' },
              { value: 'yearly', label: 'Yearly', desc: '1-year certificate validity', price: 'Save with annual billing' }
            ].map(option => (
              <button
                key={option.value}
                onClick={() => handleChange('billingCycle', option.value)}
                className={`p-4 border-2 rounded-lg text-left transition-colors ${
                  data.billingCycle === option.value
                    ? 'border-blue-500 bg-blue-50'
                    : 'border-gray-200 hover:border-gray-300'
                }`}
              >
                <div className="flex justify-between items-start">
                  <div className="font-medium text-gray-900">{option.label}</div>
                  {data.billingCycle === option.value && (
                    <svg className="w-5 h-5 text-blue-600" fill="currentColor" viewBox="0 0 20 20">
                      <path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
                    </svg>
                  )}
                </div>
                <div className="text-sm text-gray-500">{option.desc}</div>
                <div className="text-xs text-blue-600 mt-1">{option.price}</div>
              </button>
            ))}
          </div>
        </div>

        <div className="border-t pt-6">
          <label className="block text-sm font-medium text-gray-700 mb-3">
            Verification Mode <span className="text-red-500">*</span>
          </label>
          <p className="text-gray-500 text-sm mb-4">
            Choose how users will verify their age through your integration.
            Account-based verification uses the standard OAuth flow where users sign in with a v0uch.me account.
            One-time verification allows account-free verification via single-use biometric sessions.
            This can be changed later by an administrator.
          </p>
          <div className="space-y-3">
            {[
              {
                value: false,
                label: 'Account-Based Only',
                desc: 'Users sign in with their v0uch.me account via OAuth. Verifications are included in your tier subscription.'
              },
              {
                value: true,
                label: 'Account-Based and One-Time',
                desc: 'Support both flows. Account-based verifications are included in your subscription; one-time verifications are billed per-use at a higher rate.'
              }
            ].map(option => (
              <button
                key={String(option.value)}
                onClick={() => handleChange('enableOnetimeVerification', option.value)}
                className={`w-full p-4 border-2 rounded-lg text-left transition-colors ${
                  data.enableOnetimeVerification === option.value
                    ? 'border-blue-500 bg-blue-50'
                    : 'border-gray-200 hover:border-gray-300'
                }`}
              >
                <div className="flex justify-between items-start">
                  <div className="font-medium text-gray-900">{option.label}</div>
                  {data.enableOnetimeVerification === option.value && (
                    <svg className="w-5 h-5 text-blue-600 flex-shrink-0" fill="currentColor" viewBox="0 0 20 20">
                      <path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
                    </svg>
                  )}
                </div>
                <div className="text-sm text-gray-500 mt-1">{option.desc}</div>
              </button>
            ))}
          </div>
          {data.enableOnetimeVerification && (
            <React.Fragment>
              <div className="mt-3 p-3 bg-amber-50 border border-amber-200 rounded-lg">
                <div className="flex items-start gap-2">
                  <svg className="w-5 h-5 text-amber-600 mt-0.5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                  </svg>
                  <div className="text-sm text-amber-800">
                    <p className="font-medium">Per-verification billing applies for one-time verifications</p>
                    <p className="mt-1">
                      One-time verifications are billed at a higher per-use rate because each session
                      requires dedicated biometric processing without the amortization of repeat logins
                      that account-based verification provides.
                    </p>
                    <div className="mt-2 p-2 bg-amber-100 rounded">
                      <span className="font-semibold">
                        Your rate ({data.quotaTier} tier):{' '}
                        {data.quotaTier === 'enterprise' ? '$0.75' : data.quotaTier === 'premium' ? '$1.00' : '$1.50'}
                        {' '}per one-time verification
                      </span>
                    </div>
                    <p className="mt-1 text-amber-700 text-xs">
                      Account-based verifications remain included in your tier subscription at no additional per-use cost.
                    </p>
                  </div>
                </div>
              </div>
              <div className="mt-3 p-3 bg-blue-50 border border-blue-200 rounded-lg">
                <div className="flex items-start gap-2">
                  <svg className="w-5 h-5 text-blue-600 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 className="text-sm text-blue-700">
                    <p className="font-medium">How one-time verification works:</p>
                    <ol className="mt-1 list-decimal list-inside space-y-1">
                      <li>Your server initiates a verification session via <code className="bg-blue-100 px-1 rounded">POST /api/onetime/initiate</code></li>
                      <li>The user completes biometric verification (ID + selfie + liveness)</li>
                      <li>A single-use redemption token is generated</li>
                      <li>Your server redeems it via <code className="bg-blue-100 px-1 rounded">POST /oauth/onetime/redeem</code> for a signed JWT age claim</li>
                    </ol>
                    <p className="mt-2">Redemption tokens expire after 24 hours by default. This setting can be adjusted later.</p>
                  </div>
                </div>
              </div>
            </React.Fragment>
          )}
        </div>

        <div className="border-t pt-6">
          <div className="mb-4">
            <div className="flex items-center gap-2 mb-2">
              <svg className="w-5 h-5 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
              </svg>
              <label className="block text-sm font-medium text-gray-700">
                Webhooks Enabled
              </label>
            </div>
            <p className="text-sm text-gray-500 mb-3">
              Receive real-time notifications for verification events. Your webhook endpoint will be automatically configured.
            </p>
          </div>

          {autoWebhookUrl && (
            <div className="p-4 bg-green-50 border border-green-200 rounded-lg">
              <div className="flex items-center gap-2 mb-1">
                <svg className="w-5 h-5 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 10V3L4 14h7v7l9-11h-7z" />
                </svg>
                <span className="text-sm font-medium text-green-800">Auto-generated Webhook URL</span>
              </div>
              <code className="text-sm text-green-700 break-all">{autoWebhookUrl}</code>
              <p className="text-xs text-green-600 mt-2">
                Implement this endpoint to receive signed webhook payloads for verification events.
              </p>
            </div>
          )}
        </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>
  );
};
