'use client';

import { useState } from 'react';
import { TabProps } from '../types';
import toast from 'react-hot-toast';
import { getApiErrorMessage } from '@/lib/utils/apiError';

export function SMTPTab({ data, onChange, errors, canUpdate }: TabProps) {
  const [testing, setTesting] = useState(false);
  const [testStatus, setTestStatus] = useState<'idle' | 'success' | 'error'>('idle');
  const [testMessage, setTestMessage] = useState('');

  // ─── Test SMTP Connection ──────────────────────────────────────────────────

  const testSMTPConnection = async () => {
    // Validate required fields
    if (!data.smtp_host) {
      toast.error('SMTP Host is required');
      return;
    }
    if (!data.smtp_port) {
      toast.error('SMTP Port is required');
      return;
    }
    if (!data.smtp_username) {
      toast.error('SMTP Username is required');
      return;
    }
    if (!data.smtp_password) {
      toast.error('SMTP Password is required');
      return;
    }
    if (!data.from_email) {
      toast.error('From Email is required');
      return;
    }

    setTesting(true);
    setTestStatus('idle');
    setTestMessage('');

    try {
      const res = await fetch('/api//settings/test-smtp', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          smtp_host: data.smtp_host,
          smtp_port: data.smtp_port,
          smtp_encryption: data.smtp_encryption,
          smtp_username: data.smtp_username,
          smtp_password: data.smtp_password,
          from_email: data.from_email,
          from_name: data.from_name,
        }),
      });

      const result = await res.json();

      if (result.success) {
        setTestStatus('success');
        setTestMessage(result.message || 'SMTP connection successful! Test email sent.');
        toast.success(result.message || 'SMTP connection successful!');
      } else {
        setTestStatus('error');
        setTestMessage(result.message || 'SMTP connection failed');
        toast.error(getApiErrorMessage(result, 'SMTP connection failed'));
        
        // Show detailed error
        if (result.details) {
          console.error('SMTP Error Details:', result.details);
          setTestMessage(prev => `${prev}\n\nDetails: ${result.details}`);
        }
      }
    } catch (error: unknown) {
      setTestStatus('error');
      const errorMsg = (error as Error).message || 'Network error while testing SMTP';
      setTestMessage(errorMsg);
      toast.error('Failed to test SMTP connection');
    } finally {
      setTesting(false);
    }
  };

  return (
    <div className="space-y-6">
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div>
          <label className="block text-sm font-medium mb-1.5" style={{ color: 'var(--color-text-secondary)' }}>
            SMTP Host *
          </label>
          <input
            type="text"
            value={data.smtp_host || ''}
            onChange={(e) => onChange('smtp_host', e.target.value)}
            disabled={!canUpdate}
            placeholder="smtp.gmail.com"
            className="w-full px-4 py-2.5 rounded-lg text-sm outline-none transition-all focus:ring-2 focus:ring-cta/20 disabled:opacity-50"
            style={{
              background: 'var(--color-surface-alt)',
              border: `1px solid ${errors.smtp_host ? 'var(--color-danger)' : 'var(--color-border)'}`,
              color: 'var(--color-text)',
            }}
          />
          {errors.smtp_host && (
            <p className="text-xs mt-1" style={{ color: 'var(--color-danger)' }}>{errors.smtp_host}</p>
          )}
          <p className="text-xs mt-1" style={{ color: 'var(--color-text-tertiary)' }}>
            SMTP server hostname (e.g., smtp.gmail.com)
          </p>
        </div>

        <div>
          <label className="block text-sm font-medium mb-1.5" style={{ color: 'var(--color-text-secondary)' }}>
            SMTP Port *
          </label>
          <input
            type="number"
            min="1"
            max="65535"
            value={data.smtp_port || 587}
            onChange={(e) => onChange('smtp_port', e.target.value)}
            disabled={!canUpdate}
            placeholder="587"
            className="w-full px-4 py-2.5 rounded-lg text-sm outline-none transition-all focus:ring-2 focus:ring-cta/20 disabled:opacity-50"
            style={{
              background: 'var(--color-surface-alt)',
              border: `1px solid ${errors.smtp_port ? 'var(--color-danger)' : 'var(--color-border)'}`,
              color: 'var(--color-text)',
            }}
          />
          {errors.smtp_port && (
            <p className="text-xs mt-1" style={{ color: 'var(--color-danger)' }}>{errors.smtp_port}</p>
          )}
          <p className="text-xs mt-1" style={{ color: 'var(--color-text-tertiary)' }}>
            Common: 587 (TLS), 465 (SSL), 25 (no encryption)
          </p>
        </div>

        <div>
          <label className="block text-sm font-medium mb-1.5" style={{ color: 'var(--color-text-secondary)' }}>
            SMTP Encryption
          </label>
          <select
            value={data.smtp_encryption || 'tls'}
            onChange={(e) => onChange('smtp_encryption', e.target.value)}
            disabled={!canUpdate}
            className="w-full px-4 py-2.5 rounded-lg text-sm outline-none transition-all focus:ring-2 focus:ring-cta/20 disabled:opacity-50"
            style={{
              background: 'var(--color-surface-alt)',
              border: '1px solid var(--color-border)',
              color: 'var(--color-text)',
            }}
          >
            <option value="tls">TLS (Recommended)</option>
            <option value="ssl">SSL</option>
            <option value="none">None (Not Recommended)</option>
          </select>
          <p className="text-xs mt-1" style={{ color: 'var(--color-text-tertiary)' }}>
            Encryption method for secure email transmission
          </p>
        </div>

        <div>
          <label className="block text-sm font-medium mb-1.5" style={{ color: 'var(--color-text-secondary)' }}>
            SMTP Username *
          </label>
          <input
            type="text"
            value={data.smtp_username || ''}
            onChange={(e) => onChange('smtp_username', e.target.value)}
            disabled={!canUpdate}
            placeholder="your-email@gmail.com"
            className="w-full px-4 py-2.5 rounded-lg text-sm outline-none transition-all focus:ring-2 focus:ring-cta/20 disabled:opacity-50"
            style={{
              background: 'var(--color-surface-alt)',
              border: `1px solid ${errors.smtp_username ? 'var(--color-danger)' : 'var(--color-border)'}`,
              color: 'var(--color-text)',
            }}
          />
          {errors.smtp_username && (
            <p className="text-xs mt-1" style={{ color: 'var(--color-danger)' }}>{errors.smtp_username}</p>
          )}
          <p className="text-xs mt-1" style={{ color: 'var(--color-text-tertiary)' }}>
            Username for SMTP authentication
          </p>
        </div>

        <div>
          <label className="block text-sm font-medium mb-1.5" style={{ color: 'var(--color-text-secondary)' }}>
            SMTP Password *
          </label>
          <input
            type="password"
            value={data.smtp_password || ''}
            onChange={(e) => onChange('smtp_password', e.target.value)}
            disabled={!canUpdate}
            placeholder="••••••••"
            className="w-full px-4 py-2.5 rounded-lg text-sm outline-none transition-all focus:ring-2 focus:ring-cta/20 disabled:opacity-50"
            style={{
              background: 'var(--color-surface-alt)',
              border: `1px solid ${errors.smtp_password ? 'var(--color-danger)' : 'var(--color-border)'}`,
              color: 'var(--color-text)',
            }}
          />
          {errors.smtp_password && (
            <p className="text-xs mt-1" style={{ color: 'var(--color-danger)' }}>{errors.smtp_password}</p>
          )}
          <p className="text-xs mt-1" style={{ color: 'var(--color-text-tertiary)' }}>
            Leave empty to keep current password
          </p>
        </div>

        <div>
          <label className="block text-sm font-medium mb-1.5" style={{ color: 'var(--color-text-secondary)' }}>
            From Email *
          </label>
          <input
            type="email"
            value={data.from_email || ''}
            onChange={(e) => onChange('from_email', e.target.value)}
            disabled={!canUpdate}
            placeholder="noreply@yourdomain.com"
            className="w-full px-4 py-2.5 rounded-lg text-sm outline-none transition-all focus:ring-2 focus:ring-cta/20 disabled:opacity-50"
            style={{
              background: 'var(--color-surface-alt)',
              border: `1px solid ${errors.from_email ? 'var(--color-danger)' : 'var(--color-border)'}`,
              color: 'var(--color-text)',
            }}
          />
          {errors.from_email && (
            <p className="text-xs mt-1" style={{ color: 'var(--color-danger)' }}>{errors.from_email}</p>
          )}
          <p className="text-xs mt-1" style={{ color: 'var(--color-text-tertiary)' }}>
            Sender email address for all outgoing emails
          </p>
        </div>

        <div>
          <label className="block text-sm font-medium mb-1.5" style={{ color: 'var(--color-text-secondary)' }}>
            From Name
          </label>
          <input
            type="text"
            value={data.from_name || ''}
            onChange={(e) => onChange('from_name', e.target.value)}
            disabled={!canUpdate}
            placeholder="Your Store Name"
            className="w-full px-4 py-2.5 rounded-lg text-sm outline-none transition-all focus:ring-2 focus:ring-cta/20 disabled:opacity-50"
            style={{
              background: 'var(--color-surface-alt)',
              border: '1px solid var(--color-border)',
              color: 'var(--color-text)',
            }}
          />
          <p className="text-xs mt-1" style={{ color: 'var(--color-text-tertiary)' }}>
            Sender name displayed in recipient`s inbox
          </p>
        </div>
      </div>

      {/* ─── Test SMTP Button ────────────────────────────────────────────────── */}

      <div className="p-4 rounded-lg border" style={{ 
        borderColor: 'var(--color-border)',
        background: 'var(--color-surface-alt)'
      }}>
        <div className="flex items-center gap-4">
          <button
            type="button"
            onClick={testSMTPConnection}
            disabled={testing || !canUpdate}
            className="px-4 py-2 rounded-lg text-sm font-medium transition-all flex items-center gap-2 disabled:opacity-50 hover:opacity-90"
            style={{ 
              background: testStatus === 'success' 
                ? 'var(--color-success)' 
                : testStatus === 'error' 
                ? 'var(--color-danger)' 
                : 'var(--color-cta)',
              color: 'white'
            }}
          >
            {testing ? (
              <>
                <svg className="animate-spin h-4 w-4" viewBox="0 0 24 24">
                  <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none"/>
                  <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"/>
                </svg>
                Testing...
              </>
            ) : (
              <>
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
                </svg>
                Test SMTP Connection
              </>
            )}
          </button>

          {testStatus === 'success' && (
            <span className="text-sm font-medium flex items-center gap-1" style={{ color: 'var(--color-success)' }}>
              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
              Connected Successfully!
            </span>
          )}

          {testStatus === 'error' && (
            <span className="text-sm font-medium flex items-center gap-1" style={{ color: 'var(--color-danger)' }}>
              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
              Connection Failed
            </span>
          )}
        </div>

        {testMessage && (
          <div className={`mt-3 p-3 rounded-lg text-sm ${
            testStatus === 'success' 
              ? 'border' 
              : 'border'
          }`} style={{
            background: testStatus === 'success' 
              ? 'var(--color-success-light)' 
              : 'var(--color-danger-light)',
            borderColor: testStatus === 'success' 
              ? 'var(--color-success)' 
              : 'var(--color-danger)',
            color: testStatus === 'success' 
              ? 'var(--color-success-dark)' 
              : 'var(--color-danger)',
          }}>
            <pre className="whitespace-pre-wrap font-mono text-xs" style={{ color: 'inherit' }}>
              {testMessage}
            </pre>
          </div>
        )}

        <p className="text-xs mt-3" style={{ color: 'var(--color-text-tertiary)' }}>
          💡 Test your SMTP configuration by sending a test email. This will verify:
          <br />• Connection to SMTP server
          <br />• Authentication credentials
          <br />• Email sending capability
        </p>
      </div>

      {/* ─── Common SMTP Settings ──────────────────────────────────────────── */}

      <div className="p-4 rounded-lg" style={{ 
        background: 'var(--color-surface-alt)',
        border: '1px solid var(--color-border)'
      }}>
        <h4 className="text-sm font-medium mb-2" style={{ color: 'var(--color-text-secondary)' }}>
          📧 Common SMTP Settings:
        </h4>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-2 text-xs">
          <div className="p-2 rounded" style={{ background: 'var(--color-surface)' }}>
            <div className="font-medium" style={{ color: 'var(--color-text)' }}>Gmail</div>
            <div style={{ color: 'var(--color-text-tertiary)' }}>Host: smtp.gmail.com</div>
            <div style={{ color: 'var(--color-text-tertiary)' }}>Port: 587 | TLS</div>
            <div style={{ color: 'var(--color-text-tertiary)' }}>Auth: Yes (App Password required)</div>
          </div>
          <div className="p-2 rounded" style={{ background: 'var(--color-surface)' }}>
            <div className="font-medium" style={{ color: 'var(--color-text)' }}>Outlook</div>
            <div style={{ color: 'var(--color-text-tertiary)' }}>Host: smtp.office365.com</div>
            <div style={{ color: 'var(--color-text-tertiary)' }}>Port: 587 | TLS</div>
            <div style={{ color: 'var(--color-text-tertiary)' }}>Auth: Yes</div>
          </div>
          <div className="p-2 rounded" style={{ background: 'var(--color-surface)' }}>
            <div className="font-medium" style={{ color: 'var(--color-text)' }}>SendGrid</div>
            <div style={{ color: 'var(--color-text-tertiary)' }}>Host: smtp.sendgrid.net</div>
            <div style={{ color: 'var(--color-text-tertiary)' }}>Port: 587 | TLS</div>
            <div style={{ color: 'var(--color-text-tertiary)' }}>Auth: Yes</div>
          </div>
          <div className="p-2 rounded" style={{ background: 'var(--color-surface)' }}>
            <div className="font-medium" style={{ color: 'var(--color-text)' }}>Mailgun</div>
            <div style={{ color: 'var(--color-text-tertiary)' }}>Host: smtp.mailgun.org</div>
            <div style={{ color: 'var(--color-text-tertiary)' }}>Port: 587 | TLS</div>
            <div style={{ color: 'var(--color-text-tertiary)' }}>Auth: Yes</div>
          </div>
        </div>
      </div>
    </div>
  );
}