
import { PasswordInput } from './PasswordInput';

import * as ActionIcons from './Icons';
import { api, type Me } from '@/lib/api';
import { date } from '@/lib/format';
import { changeLoginEmail, disableMfa, resendVerification, revokeOtherSessions, revokeSession } from '@/app/actions';
import { Card, Pill } from './ui';
import { SubmitButton } from './Actions';
import { ChangePasswordForm, MfaEnableForm, RecoveryCodesForm } from './AccountForms';
import { AlertIcon, CheckCircleIcon, KeyIcon, LockIcon, MailIcon, ServerIcon, ShieldCheckIcon } from './Icons';

type Session = { id: string; mfa: boolean; userAgent: string | null; createdAt: string; lastSeenAt: string; current: boolean };

/** "Mozilla/5.0 (Windows NT 10.0…) Chrome/…" → "Chrome on Windows" */
function device(ua: string | null) {
  if (!ua) return 'Unknown device';
  const browser = /Edg\//.test(ua) ? 'Edge' : /Chrome\//.test(ua) ? 'Chrome' : /Firefox\//.test(ua) ? 'Firefox' : /Safari\//.test(ua) ? 'Safari' : /node|undici/i.test(ua) ? 'Server' : 'Browser';
  const os = /Windows/.test(ua) ? 'Windows' : /Android/.test(ua) ? 'Android' : /iPhone|iPad/.test(ua) ? 'iOS' : /Mac OS X/.test(ua) ? 'macOS' : /Linux/.test(ua) ? 'Linux' : '';
  return os ? `${browser} on ${os}` : browser;
}

const codeInput = 'field num w-40 text-center text-base tracking-[0.4em]';

/** Account security for any signed-in user: email, password, two-factor, recovery codes, sessions */
export async function SecurityPanels({ user, basePath, setup }: { user: Me; basePath: string; setup: boolean }) {
  const [sessions, mfaSetup] = await Promise.all([
    api<Session[]>('/auth/sessions'),
    !user.mfaEnabled && setup ? api<{ qr: string; secret: string }>('/auth/mfa/setup', { method: 'POST', body: {} }).catch(() => null) : null,
  ]);
  const privileged = user.role === 'owner' || user.role === 'admin';
  return (
    <div className="grid gap-6 xl:grid-cols-2">
      <div className="space-y-6">
        {!user.emailVerified && (
          <Card title="Confirm your email" icon={<MailIcon className="h-4 w-4" />}>
            <form action={resendVerification} className="flex flex-wrap items-center gap-3 p-5 text-sm">
              <input type="hidden" name="back" value={basePath} />
              <AlertIcon className="h-4 w-4 text-brass" />
              <span className="flex-1 text-ink-2">{user.email} has not been confirmed yet.</span>
              <SubmitButton className="btn btn-quiet btn-sm" pendingLabel="Sending…">
                <ActionIcons.SendIcon />Send confirmation email
              </SubmitButton>
            </form>
          </Card>
        )}

        {<Card title="Login email" icon={<MailIcon className="h-4 w-4" />}>
          <form action={changeLoginEmail} className="space-y-4 p-5 text-sm">
            <p className="text-muted">Current email: {user.email}. SMTP sender settings are managed separately on the Email page.</p>
            <label className="block"><span className="field-label"><ActionIcons.MailIcon />New login email</span><input name="email" type="email" required autoComplete="email" className="field" /></label>
            <label className="block"><span className="field-label"><ActionIcons.KeyIcon />Current password</span><PasswordInput name="currentPassword" required autoComplete="current-password" className="field" /></label>
            {user.mfaEnabled && <label className="block"><span className="field-label"><ActionIcons.ShieldCheckIcon />Authenticator code</span><input name="code" required pattern="[0-9]{6}" maxLength={6} autoComplete="one-time-code" className="field" /></label>}
            <SubmitButton pendingLabel="Updating..."><ActionIcons.MailIcon />Verify new login email</SubmitButton>
          </form>
        </Card>}

        <Card title="Password" icon={<LockIcon className="h-4 w-4" />}>
          <div className="p-5">
            <p className="mb-4 text-xs text-muted">Last changed {user.passwordChangedAt ? date(user.passwordChangedAt, true) : 'never'}.</p>
            <ChangePasswordForm requireCode={user.mfaEnabled} back={basePath} />
          </div>
        </Card>

        <Card title="Two-factor authentication" icon={<ShieldCheckIcon className="h-4 w-4" />}>
          <div className="space-y-4 p-5 text-sm">
            {user.mfaEnabled ? (
              <>
                <p className="flex items-center gap-2 rounded-lg bg-ledger-soft px-3 py-2.5 text-ledger">
                  <CheckCircleIcon className="h-4 w-4" />
                  Two-factor authentication is <strong>on</strong> for {user.email}.
                </p>
                <form action={disableMfa} className="flex flex-wrap items-end gap-2">
                  <input type="hidden" name="back" value={basePath} />
                  <label className="block">
                    <span className="field-label"><ActionIcons.ShieldCheckIcon />Current code</span>
                    <input name="code" inputMode="numeric" pattern="\d{6}" maxLength={6} required autoComplete="one-time-code" placeholder="000000" className={codeInput} />
                  </label>
                  <SubmitButton className="btn btn-danger-quiet" confirm="Turn off two-factor authentication for your account?">
                    <ActionIcons.LockIcon />Turn off
                  </SubmitButton>
                </form>
              </>
            ) : mfaSetup ? (
              <>
                <ol className="list-decimal space-y-1 pl-5 text-ink-2">
                  <li>Scan this code with an authenticator app (1Password, Google Authenticator, Authy).</li>
                  <li>Enter the six-digit code it shows. You’ll then get recovery codes to keep safe.</li>
                </ol>
                {/* eslint-disable-next-line @next/next/no-img-element */}
                <img src={mfaSetup.qr} alt="QR code for your authenticator app" width={180} height={180} className="rounded-lg border border-rule bg-white p-2" />
                <p className="text-xs text-muted">
                  Can’t scan? Enter this key: <code className="num select-all break-all rounded bg-sunken px-1.5 py-0.5 text-ink">{mfaSetup.secret}</code>
                </p>
                <MfaEnableForm />
              </>
            ) : (
              <>
                <p className="text-ink-2">Two-factor authentication is off. Turn it on so a stolen password alone can’t open your account.</p>
                <a href={`${basePath}?setup=1`} className="btn btn-primary btn-sm">
                  <ShieldCheckIcon className="h-4 w-4" /> Set up two-factor authentication
                </a>
              </>
            )}
          </div>
        </Card>

        {user.mfaEnabled && (
          <Card title="Recovery codes" icon={<KeyIcon className="h-4 w-4" />}>
            <div className="p-5">
              <RecoveryCodesForm remaining={user.recoveryCodesRemaining} />
            </div>
          </Card>
        )}
      </div>

      <Card
        title="Signed-in devices"
        icon={<ServerIcon className="h-4 w-4" />}
        actions={
          sessions.length > 1 && (
            <form action={revokeOtherSessions}>
              <input type="hidden" name="back" value={basePath} />
              <SubmitButton className="btn btn-quiet btn-xs" confirm="Sign out every other device?">
                <ActionIcons.LogOutIcon />Sign out all others
              </SubmitButton>
            </form>
          )
        }
      >
        <ul className="divide-y divide-rule">
          {sessions.map((s) => (
            <li key={s.id} className="flex flex-wrap items-center gap-3 px-4 py-3 text-sm">
              <div className="min-w-0 flex-1">
                <p className="font-medium">
                  {device(s.userAgent)} {s.current && <Pill value="this device" tone="good" />} {s.mfa && <Pill value="2FA" tone="info" />}
                </p>
                <p className="text-xs text-muted">
                  Signed in {date(s.createdAt, true)} · last active {date(s.lastSeenAt, true)}
                </p>
              </div>
              {!s.current && (
                <form action={revokeSession}>
                  <input type="hidden" name="back" value={basePath} />
                  <input type="hidden" name="ref" value={s.id} />
                  <SubmitButton className="btn btn-quiet btn-xs"><ActionIcons.LogOutIcon />Sign out</SubmitButton>
                </form>
              )}
            </li>
          ))}
        </ul>
        <p className="border-t border-rule px-4 py-2.5 text-xs text-muted">Changing your password or resetting it signs out every other device automatically.</p>
      </Card>
    </div>
  );
}
