
import { PasswordInput } from '@/components/PasswordInput';

import * as ActionIcons from '@/components/Icons';
import { api, isAdmin, isOwner, me } from '@/lib/api';
import { date, n } from '@/lib/format';
import { Card, Empty, Flash, Forbidden, Kpi, PageHeader, Pill, type SP } from '@/components/ui';
import { SubmitButton } from '@/components/Actions';
import { AlertIcon, CheckCircleIcon, MailIcon, SendIcon } from '@/components/Icons';
import { sendTestEmail, saveSmtp, removeSmtp } from '../../actions';

type Status = {
  configured: boolean;
  provider: string;
  smtp: { host: string | null; port: number; secure: boolean; user: string | null; passwordSet: boolean };
  from: { name: string; address: string | null };
  supportEmail: string | null;
  queue: 'redis' | 'inline';
  stats: { sent_24h: number; failed_24h: number; queued: number; last_sent: string | null; last_failed: string | null };
  recent: { id: number; toAddress: string; template: string; subject: string; status: string; attempts: number; lastError: string | null; createdAt: string; sentAt: string | null }[];
};

export default async function EmailPage({ searchParams }: { searchParams: SP }) {
  const sp = await searchParams;
  const viewer = await me();
  if (!isAdmin(viewer.role)) return <Forbidden what="email settings" />;
  const s = await api<Status>('/admin/email');
  return (
    <>
      <PageHeader
        title="Email"
        icon={<MailIcon className="h-5 w-5" />}
        description="Transactional email (password resets, invitations, security alerts) goes out over SMTP through a retrying queue. Save and test your SMTP connection here. App Passwords are encrypted and never displayed."
      />
      <Flash ok={sp.ok} err={sp.err} />

      {!s.configured && (
        <p className="mb-6 flex items-start gap-2 rounded-lg border border-brass/40 bg-brass-soft px-4 py-3 text-sm text-ink-2">
          <AlertIcon className="mt-0.5 h-4 w-4 text-brass" />
          <span>
            SMTP is not configured, so emails are not being delivered. Paste your Google App Password below. Your owner email and Gmail connection details are filled automatically. Gmail requires 2-Step Verification and an App Password.

          </span>
        </p>
      )}

      <div className="mb-6 grid grid-cols-2 gap-3 md:grid-cols-4">
        <Kpi label="SMTP" icon={<MailIcon className="h-4 w-4" />} value={s.configured ? 'Configured' : 'Not set'} tone={s.configured ? 'default' : 'warn'} hint={s.configured ? `${s.smtp.host}:${s.smtp.port}` : s.provider} />
        <Kpi label="Sent, 24h" icon={<CheckCircleIcon className="h-4 w-4" />} value={n(s.stats.sent_24h)} hint={s.stats.last_sent ? `last ${date(s.stats.last_sent, true)}` : 'none yet'} />
        <Kpi label="Failed, 24h" icon={<AlertIcon className="h-4 w-4" />} value={n(s.stats.failed_24h)} tone={s.stats.failed_24h ? 'warn' : 'default'} hint={s.stats.last_failed ? `last ${date(s.stats.last_failed, true)}` : 'none'} />
        <Kpi label="Waiting" icon={<SendIcon className="h-4 w-4" />} value={n(s.stats.queued)} hint={s.queue === 'redis' ? 'queued in Redis, retried 5×' : 'sent inline (no Redis)'} />
      </div>

      <div className="mb-6 grid gap-6 xl:grid-cols-2">
        <Card title="Configuration" icon={<MailIcon className="h-4 w-4" />}>
          <dl className="divide-y divide-rule text-sm">
            {[
              ['From', s.from.address ? `${s.from.name} <${s.from.address}>` : '—'],
              ['SMTP host', s.smtp.host ? `${s.smtp.host}:${s.smtp.port} (${s.smtp.secure ? 'SSL' : 'STARTTLS'})` : '—'],
              ['SMTP user', s.smtp.user ?? '—'],
              ['App password', s.smtp.passwordSet ? 'Configured ✓' : 'Not set'],
              ['Support email', s.supportEmail ?? '—'],
            ].map(([k, v]) => (
              <div key={k} className="flex justify-between gap-4 px-4 py-2.5">
                <dt className="text-muted">{k}</dt>
                <dd className="text-right font-medium">{v}</dd>
              </div>
            ))}
          </dl>
        </Card>
        <Card title="Send a test email" icon={<SendIcon className="h-4 w-4" />}>
          {isOwner(viewer.role) ? (
            <form action={sendTestEmail} className="flex flex-wrap items-end gap-2 p-5 text-sm">
              <label className="block flex-1">
                <span className="field-label"><ActionIcons.MailIcon />Recipient</span>
                <input name="to" type="email" defaultValue={viewer.email} className="field" />
              </label>
              <SubmitButton pendingLabel="Queuing…">
                <SendIcon className="h-4 w-4" /> Send test
              </SubmitButton>
            </form>
          ) : (
            <p className="p-5 text-sm text-muted">Only an owner can send test emails.</p>
          )}
        </Card>
      </div>

      {isOwner(viewer.role) && <Card title="Gmail App Password" icon={<MailIcon className="h-4 w-4" />}>
        <form action={saveSmtp} className="space-y-4 p-5 text-sm">
          <p className="text-ink-2">Sending email: <strong>{viewer.email}</strong>. Gmail server, port, encryption and sender details are configured automatically.</p>
          <label className="block"><span className="field-label"><ActionIcons.KeyIcon />Google App Password</span><PasswordInput name="password"  autoComplete="new-password" required maxLength={200} placeholder={s.smtp.passwordSet ? 'Enter a new App Password to replace the saved one' : 'Paste your 16-character Google App Password'} className="field" /></label>
          <p className="text-xs text-muted">Saving verifies Gmail and sends a test email to your owner inbox. Settings apply immediately and the App Password is stored encrypted.</p>
          <SubmitButton pendingLabel="Verifying Gmail..."><ActionIcons.SendIcon />Save and send test</SubmitButton>
        </form>
        {s.configured && <form action={removeSmtp} className="border-t border-rule p-5 text-sm"><SubmitButton className="btn btn-danger-quiet" confirm="Remove the saved App Password and disable email delivery?" pendingLabel="Removing..."><ActionIcons.TrashIcon />Remove App Password</SubmitButton></form>}
      </Card>}
      <div className="mb-6" />

      <Card title="Recent deliveries">
        {s.recent.length ? (
          <div className="overflow-x-auto">
            <table className="tbl">
              <thead>
                <tr>
                  <th>When</th>
                  <th>To</th>
                  <th>Template</th>
                  <th>Status</th>
                  <th>Attempts</th>
                  <th>Last error</th>
                </tr>
              </thead>
              <tbody>
                {s.recent.map((e) => (
                  <tr key={e.id}>
                    <td className="whitespace-nowrap text-xs text-muted">{date(e.createdAt, true)}</td>
                    <td className="text-xs">{e.toAddress}</td>
                    <td>
                      <code className="text-xs">{e.template}</code>
                    </td>
                    <td>
                      <Pill value={e.status === 'sent' ? 'delivered' : e.status} tone={e.status === 'failed' ? 'bad' : e.status === 'sent' ? 'good' : 'info'} />
                    </td>
                    <td className="num text-xs">{e.attempts}</td>
                    <td className="max-w-xs truncate text-xs text-danger" title={e.lastError ?? ''}>
                      {e.lastError ?? ''}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          <Empty icon={<MailIcon className="h-6 w-6" />}>No emails sent yet.</Empty>
        )}
      </Card>
    </>
  );
}
