/**
 * Email Configuration Wizard Component
 *
 * A step-by-step wizard for configuring email settings with:
 * - Auto-detection of email provider (Gmail, Outlook, etc.)
 * - OAuth authentication for Google and Microsoft
 * - Manual IMAP/SMTP configuration fallback
 * - Connection testing
 */

import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import {
  Mail,
  Loader2,
  CheckCircle,
  AlertCircle,
  ArrowRight,
  ArrowLeft,
  Settings,
  Key,
  Shield,
  Server,
  Eye,
  EyeOff,
  ExternalLink,
  Zap,
} from 'lucide-react';
import {
  useDetectEmailProvider,
  useUpdateTicketEmailSettings,
  useTestImapConnection,
  useTestSmtpConnection,
  useOAuthStatus,
  useInitiateGoogleOAuth,
  useInitiateMicrosoftOAuth,
  EmailProviderDetectResult,
} from '../hooks/useTicketEmailSettings';

type WizardStep = 'email' | 'auth-method' | 'oauth' | 'manual' | 'test' | 'complete';

interface EmailConfigWizardProps {
  onComplete?: () => void;
  onCancel?: () => void;
  initialEmail?: string;
}

// Provider icons/logos (using colored backgrounds as placeholders)
const ProviderIcon: React.FC<{ provider: string }> = ({ provider }) => {
  const colors: Record<string, string> = {
    google: 'bg-red-500',
    microsoft: 'bg-blue-600',
    yahoo: 'bg-purple-600',
    apple: 'bg-gray-800',
    unknown: 'bg-gray-400',
  };

  const labels: Record<string, string> = {
    google: 'G',
    microsoft: 'M',
    yahoo: 'Y',
    apple: 'A',
    unknown: '?',
  };

  return (
    <div
      className={`w-10 h-10 rounded-lg ${colors[provider] || colors.unknown} flex items-center justify-center text-white font-bold text-lg`}
    >
      {labels[provider] || '?'}
    </div>
  );
};

const EmailConfigWizard: React.FC<EmailConfigWizardProps> = ({
  onComplete,
  onCancel,
  initialEmail = '',
}) => {
  const { t } = useTranslation();

  // Wizard state
  const [currentStep, setCurrentStep] = useState<WizardStep>('email');
  const [email, setEmail] = useState(initialEmail);
  const [detectedProvider, setDetectedProvider] = useState<EmailProviderDetectResult | null>(null);
  const [authMethod, setAuthMethod] = useState<'oauth' | 'manual'>('manual');

  // Manual config state
  const [manualConfig, setManualConfig] = useState({
    imap_host: '',
    imap_port: 993,
    imap_use_ssl: true,
    imap_username: '',
    imap_password: '',
    smtp_host: '',
    smtp_port: 587,
    smtp_use_tls: true,
    smtp_use_ssl: false,
    smtp_username: '',
    smtp_password: '',
    smtp_from_email: '',
    smtp_from_name: '',
  });

  const [showImapPassword, setShowImapPassword] = useState(false);
  const [showSmtpPassword, setShowSmtpPassword] = useState(false);

  // Mutations
  const detectMutation = useDetectEmailProvider();
  const updateMutation = useUpdateTicketEmailSettings();
  const testImapMutation = useTestImapConnection();
  const testSmtpMutation = useTestSmtpConnection();

  // OAuth
  const { data: oauthStatus } = useOAuthStatus();
  const googleOAuthMutation = useInitiateGoogleOAuth();
  const microsoftOAuthMutation = useInitiateMicrosoftOAuth();

  // Update manual config when provider is detected
  useEffect(() => {
    if (detectedProvider && detectedProvider.detected) {
      setManualConfig((prev) => ({
        ...prev,
        imap_host: detectedProvider.imap_host || prev.imap_host,
        imap_port: detectedProvider.imap_port || prev.imap_port,
        smtp_host: detectedProvider.smtp_host || prev.smtp_host,
        smtp_port: detectedProvider.smtp_port || prev.smtp_port,
        imap_username: email,
        smtp_username: email,
        smtp_from_email: email,
      }));
    }
  }, [detectedProvider, email]);

  // Step 1: Detect email provider
  const handleDetectProvider = async () => {
    if (!email || !email.includes('@')) return;

    try {
      const result = await detectMutation.mutateAsync(email);
      setDetectedProvider(result);

      if (result.oauth_supported) {
        setAuthMethod('oauth');
      } else {
        setAuthMethod('manual');
      }

      setCurrentStep('auth-method');
    } catch {
      // If detection fails, go to manual config
      setAuthMethod('manual');
      setCurrentStep('auth-method');
    }
  };

  // Step 2: Choose auth method
  const handleAuthMethodSelect = (method: 'oauth' | 'manual') => {
    setAuthMethod(method);
    if (method === 'oauth') {
      setCurrentStep('oauth');
    } else {
      setCurrentStep('manual');
    }
  };

  // Step 3a: OAuth flow - redirect to provider's auth page
  const handleOAuthConnect = async () => {
    if (!detectedProvider) return;

    try {
      let result;

      if (detectedProvider.provider === 'google') {
        // Check if Google OAuth is configured
        if (!oauthStatus?.google?.configured) {
          alert('Google OAuth is not configured. Please contact your administrator or use manual configuration.');
          setCurrentStep('manual');
          return;
        }
        result = await googleOAuthMutation.mutateAsync('email');
      } else if (detectedProvider.provider === 'microsoft') {
        // Check if Microsoft OAuth is configured
        if (!oauthStatus?.microsoft?.configured) {
          alert('Microsoft OAuth is not configured. Please contact your administrator or use manual configuration.');
          setCurrentStep('manual');
          return;
        }
        result = await microsoftOAuthMutation.mutateAsync('email');
      } else {
        // Unsupported OAuth provider
        alert('OAuth is not supported for this provider. Please use manual configuration.');
        setCurrentStep('manual');
        return;
      }

      if (result.success && result.authorization_url) {
        // Redirect to OAuth provider
        window.location.href = result.authorization_url;
      } else {
        alert(result.error || 'Failed to initiate OAuth. Please try manual configuration.');
        setCurrentStep('manual');
      }
    } catch {
      alert('Failed to initiate OAuth. Please try manual configuration.');
      setCurrentStep('manual');
    }
  };

  // Check if OAuth is available for this provider
  const isOAuthAvailable = (provider: string | undefined): boolean => {
    if (!provider || !oauthStatus) return false;
    if (provider === 'google') return oauthStatus.google?.configured ?? false;
    if (provider === 'microsoft') return oauthStatus.microsoft?.configured ?? false;
    return false;
  };

  // Step 3b: Save manual configuration
  const handleSaveManualConfig = async () => {
    try {
      await updateMutation.mutateAsync({
        ...manualConfig,
        support_email_address: email,
      });
      setCurrentStep('test');
    } catch {
      // Error is handled by mutation
    }
  };

  // Step 4: Test connections
  const handleTestConnections = async () => {
    await Promise.all([testImapMutation.mutateAsync(), testSmtpMutation.mutateAsync()]);
  };

  // Step navigation
  const goBack = () => {
    switch (currentStep) {
      case 'auth-method':
        setCurrentStep('email');
        break;
      case 'oauth':
      case 'manual':
        setCurrentStep('auth-method');
        break;
      case 'test':
        setCurrentStep('manual');
        break;
      case 'complete':
        setCurrentStep('test');
        break;
    }
  };

  // Progress indicator
  const steps = ['email', 'auth-method', authMethod === 'oauth' ? 'oauth' : 'manual', 'test'];
  const currentStepIndex = steps.indexOf(currentStep);
  const progress = ((currentStepIndex + 1) / steps.length) * 100;

  return (
    <div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 overflow-hidden">
      {/* Header */}
      <div className="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
        <div className="flex items-center justify-between">
          <h2 className="text-lg font-semibold text-gray-900 dark:text-white flex items-center gap-2">
            <Mail className="w-5 h-5" />
            {t('emailWizard.title', 'Configure Email Settings')}
          </h2>
          {onCancel && (
            <button
              onClick={onCancel}
              className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
            >
              &times;
            </button>
          )}
        </div>

        {/* Progress bar */}
        <div className="mt-4 h-1 bg-gray-200 dark:bg-gray-700 rounded-full overflow-hidden">
          <div
            className="h-full bg-blue-600 transition-all duration-300"
            style={{ width: `${progress}%` }}
          />
        </div>
      </div>

      {/* Content */}
      <div className="p-6">
        {/* Step 1: Enter Email */}
        {currentStep === 'email' && (
          <div className="space-y-6">
            <div>
              <h3 className="text-lg font-medium text-gray-900 dark:text-white mb-2">
                {t('emailWizard.step1.title', 'Enter your support email address')}
              </h3>
              <p className="text-sm text-gray-500 dark:text-gray-400">
                {t(
                  'emailWizard.step1.description',
                  "We'll auto-detect your email provider and configure the optimal settings."
                )}
              </p>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                {t('emailWizard.emailAddress', 'Email Address')}
              </label>
              <div className="relative">
                <Mail className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
                <input
                  type="email"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  placeholder="support@yourcompany.com"
                  className="w-full pl-10 pr-4 py-3 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  onKeyPress={(e) => e.key === 'Enter' && handleDetectProvider()}
                />
              </div>
            </div>

            <button
              onClick={handleDetectProvider}
              disabled={!email || !email.includes('@') || detectMutation.isPending}
              className="w-full flex items-center justify-center gap-2 px-6 py-3 bg-blue-600 text-white font-medium rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
            >
              {detectMutation.isPending ? (
                <>
                  <Loader2 className="w-5 h-5 animate-spin" />
                  {t('emailWizard.detecting', 'Detecting provider...')}
                </>
              ) : (
                <>
                  {t('emailWizard.continue', 'Continue')}
                  <ArrowRight className="w-5 h-5" />
                </>
              )}
            </button>
          </div>
        )}

        {/* Step 2: Choose Auth Method */}
        {currentStep === 'auth-method' && (
          <div className="space-y-6">
            {/* Detection result */}
            {detectedProvider && (
              <div
                className={`p-4 rounded-lg ${detectedProvider.detected ? 'bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800' : 'bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800'}`}
              >
                <div className="flex items-center gap-3">
                  <ProviderIcon provider={detectedProvider.provider} />
                  <div>
                    <p className="font-medium text-gray-900 dark:text-white">
                      {detectedProvider.display_name}
                    </p>
                    <p className="text-sm text-gray-500 dark:text-gray-400">
                      {detectedProvider.detected
                        ? t('emailWizard.providerDetected', 'Provider detected automatically')
                        : t('emailWizard.providerUnknown', 'Provider could not be auto-detected')}
                    </p>
                  </div>
                  {detectedProvider.detected && (
                    <CheckCircle className="w-5 h-5 text-green-500 ml-auto" />
                  )}
                </div>
              </div>
            )}

            <div>
              <h3 className="text-lg font-medium text-gray-900 dark:text-white mb-2">
                {t('emailWizard.step2.title', 'Choose authentication method')}
              </h3>
              <p className="text-sm text-gray-500 dark:text-gray-400">
                {t(
                  'emailWizard.step2.description',
                  'Select how you want to authenticate with your email provider.'
                )}
              </p>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {/* OAuth option */}
              <button
                onClick={() => handleAuthMethodSelect('oauth')}
                disabled={!detectedProvider?.oauth_supported || !isOAuthAvailable(detectedProvider?.provider)}
                className={`p-4 rounded-lg border-2 text-left transition-all ${
                  detectedProvider?.oauth_supported && isOAuthAvailable(detectedProvider?.provider)
                    ? 'border-blue-200 dark:border-blue-800 hover:border-blue-500 hover:bg-blue-50 dark:hover:bg-blue-900/20 cursor-pointer'
                    : 'border-gray-200 dark:border-gray-700 opacity-50 cursor-not-allowed'
                }`}
              >
                <div className="flex items-start gap-3">
                  <div className="p-2 bg-blue-100 dark:bg-blue-900/30 rounded-lg">
                    <Shield className="w-6 h-6 text-blue-600 dark:text-blue-400" />
                  </div>
                  <div className="flex-1">
                    <h4 className="font-medium text-gray-900 dark:text-white flex items-center gap-2">
                      {t('emailWizard.oauth.title', 'Sign in with OAuth')}
                      {detectedProvider?.oauth_supported && isOAuthAvailable(detectedProvider?.provider) && (
                        <span className="px-2 py-0.5 text-xs bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-400 rounded">
                          {t('emailWizard.recommended', 'Recommended')}
                        </span>
                      )}
                    </h4>
                    <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
                      {!detectedProvider?.oauth_supported
                        ? t(
                            'emailWizard.oauth.notSupported',
                            'OAuth is not supported for this provider.'
                          )
                        : !isOAuthAvailable(detectedProvider?.provider)
                          ? t(
                              'emailWizard.oauth.notConfigured',
                              'OAuth is not configured on this server. Contact your administrator.'
                            )
                          : t(
                              'emailWizard.oauth.description',
                              'More secure. No password required. Tokens refresh automatically.'
                            )}
                    </p>
                  </div>
                </div>
              </button>

              {/* Manual option */}
              <button
                onClick={() => handleAuthMethodSelect('manual')}
                className="p-4 rounded-lg border-2 border-gray-200 dark:border-gray-700 hover:border-gray-400 hover:bg-gray-50 dark:hover:bg-gray-700/50 text-left transition-all"
              >
                <div className="flex items-start gap-3">
                  <div className="p-2 bg-gray-100 dark:bg-gray-700 rounded-lg">
                    <Key className="w-6 h-6 text-gray-600 dark:text-gray-400" />
                  </div>
                  <div className="flex-1">
                    <h4 className="font-medium text-gray-900 dark:text-white">
                      {t('emailWizard.manual.title', 'Manual Configuration')}
                    </h4>
                    <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
                      {t(
                        'emailWizard.manual.description',
                        'Enter IMAP/SMTP server settings and app password manually.'
                      )}
                    </p>
                  </div>
                </div>
              </button>
            </div>

            <button
              onClick={goBack}
              className="flex items-center gap-2 text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white"
            >
              <ArrowLeft className="w-4 h-4" />
              {t('emailWizard.back', 'Back')}
            </button>
          </div>
        )}

        {/* Step 3a: OAuth */}
        {currentStep === 'oauth' && (
          <div className="space-y-6">
            <div>
              <h3 className="text-lg font-medium text-gray-900 dark:text-white mb-2">
                {t('emailWizard.step3oauth.title', 'Connect with {{provider}}', {
                  provider: detectedProvider?.display_name || 'OAuth',
                })}
              </h3>
              <p className="text-sm text-gray-500 dark:text-gray-400">
                {t(
                  'emailWizard.step3oauth.description',
                  "You'll be redirected to sign in and grant email access."
                )}
              </p>
            </div>

            <div className="p-4 bg-blue-50 dark:bg-blue-900/20 rounded-lg border border-blue-200 dark:border-blue-800">
              <div className="flex items-start gap-3">
                <Zap className="w-5 h-5 text-blue-600 dark:text-blue-400 mt-0.5" />
                <div>
                  <p className="text-sm text-blue-800 dark:text-blue-300">
                    {t(
                      'emailWizard.oauth.benefits',
                      'OAuth provides enhanced security without storing your password. Access can be revoked at any time from your account settings.'
                    )}
                  </p>
                </div>
              </div>
            </div>

            <button
              onClick={handleOAuthConnect}
              className="w-full flex items-center justify-center gap-2 px-6 py-3 bg-blue-600 text-white font-medium rounded-lg hover:bg-blue-700 transition-colors"
            >
              <ExternalLink className="w-5 h-5" />
              {t('emailWizard.oauth.connect', 'Connect with {{provider}}', {
                provider: detectedProvider?.display_name || 'OAuth',
              })}
            </button>

            <button
              onClick={goBack}
              className="flex items-center gap-2 text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white"
            >
              <ArrowLeft className="w-4 h-4" />
              {t('emailWizard.back', 'Back')}
            </button>
          </div>
        )}

        {/* Step 3b: Manual Configuration */}
        {currentStep === 'manual' && (
          <div className="space-y-6">
            <div>
              <h3 className="text-lg font-medium text-gray-900 dark:text-white mb-2">
                {t('emailWizard.step3manual.title', 'Configure IMAP & SMTP')}
              </h3>
              <p className="text-sm text-gray-500 dark:text-gray-400">
                {detectedProvider?.detected
                  ? t(
                      'emailWizard.step3manual.prefilled',
                      "We've pre-filled settings for {{provider}}. Just add your password.",
                      { provider: detectedProvider.display_name }
                    )
                  : t(
                      'emailWizard.step3manual.description',
                      'Enter your email server settings below.'
                    )}
              </p>
            </div>

            {detectedProvider?.notes && (
              <div className="p-3 bg-yellow-50 dark:bg-yellow-900/20 rounded-lg border border-yellow-200 dark:border-yellow-800">
                <p className="text-sm text-yellow-800 dark:text-yellow-300">
                  <AlertCircle className="w-4 h-4 inline mr-1" />
                  {detectedProvider.notes}
                </p>
              </div>
            )}

            {/* IMAP Settings */}
            <div className="border border-gray-200 dark:border-gray-700 rounded-lg p-4">
              <h4 className="font-medium text-gray-900 dark:text-white mb-4 flex items-center gap-2">
                <Server className="w-4 h-4" />
                {t('emailWizard.imap.title', 'IMAP (Incoming Mail)')}
              </h4>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    {t('emailWizard.host', 'Host')}
                  </label>
                  <input
                    type="text"
                    value={manualConfig.imap_host}
                    onChange={(e) =>
                      setManualConfig((prev) => ({ ...prev, imap_host: e.target.value }))
                    }
                    placeholder="imap.example.com"
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                  />
                </div>

                <div className="grid grid-cols-2 gap-2">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                      {t('emailWizard.port', 'Port')}
                    </label>
                    <input
                      type="number"
                      value={manualConfig.imap_port}
                      onChange={(e) =>
                        setManualConfig((prev) => ({
                          ...prev,
                          imap_port: parseInt(e.target.value) || 993,
                        }))
                      }
                      className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                    />
                  </div>
                  <div className="flex items-end pb-2">
                    <label className="flex items-center gap-2">
                      <input
                        type="checkbox"
                        checked={manualConfig.imap_use_ssl}
                        onChange={(e) =>
                          setManualConfig((prev) => ({ ...prev, imap_use_ssl: e.target.checked }))
                        }
                        className="rounded border-gray-300 text-blue-600"
                      />
                      <span className="text-sm text-gray-700 dark:text-gray-300">SSL</span>
                    </label>
                  </div>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    {t('emailWizard.username', 'Username')}
                  </label>
                  <input
                    type="text"
                    value={manualConfig.imap_username}
                    onChange={(e) =>
                      setManualConfig((prev) => ({ ...prev, imap_username: e.target.value }))
                    }
                    placeholder={email}
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    {t('emailWizard.password', 'Password / App Password')}
                  </label>
                  <div className="relative">
                    <input
                      type={showImapPassword ? 'text' : 'password'}
                      value={manualConfig.imap_password}
                      onChange={(e) =>
                        setManualConfig((prev) => ({ ...prev, imap_password: e.target.value }))
                      }
                      placeholder="Enter password"
                      className="w-full px-3 py-2 pr-10 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                    />
                    <button
                      type="button"
                      onClick={() => setShowImapPassword(!showImapPassword)}
                      className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400"
                    >
                      {showImapPassword ? (
                        <EyeOff className="w-4 h-4" />
                      ) : (
                        <Eye className="w-4 h-4" />
                      )}
                    </button>
                  </div>
                </div>
              </div>
            </div>

            {/* SMTP Settings */}
            <div className="border border-gray-200 dark:border-gray-700 rounded-lg p-4">
              <h4 className="font-medium text-gray-900 dark:text-white mb-4 flex items-center gap-2">
                <Server className="w-4 h-4" />
                {t('emailWizard.smtp.title', 'SMTP (Outgoing Mail)')}
              </h4>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    {t('emailWizard.host', 'Host')}
                  </label>
                  <input
                    type="text"
                    value={manualConfig.smtp_host}
                    onChange={(e) =>
                      setManualConfig((prev) => ({ ...prev, smtp_host: e.target.value }))
                    }
                    placeholder="smtp.example.com"
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                  />
                </div>

                <div className="grid grid-cols-3 gap-2">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                      {t('emailWizard.port', 'Port')}
                    </label>
                    <input
                      type="number"
                      value={manualConfig.smtp_port}
                      onChange={(e) =>
                        setManualConfig((prev) => ({
                          ...prev,
                          smtp_port: parseInt(e.target.value) || 587,
                        }))
                      }
                      className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                    />
                  </div>
                  <div className="flex items-end pb-2">
                    <label className="flex items-center gap-2">
                      <input
                        type="checkbox"
                        checked={manualConfig.smtp_use_tls}
                        onChange={(e) =>
                          setManualConfig((prev) => ({
                            ...prev,
                            smtp_use_tls: e.target.checked,
                            smtp_use_ssl: e.target.checked ? false : prev.smtp_use_ssl,
                          }))
                        }
                        className="rounded border-gray-300 text-blue-600"
                      />
                      <span className="text-sm text-gray-700 dark:text-gray-300">TLS</span>
                    </label>
                  </div>
                  <div className="flex items-end pb-2">
                    <label className="flex items-center gap-2">
                      <input
                        type="checkbox"
                        checked={manualConfig.smtp_use_ssl}
                        onChange={(e) =>
                          setManualConfig((prev) => ({
                            ...prev,
                            smtp_use_ssl: e.target.checked,
                            smtp_use_tls: e.target.checked ? false : prev.smtp_use_tls,
                          }))
                        }
                        className="rounded border-gray-300 text-blue-600"
                      />
                      <span className="text-sm text-gray-700 dark:text-gray-300">SSL</span>
                    </label>
                  </div>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    {t('emailWizard.username', 'Username')}
                  </label>
                  <input
                    type="text"
                    value={manualConfig.smtp_username}
                    onChange={(e) =>
                      setManualConfig((prev) => ({ ...prev, smtp_username: e.target.value }))
                    }
                    placeholder={email}
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    {t('emailWizard.password', 'Password / App Password')}
                  </label>
                  <div className="relative">
                    <input
                      type={showSmtpPassword ? 'text' : 'password'}
                      value={manualConfig.smtp_password}
                      onChange={(e) =>
                        setManualConfig((prev) => ({ ...prev, smtp_password: e.target.value }))
                      }
                      placeholder="Enter password"
                      className="w-full px-3 py-2 pr-10 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                    />
                    <button
                      type="button"
                      onClick={() => setShowSmtpPassword(!showSmtpPassword)}
                      className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400"
                    >
                      {showSmtpPassword ? (
                        <EyeOff className="w-4 h-4" />
                      ) : (
                        <Eye className="w-4 h-4" />
                      )}
                    </button>
                  </div>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    {t('emailWizard.fromEmail', 'From Email')}
                  </label>
                  <input
                    type="email"
                    value={manualConfig.smtp_from_email}
                    onChange={(e) =>
                      setManualConfig((prev) => ({ ...prev, smtp_from_email: e.target.value }))
                    }
                    placeholder={email}
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    {t('emailWizard.fromName', 'From Name')}
                  </label>
                  <input
                    type="text"
                    value={manualConfig.smtp_from_name}
                    onChange={(e) =>
                      setManualConfig((prev) => ({ ...prev, smtp_from_name: e.target.value }))
                    }
                    placeholder="Support Team"
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                  />
                </div>
              </div>
            </div>

            {/* Error display */}
            {updateMutation.isError && (
              <div className="p-3 bg-red-50 dark:bg-red-900/20 rounded-lg">
                <p className="text-sm text-red-700 dark:text-red-400 flex items-center gap-2">
                  <AlertCircle className="w-4 h-4" />
                  {t('emailWizard.saveError', 'Failed to save settings. Please try again.')}
                </p>
              </div>
            )}

            <div className="flex items-center justify-between">
              <button
                onClick={goBack}
                className="flex items-center gap-2 text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white"
              >
                <ArrowLeft className="w-4 h-4" />
                {t('emailWizard.back', 'Back')}
              </button>

              <button
                onClick={handleSaveManualConfig}
                disabled={
                  updateMutation.isPending ||
                  !manualConfig.imap_host ||
                  !manualConfig.imap_password ||
                  !manualConfig.smtp_host ||
                  !manualConfig.smtp_password
                }
                className="flex items-center gap-2 px-6 py-2 bg-blue-600 text-white font-medium rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
              >
                {updateMutation.isPending ? (
                  <>
                    <Loader2 className="w-4 h-4 animate-spin" />
                    {t('emailWizard.saving', 'Saving...')}
                  </>
                ) : (
                  <>
                    {t('emailWizard.saveAndTest', 'Save & Test')}
                    <ArrowRight className="w-4 h-4" />
                  </>
                )}
              </button>
            </div>
          </div>
        )}

        {/* Step 4: Test Connections */}
        {currentStep === 'test' && (
          <div className="space-y-6">
            <div>
              <h3 className="text-lg font-medium text-gray-900 dark:text-white mb-2">
                {t('emailWizard.step4.title', 'Test your email connections')}
              </h3>
              <p className="text-sm text-gray-500 dark:text-gray-400">
                {t(
                  'emailWizard.step4.description',
                  "Let's verify that both incoming and outgoing email are working correctly."
                )}
              </p>
            </div>

            <div className="space-y-4">
              {/* IMAP Test Result */}
              <div className="p-4 border border-gray-200 dark:border-gray-700 rounded-lg">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-3">
                    <Server className="w-5 h-5 text-gray-400" />
                    <div>
                      <p className="font-medium text-gray-900 dark:text-white">
                        {t('emailWizard.test.imap', 'IMAP Connection')}
                      </p>
                      <p className="text-sm text-gray-500">
                        {t('emailWizard.test.imapDesc', 'Incoming mail server')}
                      </p>
                    </div>
                  </div>
                  <div>
                    {testImapMutation.isPending && (
                      <Loader2 className="w-5 h-5 animate-spin text-blue-600" />
                    )}
                    {testImapMutation.isSuccess && testImapMutation.data?.success && (
                      <CheckCircle className="w-5 h-5 text-green-500" />
                    )}
                    {testImapMutation.isSuccess && !testImapMutation.data?.success && (
                      <AlertCircle className="w-5 h-5 text-red-500" />
                    )}
                    {testImapMutation.isError && (
                      <AlertCircle className="w-5 h-5 text-red-500" />
                    )}
                  </div>
                </div>
                {testImapMutation.isSuccess && (
                  <p
                    className={`mt-2 text-sm ${testImapMutation.data?.success ? 'text-green-600' : 'text-red-600'}`}
                  >
                    {testImapMutation.data?.message}
                  </p>
                )}
              </div>

              {/* SMTP Test Result */}
              <div className="p-4 border border-gray-200 dark:border-gray-700 rounded-lg">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-3">
                    <Server className="w-5 h-5 text-gray-400" />
                    <div>
                      <p className="font-medium text-gray-900 dark:text-white">
                        {t('emailWizard.test.smtp', 'SMTP Connection')}
                      </p>
                      <p className="text-sm text-gray-500">
                        {t('emailWizard.test.smtpDesc', 'Outgoing mail server')}
                      </p>
                    </div>
                  </div>
                  <div>
                    {testSmtpMutation.isPending && (
                      <Loader2 className="w-5 h-5 animate-spin text-blue-600" />
                    )}
                    {testSmtpMutation.isSuccess && testSmtpMutation.data?.success && (
                      <CheckCircle className="w-5 h-5 text-green-500" />
                    )}
                    {testSmtpMutation.isSuccess && !testSmtpMutation.data?.success && (
                      <AlertCircle className="w-5 h-5 text-red-500" />
                    )}
                    {testSmtpMutation.isError && (
                      <AlertCircle className="w-5 h-5 text-red-500" />
                    )}
                  </div>
                </div>
                {testSmtpMutation.isSuccess && (
                  <p
                    className={`mt-2 text-sm ${testSmtpMutation.data?.success ? 'text-green-600' : 'text-red-600'}`}
                  >
                    {testSmtpMutation.data?.message}
                  </p>
                )}
              </div>
            </div>

            <div className="flex items-center justify-between">
              <button
                onClick={goBack}
                className="flex items-center gap-2 text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white"
              >
                <ArrowLeft className="w-4 h-4" />
                {t('emailWizard.back', 'Back')}
              </button>

              <div className="flex gap-3">
                <button
                  onClick={handleTestConnections}
                  disabled={testImapMutation.isPending || testSmtpMutation.isPending}
                  className="flex items-center gap-2 px-4 py-2 text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 font-medium rounded-lg hover:bg-gray-50 dark:hover:bg-gray-600 disabled:opacity-50"
                >
                  {testImapMutation.isPending || testSmtpMutation.isPending ? (
                    <>
                      <Loader2 className="w-4 h-4 animate-spin" />
                      {t('emailWizard.testing', 'Testing...')}
                    </>
                  ) : (
                    <>
                      <Settings className="w-4 h-4" />
                      {t('emailWizard.runTests', 'Run Tests')}
                    </>
                  )}
                </button>

                <button
                  onClick={() => {
                    setCurrentStep('complete');
                    onComplete?.();
                  }}
                  disabled={
                    !testImapMutation.data?.success || !testSmtpMutation.data?.success
                  }
                  className="flex items-center gap-2 px-6 py-2 bg-green-600 text-white font-medium rounded-lg hover:bg-green-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                >
                  <CheckCircle className="w-4 h-4" />
                  {t('emailWizard.complete', 'Complete Setup')}
                </button>
              </div>
            </div>
          </div>
        )}

        {/* Step 5: Complete */}
        {currentStep === 'complete' && (
          <div className="text-center py-8">
            <div className="w-16 h-16 bg-green-100 dark:bg-green-900/30 rounded-full flex items-center justify-center mx-auto mb-4">
              <CheckCircle className="w-8 h-8 text-green-600 dark:text-green-400" />
            </div>
            <h3 className="text-xl font-medium text-gray-900 dark:text-white mb-2">
              {t('emailWizard.success.title', 'Email configured successfully!')}
            </h3>
            <p className="text-gray-500 dark:text-gray-400 mb-6">
              {t(
                'emailWizard.success.description',
                'Your support email is now connected and ready to process incoming messages.'
              )}
            </p>
            <button
              onClick={onComplete}
              className="px-6 py-2 bg-blue-600 text-white font-medium rounded-lg hover:bg-blue-700 transition-colors"
            >
              {t('emailWizard.done', 'Done')}
            </button>
          </div>
        )}
      </div>
    </div>
  );
};

export default EmailConfigWizard;
