"use client";

import { useEffect, useState } from "react";
import { SMTPConfig, SMTPConfigResponse } from "@/lib/types/smtp";

export default function SettingsPage() {
  const [activeTab, setActiveTab] = useState<'smtp'>('smtp');
  const [config, setConfig] = useState<SMTPConfig>({
    host: '',
    port: 587,
    secure: false,
    auth: { user: '', pass: '' },
    from: { email: '', name: 'Location Tracker' },
    replyTo: '',
    timeout: 10000,
  });
  const [source, setSource] = useState<'database' | 'env'>('env');
  const [hasPassword, setHasPassword] = useState(false);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [testing, setTesting] = useState(false);
  const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);
  const [testEmail, setTestEmail] = useState('');
  const [showTestModal, setShowTestModal] = useState(false);

  // Fetch current config
  useEffect(() => {
    fetchConfig();
  }, []);

  const fetchConfig = async () => {
    try {
      const response = await fetch('/api/admin/settings/smtp');
      if (!response.ok) throw new Error('Failed to fetch config');

      const data: SMTPConfigResponse = await response.json();

      if (data.config) {
        setConfig(data.config);
        setHasPassword(data.config.auth.pass === '***');
      }
      setSource(data.source);
    } catch (error) {
      console.error('Failed to fetch SMTP config:', error);
      setMessage({ type: 'error', text: 'Failed to load SMTP configuration' });
    } finally {
      setLoading(false);
    }
  };

  // Save config
  const handleSave = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true);
    setMessage(null);

    try {
      const response = await fetch('/api/admin/settings/smtp', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ config }),
      });

      if (!response.ok) {
        const error = await response.json();
        throw new Error(error.error || 'Failed to save');
      }

      setMessage({ type: 'success', text: 'SMTP settings saved successfully' });
      setHasPassword(true);
      setSource('database');

      // Clear password field for security
      setConfig({ ...config, auth: { ...config.auth, pass: '' } });
    } catch (error: any) {
      setMessage({ type: 'error', text: error.message || 'Failed to save settings' });
    } finally {
      setSaving(false);
    }
  };

  // Reset to defaults
  const handleReset = async () => {
    if (!confirm('Reset to environment defaults? This will delete database configuration.')) {
      return;
    }

    try {
      const response = await fetch('/api/admin/settings/smtp', {
        method: 'DELETE',
      });

      if (!response.ok) throw new Error('Failed to reset');

      setMessage({ type: 'success', text: 'Reset to environment defaults' });
      await fetchConfig();
    } catch (error) {
      setMessage({ type: 'error', text: 'Failed to reset settings' });
    }
  };

  // Test connection
  const handleTest = async () => {
    if (!testEmail) {
      alert('Please enter a test email address');
      return;
    }

    setTesting(true);
    setMessage(null);

    try {
      const response = await fetch('/api/admin/settings/smtp/test', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          config: hasPassword ? undefined : config,
          testEmail,
        }),
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || 'Test failed');
      }

      setMessage({ type: 'success', text: data.message });
      setShowTestModal(false);
      setTestEmail('');
    } catch (error: any) {
      setMessage({ type: 'error', text: error.message || 'Connection test failed' });
    } finally {
      setTesting(false);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <p className="text-gray-600">Loading settings...</p>
      </div>
    );
  }

  return (
    <div className="space-y-8">
      {/* Hero Section with Gradient */}
      <div className="relative overflow-hidden rounded-2xl bg-gradient-to-br from-indigo-600 via-blue-700 to-purple-800 p-8 shadow-xl">
        <div className="absolute top-0 right-0 -mt-4 -mr-4 h-40 w-40 rounded-full bg-white/10 blur-3xl"></div>
        <div className="absolute bottom-0 left-0 -mb-4 -ml-4 h-40 w-40 rounded-full bg-white/10 blur-3xl"></div>
        <div className="relative">
          <h2 className="text-4xl font-bold text-white mb-2">Settings</h2>
          <p className="text-indigo-100 text-lg">Konfiguriere System-Einstellungen und Integrationen</p>
        </div>
      </div>

      {/* Tab Navigation */}
      <div className="bg-white rounded-2xl shadow-lg overflow-hidden">
        <nav className="flex gap-2 p-2 bg-gradient-to-r from-gray-50 to-slate-50">
          <button
            onClick={() => setActiveTab('smtp')}
            className={`px-6 py-3 rounded-xl font-semibold transition-all ${
              activeTab === 'smtp'
                ? 'bg-gradient-to-r from-blue-600 to-indigo-600 text-white shadow-lg'
                : 'text-gray-600 hover:bg-white hover:text-gray-900'
            }`}
          >
            📧 SMTP Settings
          </button>
        </nav>
      </div>

      {/* Status Message */}
      {message && (
        <div
          className={`p-5 rounded-xl shadow-lg flex items-center gap-3 ${
            message.type === 'success'
              ? 'bg-gradient-to-r from-green-50 to-emerald-50 border-2 border-green-200 text-green-800'
              : 'bg-gradient-to-r from-red-50 to-orange-50 border-2 border-red-200 text-red-800'
          }`}
        >
          <span className="text-2xl">{message.type === 'success' ? '✓' : '⚠️'}</span>
          <span className="font-semibold">{message.text}</span>
        </div>
      )}

      {/* Config Source Info */}
      <div className="bg-gradient-to-br from-blue-50 to-indigo-50 border-2 border-blue-200 rounded-2xl p-5 shadow-md">
        <div className="flex items-center gap-3">
          <div className="w-10 h-10 rounded-lg bg-gradient-to-br from-blue-600 to-indigo-600 flex items-center justify-center text-white text-xl">
            📊
          </div>
          <div>
            <p className="text-sm font-bold text-blue-900">Current Source</p>
            <p className="text-blue-700">{source === 'database' ? 'Database (Custom)' : 'Environment (.env)'}</p>
          </div>
        </div>
      </div>

      {/* SMTP Form */}
      <form onSubmit={handleSave} className="bg-white rounded-2xl shadow-lg p-8">
        <div className="space-y-4">
          {/* Host */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              SMTP Host *
            </label>
            <input
              type="text"
              required
              value={config.host}
              onChange={(e) => setConfig({ ...config, host: e.target.value.trim() })}
              placeholder="smtp.gmail.com"
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
            {config.host.includes('gmail') && (
              <p className="mt-1 text-xs text-blue-600">
                Gmail detected: Use App Password, not your regular password.
                <a
                  href="https://myaccount.google.com/apppasswords"
                  target="_blank"
                  rel="noopener noreferrer"
                  className="underline ml-1"
                >
                  Generate App Password
                </a>
              </p>
            )}
          </div>

          {/* Port and Secure */}
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Port *
              </label>
              <input
                type="number"
                required
                min="1"
                max="65535"
                value={config.port}
                onChange={(e) => setConfig({ ...config, port: parseInt(e.target.value) })}
                className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              />
            </div>
            <div className="flex items-end">
              <label className="flex items-center gap-2 cursor-pointer">
                <input
                  type="checkbox"
                  checked={config.secure}
                  onChange={(e) => setConfig({ ...config, secure: e.target.checked })}
                  className="w-4 h-4 text-blue-600"
                />
                <span className="text-sm text-gray-700">Use TLS/SSL</span>
              </label>
            </div>
          </div>

          {/* Username */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Username *
            </label>
            <input
              type="text"
              required
              value={config.auth.user}
              onChange={(e) => setConfig({ ...config, auth: { ...config.auth, user: e.target.value.trim() } })}
              placeholder="your-email@example.com"
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </div>

          {/* Password */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Password {hasPassword && '(leave empty to keep current)'}
              {config.host.includes('gmail') && (
                <span className="text-red-600 font-semibold ml-2">
                  - Use App Password!
                </span>
              )}
            </label>
            <input
              type="password"
              required={!hasPassword}
              value={config.auth.pass}
              onChange={(e) => setConfig({ ...config, auth: { ...config.auth, pass: e.target.value.trim() } })}
              placeholder={hasPassword ? '••••••••' : (config.host.includes('gmail') ? 'Gmail App Password (16 chars)' : 'your-password')}
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
            {config.host.includes('gmail') && (
              <p className="mt-1 text-xs text-amber-600">
                Do NOT use your Gmail password. Generate an App Password with 2FA enabled.
              </p>
            )}
          </div>

          {/* From Email */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              From Email *
            </label>
            <input
              type="email"
              required
              value={config.from.email}
              onChange={(e) => setConfig({ ...config, from: { ...config.from, email: e.target.value.trim() } })}
              placeholder="noreply@example.com"
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </div>

          {/* From Name */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              From Name *
            </label>
            <input
              type="text"
              required
              value={config.from.name}
              onChange={(e) => setConfig({ ...config, from: { ...config.from, name: e.target.value } })}
              placeholder="Location Tracker"
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </div>

          {/* Reply-To */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Reply-To (optional)
            </label>
            <input
              type="email"
              value={config.replyTo || ''}
              onChange={(e) => setConfig({ ...config, replyTo: e.target.value })}
              placeholder="support@example.com"
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </div>

          {/* Timeout */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Timeout (ms)
            </label>
            <input
              type="number"
              min="1000"
              value={config.timeout}
              onChange={(e) => setConfig({ ...config, timeout: parseInt(e.target.value) })}
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </div>
        </div>

        {/* Buttons */}
        <div className="flex gap-3 mt-8 pt-6 border-t border-gray-200">
          <button
            type="submit"
            disabled={saving}
            className="px-6 py-3 bg-gradient-to-r from-blue-600 to-indigo-600 text-white rounded-xl hover:from-blue-700 hover:to-indigo-700 disabled:from-gray-400 disabled:to-gray-500 font-semibold shadow-lg hover:shadow-xl transition-all"
          >
            {saving ? '⚙️ Saving...' : '💾 Save Settings'}
          </button>
          <button
            type="button"
            onClick={() => setShowTestModal(true)}
            className="px-6 py-3 bg-gradient-to-r from-green-500 to-emerald-600 text-white rounded-xl hover:from-green-600 hover:to-emerald-700 font-semibold shadow-lg hover:shadow-xl transition-all"
          >
            ✓ Test Connection
          </button>
          {source === 'database' && (
            <button
              type="button"
              onClick={handleReset}
              className="px-6 py-3 bg-gradient-to-r from-gray-100 to-slate-100 border-2 border-gray-300 rounded-xl hover:from-gray-200 hover:to-slate-200 font-semibold shadow-md hover:shadow-lg transition-all"
            >
              ↺ Reset to Defaults
            </button>
          )}
        </div>
      </form>

      {/* Test Email Modal */}
      {showTestModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg p-6 w-full max-w-md">
            <h3 className="text-xl font-bold mb-4">Test SMTP Connection</h3>
            <p className="text-sm text-gray-600 mb-4">
              Enter your email address to receive a test email.
            </p>
            <input
              type="email"
              value={testEmail}
              onChange={(e) => setTestEmail(e.target.value)}
              placeholder="your-email@example.com"
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 mb-4"
            />
            <div className="flex gap-3">
              <button
                onClick={() => {
                  setShowTestModal(false);
                  setTestEmail('');
                }}
                className="flex-1 px-4 py-2 border border-gray-300 rounded-md hover:bg-gray-100"
              >
                Cancel
              </button>
              <button
                onClick={handleTest}
                disabled={testing || !testEmail}
                className="flex-1 px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 disabled:bg-gray-400"
              >
                {testing ? 'Sending...' : 'Send Test Email'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
