"use client";
// Admin Settings page – view & edit SMTP configuration and send test email
import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';

interface Settings {
  host: string;
  port: number;
  secure: boolean;
  user: string;
  pass: string;
}

export default function SettingsPage() {
  const [settings, setSettings] = useState<Settings | null>(null);
  const [loading, setLoading] = useState(true);
  const [message, setMessage] = useState('');
  const router = useRouter();

  // Load current settings
  useEffect(() => {
    fetch('/api/admin/smtp-settings')
      .then((res) => res.json())
      .then((data) => {
        if (data.settings) setSettings(data.settings as Settings);
        else setMessage('Failed to load settings');
      })
      .catch(() => setMessage('Failed to load settings'))
      .finally(() => setLoading(false));
  }, []);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value, type, checked } = e.target;
    setSettings((prev) =>
      prev && {
        ...prev,
        [name]: type === 'checkbox' ? checked : name === 'port' ? Number(value) : value,
      }
    );
  };

  const handleSave = async (e: React.FormEvent) => {
    e.preventDefault();
    setMessage('');
    const res = await fetch('/api/admin/smtp-settings', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(settings),
    });
    const data = await res.json();
    if (res.ok) setMessage('Settings saved');
    else setMessage(data.error || 'Error saving settings');
  };

  const handleTestEmail = async () => {
    setMessage('');
    const testPayload = {
      to: settings?.user || '', // send to the configured user address
      subject: 'Test Email from Webshop Admin',
      text: 'This is a test email to verify SMTP configuration.',
    };
    const res = await fetch('/api/admin/send-test-email', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(testPayload),
    });
    const data = await res.json();
    if (res.ok) setMessage('Test email sent successfully');
    else setMessage(data.error || 'Failed to send test email');
  };

  if (loading) return <div className="p-8">Loading…</div>;

  return (
    <div className="max-w-2xl mx-auto p-8 bg-black/30 backdrop-blur-xl rounded-lg text-white">
      <h1 className="text-2xl font-bold mb-6">SMTP‑Einstellungen</h1>
      {message && <p className="mb-4 text-yellow-300">{message}</p>}
      <form onSubmit={handleSave} className="space-y-4">
        <label className="flex flex-col">
          Host
          <input
            name="host"
            type="text"
            required
            value={settings?.host ?? ''}
            onChange={handleChange}
            className="mt-1 p-2 rounded bg-black/20 border border-white/20"
          />
        </label>
        <label className="flex flex-col">
          Port
          <input
            name="port"
            type="number"
            required
            value={settings?.port ?? ''}
            onChange={handleChange}
            className="mt-1 p-2 rounded bg-black/20 border border-white/20"
          />
        </label>
        <label className="inline-flex items-center space-x-2">
          <input
            name="secure"
            type="checkbox"
            checked={settings?.secure ?? false}
            onChange={handleChange}
            className="rounded"
          />
          <span>SSL / TLS (secure)</span>
        </label>
        <label className="flex flex-col">
          Benutzer (SMTP‑User)
          <input
            name="user"
            type="email"
            required
            value={settings?.user ?? ''}
            onChange={handleChange}
            className="mt-1 p-2 rounded bg-black/20 border border-white/20"
          />
        </label>
        <label className="flex flex-col">
          Passwort
          <input
            name="pass"
            type="password"
            required
            value={settings?.pass ?? ''}
            onChange={handleChange}
            className="mt-1 p-2 rounded bg-black/20 border border-white/20"
          />
        </label>
        <div className="flex space-x-4 mt-4">
          <button
            type="submit"
            className="px-4 py-2 bg-primary rounded hover:bg-primary/80 transition"
          >
            Speichern
          </button>
          <button
            type="button"
            onClick={handleTestEmail}
            className="px-4 py-2 bg-green-600 rounded hover:bg-green-500 transition"
          >
            Test‑Mail senden
          </button>
        </div>
      </form>
    </div>
  );
}
