'use client';

import { useEffect, useState } from 'react';
import { Loader2, Save, Mail, Send } from 'lucide-react';
import { toast } from 'sonner';

interface SmtpView {
  host: string;
  port: number;
  user: string;
  from: string;
  secure: boolean;
  passSet?: boolean;
}
interface AdminBrand { name: string; url: string; logoUrl?: string }

const DEFAULTS: SmtpView = { host: '', port: 587, user: '', from: '', secure: false };

export default function AdminEmailSettingsPage() {
  const [smtp, setSmtp] = useState<SmtpView>(DEFAULTS);
  const [pass, setPass] = useState('');
  const [brand, setBrand] = useState<AdminBrand>({ name: 'diploy', url: 'https://diploy.in', logoUrl: '' });
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [testTo, setTestTo] = useState('');
  const [testing, setTesting] = useState(false);

  useEffect(() => {
    fetch('/api/admin/email/smtp', { credentials: 'include' })
      .then(r => r.json())
      .then((d) => {
        if (d?.smtp) setSmtp({ ...DEFAULTS, ...d.smtp });
        if (d?.adminBrand) setBrand(d.adminBrand);
      })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  const save = async () => {
    setSaving(true);
    try {
      const body: Record<string, unknown> = {
        host: smtp.host, port: smtp.port, user: smtp.user, from: smtp.from, secure: !!smtp.secure,
        adminBrandName: brand.name, adminBrandUrl: brand.url, adminBrandLogoUrl: brand.logoUrl || '',
      };
      if (pass) body.pass = pass;
      const r = await fetch('/api/admin/email/smtp', {
        method: 'POST', credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body),
      });
      if (!r.ok) throw new Error((await r.json()).error || 'Save failed');
      toast.success('SMTP settings saved');
      setPass('');
      setSmtp((s) => ({ ...s, passSet: true }));
    } catch (e) {
      toast.error(e instanceof Error ? e.message : 'Save failed');
    } finally { setSaving(false); }
  };

  const sendTest = async () => {
    if (!testTo) return toast.error('Enter a recipient email');
    setTesting(true);
    try {
      const r = await fetch('/api/admin/email/smtp', {
        method: 'PUT', credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ to: testTo }),
      });
      if (!r.ok) throw new Error((await r.json()).error || 'Test failed');
      toast.success('Test email sent');
    } catch (e) { toast.error(e instanceof Error ? e.message : 'Test failed'); }
    finally { setTesting(false); }
  };

  if (loading) return <div className="p-8 flex justify-center"><Loader2 className="animate-spin" /></div>;

  return (
    <div className="p-6 max-w-3xl mx-auto space-y-6">
      <div className="flex items-center gap-3">
        <Mail className="text-orange-500" />
        <h1 className="text-2xl font-semibold">Platform Email (SMTP)</h1>
      </div>
      <p className="text-sm text-gray-600">These credentials are used to send branded emails when a tenant has not configured their own SMTP. The password is encrypted at rest.</p>

      <div className="bg-white rounded-lg border p-6 space-y-4">
        <div className="grid grid-cols-2 gap-4">
          <Field label="SMTP host" value={smtp.host} onChange={(v) => setSmtp({ ...smtp, host: v })} placeholder="smtp.sendgrid.net" />
          <Field label="Port" type="number" value={String(smtp.port)} onChange={(v) => setSmtp({ ...smtp, port: Number(v) || 587 })} />
        </div>
        <label className="flex items-center gap-2 text-sm">
          <input type="checkbox" checked={smtp.secure} onChange={(e) => setSmtp({ ...smtp, secure: e.target.checked })} />
          Use TLS (secure)
        </label>
        <Field label="Username" value={smtp.user} onChange={(v) => setSmtp({ ...smtp, user: v })} />
        <Field label={`Password ${smtp.passSet ? '(stored — leave blank to keep)' : ''}`} type="password"
               value={pass} onChange={setPass} placeholder={smtp.passSet ? '••••••••' : ''} />
        <Field label='From (e.g. "diploy <no-reply@diploy.in>")' value={smtp.from} onChange={(v) => setSmtp({ ...smtp, from: v })} placeholder="diploy <no-reply@diploy.in>" />

        <div className="border-t pt-4 grid grid-cols-2 gap-4">
          <Field label="Admin brand name (footer)" value={brand.name} onChange={(v) => setBrand({ ...brand, name: v })} placeholder="diploy" />
          <Field label="Admin brand URL" value={brand.url} onChange={(v) => setBrand({ ...brand, url: v })} placeholder="https://diploy.in" />
          <div className="col-span-2">
            <Field label="Admin brand logo URL (used in email footer)" value={brand.logoUrl || ''} onChange={(v) => setBrand({ ...brand, logoUrl: v })} placeholder="https://diploy.in/logo.png" />
          </div>
        </div>

        <div className="flex justify-end">
          <button disabled={saving} onClick={save} className="inline-flex items-center gap-2 bg-orange-500 hover:bg-orange-600 text-white px-4 py-2 rounded-md disabled:opacity-50">
            {saving ? <Loader2 className="animate-spin" size={16} /> : <Save size={16} />} Save
          </button>
        </div>
      </div>

      <div className="bg-white rounded-lg border p-6 space-y-3">
        <h2 className="font-semibold flex items-center gap-2"><Send size={18} /> Send a test email</h2>
        <p className="text-xs text-gray-500">Sends the signup OTP template (with sample variables) to the address below.</p>
        <div className="flex gap-2">
          <input className="flex-1 border rounded-md px-3 py-2" type="email" placeholder="you@example.com"
                 value={testTo} onChange={(e) => setTestTo(e.target.value)} />
          <button disabled={testing} onClick={sendTest} className="bg-gray-900 text-white px-4 py-2 rounded-md disabled:opacity-50">
            {testing ? 'Sending…' : 'Send test'}
          </button>
        </div>
      </div>
    </div>
  );
}

function Field({ label, value, onChange, type = 'text', placeholder }: {
  label: string; value: string; onChange: (v: string) => void; type?: string; placeholder?: string;
}) {
  return (
    <label className="block">
      <span className="block text-xs font-medium text-gray-600 mb-1">{label}</span>
      <input className="w-full border rounded-md px-3 py-2" type={type} value={value}
             placeholder={placeholder} onChange={(e) => onChange(e.target.value)} />
    </label>
  );
}
