'use client';
import { useState, useEffect } from 'react';
import api from '@/lib/api';
import toast from 'react-hot-toast';
import { Save, MailCheck, Loader2 } from 'lucide-react';

type Field = { key: string; label: string; type: string; options?: string[]; placeholder?: string; hint?: string };

const GROUPS: { title: string; description?: string; fields: Field[] }[] = [
  {
    title: 'General',
    fields: [
      { key: 'site_name', label: 'Site Name', type: 'text' },
      { key: 'site_description', label: 'Site Description', type: 'textarea' },
      { key: 'site_url', label: 'Site URL', type: 'text', placeholder: 'https://…' },
      { key: 'admin_email', label: 'Admin Email', type: 'email' },
      { key: 'articles_per_page', label: 'Articles Per Page', type: 'number' },
    ],
  },
  {
    title: 'Content & Access',
    fields: [
      { key: 'allow_comments', label: 'Allow Comments', type: 'select', options: ['true', 'false'] },
      { key: 'comment_moderation', label: 'Comment Moderation', type: 'select', options: ['true', 'false'] },
      { key: 'allow_registration', label: 'Allow Registration', type: 'select', options: ['true', 'false'] },
      { key: 'maintenance_mode', label: 'Maintenance Mode', type: 'select', options: ['false', 'true'] },
    ],
  },
  {
    title: 'Email (SMTP)',
    description:
      'Set your outgoing mail credentials here. Once saved and verified, the newsletter and other emails send for real. Leave the password blank to keep the one already saved. For Gmail, use an App Password (not your normal password).',
    fields: [
      { key: 'smtp_host', label: 'SMTP Host', type: 'text', placeholder: 'smtp.gmail.com' },
      { key: 'smtp_port', label: 'SMTP Port', type: 'number', placeholder: '587', hint: '587 (TLS) or 465 (SSL)' },
      { key: 'smtp_secure', label: 'Use SSL (port 465)', type: 'select', options: ['false', 'true'] },
      { key: 'smtp_user', label: 'SMTP Username', type: 'text', placeholder: 'you@gmail.com' },
      { key: 'smtp_pass', label: 'SMTP Password', type: 'password', placeholder: '••••••••', hint: 'Stored securely; never shown back.' },
      { key: 'mail_from', label: 'From Address', type: 'text', placeholder: 'The Daily Tribune <no-reply@yourdomain.com>' },
    ],
  },
  {
    title: 'Social Links',
    fields: [
      { key: 'twitter_url', label: 'Twitter / X URL', type: 'text' },
      { key: 'facebook_url', label: 'Facebook URL', type: 'text' },
      { key: 'instagram_url', label: 'Instagram URL', type: 'text' },
    ],
  },
];

const inputCls =
  'w-full rounded-md border border-surface bg-surface px-3 py-2 text-sm text-body outline-none transition focus:border-brand-500 focus:ring-2 focus:ring-brand-500/20';

export default function AdminSettings() {
  const [settings, setSettings] = useState<Record<string, string>>({});
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [saving, setSaving] = useState(false);
  const [testing, setTesting] = useState(false);

  function load() {
    setLoading(true);
    setError('');
    api.get('/settings/admin')
      .then((r) => setSettings(r.data.data || r.data || {}))
      .catch(() => setError('Failed to load settings.'))
      .finally(() => setLoading(false));
  }
  useEffect(load, []);

  const handleChange = (key: string, value: string) => setSettings((s) => ({ ...s, [key]: value }));

  const handleSave = async () => {
    setSaving(true);
    try {
      await api.put('/settings', settings);
      toast.success('Settings saved');
      load();
    } catch {
      toast.error('Save failed');
    } finally {
      setSaving(false);
    }
  };

  const testEmail = async () => {
    setTesting(true);
    try {
      const r = await api.post('/settings/test-email');
      toast.success(r.data.message || 'SMTP connection succeeded');
    } catch (e: any) {
      toast.error(e.response?.data?.message || 'SMTP test failed. Save your credentials first.');
    } finally {
      setTesting(false);
    }
  };

  if (loading) {
    return (
      <div className="grid h-64 place-items-center text-muted">
        <span className="h-8 w-8 animate-spin rounded-full border-2 border-brand-500 border-t-transparent" />
      </div>
    );
  }
  if (error) {
    return (
      <div className="rounded-card border border-red-200 bg-red-50 p-6 text-sm text-red-700 dark:border-red-500/30 dark:bg-red-500/10">
        {error} <button onClick={load} className="ml-2 font-semibold underline">Retry</button>
      </div>
    );
  }

  return (
    <div className="max-w-2xl space-y-6">
      <div className="flex items-center justify-between gap-3">
        <div>
          <h1 className="font-serif text-2xl font-bold text-body">Settings</h1>
          <p className="text-sm text-muted">Configure how your publication behaves.</p>
        </div>
        <button
          onClick={handleSave}
          disabled={saving}
          className="inline-flex items-center gap-2 rounded-lg bg-brand-900 px-4 py-2 text-sm font-semibold text-white transition hover:bg-brand-800 disabled:opacity-60"
        >
          {saving ? <Loader2 size={16} className="animate-spin" /> : <Save size={16} />}
          {saving ? 'Saving…' : 'Save Settings'}
        </button>
      </div>

      {GROUPS.map((group) => (
        <section key={group.title} className="rounded-card border border-surface bg-surface p-6">
          <h2 className="font-serif text-lg font-bold text-body">{group.title}</h2>
          {group.description && <p className="mb-4 mt-1 text-xs leading-relaxed text-muted">{group.description}</p>}
          <div className={group.description ? 'space-y-4' : 'mt-4 space-y-4'}>
            {group.fields.map(({ key, label, type, options, placeholder, hint }) => (
              <div key={key}>
                <label className="mb-1 block text-xs font-semibold uppercase tracking-wide text-muted">{label}</label>
                {type === 'textarea' ? (
                  <textarea
                    value={settings[key] || ''}
                    onChange={(e) => handleChange(key, e.target.value)}
                    rows={3}
                    placeholder={placeholder}
                    className={`${inputCls} resize-none`}
                  />
                ) : type === 'select' ? (
                  <select value={settings[key] || options?.[0] || ''} onChange={(e) => handleChange(key, e.target.value)} className={inputCls}>
                    {options?.map((o) => (
                      <option key={o} value={o}>{o === 'true' ? 'Enabled' : o === 'false' ? 'Disabled' : o}</option>
                    ))}
                  </select>
                ) : (
                  <input
                    type={type}
                    value={settings[key] || ''}
                    onChange={(e) => handleChange(key, e.target.value)}
                    placeholder={placeholder}
                    autoComplete={type === 'password' ? 'new-password' : undefined}
                    className={inputCls}
                  />
                )}
                {hint && <p className="mt-1 text-xs text-muted">{hint}</p>}
              </div>
            ))}
            {group.title === 'Email (SMTP)' && (
              <button
                onClick={testEmail}
                disabled={testing}
                className="inline-flex items-center gap-2 rounded-md border border-surface px-4 py-2 text-sm font-semibold text-body transition hover:bg-surface-sunken disabled:opacity-60"
              >
                {testing ? <Loader2 size={15} className="animate-spin" /> : <MailCheck size={15} />}
                {testing ? 'Testing…' : 'Test connection'}
              </button>
            )}
          </div>
        </section>
      ))}
    </div>
  );
}
