
import { PasswordInput } from '@/components/PasswordInput';

import * as ActionIcons from '@/components/Icons';
import Link from 'next/link';
import { api, isAdmin, isOwner, me, ROLE_LABEL } from '@/lib/api';
import { date } from '@/lib/format';
import { Card, Flash, Forbidden, PageHeader, Pill, type SP } from '@/components/ui';
import { SubmitButton } from '@/components/Actions';
import { ArrowLeftIcon, HistoryIcon, KeyIcon, SaveIcon, ServerIcon, ShieldCheckIcon, UserIcon } from '@/components/Icons';
import { updateUser, userAction } from '../../../actions';

type Detail = {
  user: {
    id: number;
    email: string;
    name: string | null;
    role: string;
    isActive: boolean;
    mfaEnabled: boolean;
    emailVerifiedAt: string | null;
    passwordChangedAt: string | null;
    mustChangePassword: boolean;
    failedLogins: number;
    lockedUntil: string | null;
    lastLoginAt: string | null;
    createdAt: string;
    lawyerId: number | null;
    organizationId: number | null;
    invitePending: boolean;
  };
  lawyer: { id: number; slug: string; firstName: string; lastName: string } | null;
  organization: { id: number; name: string; kind: string } | null;
  sessions: { id: string; mfa: boolean; userAgent: string | null; createdAt: string; lastSeenAt: string }[];
  invitation: { expiresAt: string; createdAt: string } | null;
  history: { id: number; action: string; actor: string | null; createdAt: string; after: unknown }[];
  roles: { value: string; label: string }[];
  activeOwners: number;
};

function Row({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <div className="flex justify-between gap-4 px-4 py-2.5 text-sm">
      <dt className="text-muted">{label}</dt>
      <dd className="text-right font-medium">{children}</dd>
    </div>
  );
}

export default async function UserDetail({ params, searchParams }: { params: Promise<{ id: string }>; searchParams: SP }) {
  const [{ id }, sp, viewer] = await Promise.all([params, searchParams, me()]);
  if (!isAdmin(viewer.role)) return <Forbidden what="user management" />;
  const d = await api<Detail>(`/admin/users/${encodeURIComponent(id)}`);
  const u = d.user;
  const self = u.id === viewer.id;
  const privileged = u.role === 'owner' || u.role === 'admin';
  // Mirrors the API rules so the page doesn't offer actions that would be refused
  const canManage = isOwner(viewer.role) || !privileged;
  const lastOwner = u.role === 'owner' && u.isActive && d.activeOwners <= 1;
  const grantable = d.roles.filter((r) => isOwner(viewer.role) || !['owner', 'admin'].includes(r.value));
  const act = (kind: Parameters<typeof userAction>[0]) => userAction.bind(null, kind);
  const confirmField = isOwner(viewer.role) && (
    <PasswordInput name="confirmPassword"  placeholder="Your password for privileged actions" autoComplete="current-password" className="field h-8 w-40 text-xs" />
  );

  return (
    <>
      <Link href="/users" className="mb-3 inline-flex items-center gap-1.5 text-sm text-muted hover:text-ink">
        <ArrowLeftIcon className="h-4 w-4" /> All users
      </Link>
      <PageHeader
        title={u.name ?? u.email}
        icon={<UserIcon className="h-5 w-5" />}
        description={
          <span className="flex flex-wrap items-center gap-2">
            {u.email} <Pill value={ROLE_LABEL[u.role] ?? u.role} tone="good" />
            {u.invitePending ? <Pill value="invited" tone="info" /> : <Pill value={u.isActive ? 'active' : 'disabled'} tone={u.isActive ? 'good' : 'bad'} />}
            {lastOwner && <Pill value="last owner — protected" tone="warn" />}
          </span>
        }
      />
      <Flash ok={sp.ok} err={sp.err} />
      {!canManage && <p className="mb-6 rounded-lg bg-brass-soft px-4 py-3 text-sm text-ink-2">Only an owner can change owner and admin accounts. You can view this account but not change it.</p>}

      <div className="grid gap-6 xl:grid-cols-[1fr_1fr]">
        <div className="space-y-6">
          <Card title="Account" icon={<UserIcon className="h-4 w-4" />}>
            <dl className="divide-y divide-rule">
              <Row label="Email verified">{u.emailVerifiedAt ? date(u.emailVerifiedAt, true) : <Pill value="not verified" tone="warn" />}</Row>
              <Row label="Password changed">{u.passwordChangedAt ? date(u.passwordChangedAt, true) : u.invitePending ? 'Not set (invitation pending)' : '—'}</Row>
              <Row label="Must change password">{u.mustChangePassword ? 'Yes' : 'No'}</Row>
              <Row label="Two-factor">{u.mfaEnabled ? 'On' : 'Off'}</Row>
              <Row label="Last sign-in">{u.lastLoginAt ? date(u.lastLoginAt, true) : 'Never'}</Row>
              <Row label="Failed attempts">{u.failedLogins}{u.lockedUntil && new Date(u.lockedUntil) > new Date() ? ` · locked until ${date(u.lockedUntil, true)}` : ''}</Row>
              <Row label="Created">{date(u.createdAt, true)}</Row>
              {d.invitation && <Row label="Invitation expires">{date(d.invitation.expiresAt, true)}</Row>}
              <Row label="Linked lawyer">{d.lawyer ? `${d.lawyer.firstName} ${d.lawyer.lastName} (#${d.lawyer.id})` : '—'}</Row>
              <Row label="Organization">{d.organization ? `${d.organization.name} (#${d.organization.id})` : '—'}</Row>
            </dl>
          </Card>

          {canManage && (
            <Card title="Access" icon={<KeyIcon className="h-4 w-4" />}>
              <form action={updateUser} className="grid gap-4 p-5 text-sm sm:grid-cols-2">
                <input type="hidden" name="id" value={u.id} />
                <label className="block">
                  <span className="field-label"><ActionIcons.UserIcon />Name</span>
                  <input name="name" required minLength={2} maxLength={150} defaultValue={u.name ?? ''} className="field" />
                </label>
                <label className="block">
                  <span className="field-label"><ActionIcons.ShieldCheckIcon />Role</span>
                  <select name="role" defaultValue={u.role} disabled={lastOwner} className="field">
                    {grantable.map((r) => (
                      <option key={r.value} value={r.value}>
                        {r.label}
                      </option>
                    ))}
                  </select>
                  {lastOwner && <input type="hidden" name="role" value="owner" />}
                </label>
                <label className="block">
                  <span className="field-label"><ActionIcons.UsersIcon />Lawyer id</span>
                  <input name="lawyerId" inputMode="numeric" pattern="\d*" defaultValue={u.lawyerId ?? ''} className="field" />
                </label>
                <label className="block">
                  <span className="field-label"><ActionIcons.BuildingIcon />Organization id</span>
                  <input name="organizationId" inputMode="numeric" pattern="\d*" defaultValue={u.organizationId ?? ''} className="field" />
                </label>
                {isOwner(viewer.role) && (
                  <label className="block sm:col-span-2">
                    <span className="field-label"><ActionIcons.KeyIcon />Your password for privileged actions</span>
                    <PasswordInput name="confirmPassword"  autoComplete="current-password" className="field" />
                  </label>
                )}
                <div className="sm:col-span-2">
                  <SubmitButton pendingLabel="Saving…">
                    <SaveIcon className="h-4 w-4" /> Save
                  </SubmitButton>
                  <span className="ml-3 text-xs text-muted">Changing role or links signs the user out everywhere.</span>
                </div>
              </form>
            </Card>
          )}
        </div>

        <div className="space-y-6">
          {canManage && (
            <Card title="Admin actions" icon={<ShieldCheckIcon className="h-4 w-4" />}>
              <ul className="divide-y divide-rule text-sm">
                {u.invitePending && (
                  <li className="flex flex-wrap items-center justify-between gap-3 px-4 py-3">
                    <span>Send the invitation email again (old link stops working)</span>
                    <form action={act('resend-invite')}>
                      <input type="hidden" name="id" value={u.id} />
                      <SubmitButton className="btn btn-quiet btn-xs"><ActionIcons.SendIcon />Resend invitation</SubmitButton>
                    </form>
                  </li>
                )}
                {!u.invitePending && u.isActive && (
                  <li className="flex flex-wrap items-center justify-between gap-3 px-4 py-3">
                    <span>Email a password reset link</span>
                    <form action={act('send-reset')}>
                      <input type="hidden" name="id" value={u.id} />
                      <SubmitButton className="btn btn-quiet btn-xs"><ActionIcons.MailIcon />Send reset link</SubmitButton>
                    </form>
                  </li>
                )}
                {!self && !u.invitePending && (
                  <li className="flex flex-wrap items-center justify-between gap-3 px-4 py-3">
                    <span>Sign out everywhere and require a new password</span>
                    <form action={act('force-reset')}>
                      <input type="hidden" name="id" value={u.id} />
                      <SubmitButton className="btn btn-quiet btn-xs" confirm="Sign this user out everywhere and require a new password?">
                        <ActionIcons.KeyIcon />Force reset
                      </SubmitButton>
                    </form>
                  </li>
                )}
                <li className="flex flex-wrap items-center justify-between gap-3 px-4 py-3">
                  <span>Sign out all devices ({d.sessions.length} active)</span>
                  <form action={act('revoke-sessions')}>
                    <input type="hidden" name="id" value={u.id} />
                    <SubmitButton className="btn btn-quiet btn-xs" disabled={!d.sessions.length}>
                      <ActionIcons.LogOutIcon />Sign out everywhere
                    </SubmitButton>
                  </form>
                </li>
                {!u.emailVerifiedAt && !u.invitePending && (
                  <li className="flex flex-wrap items-center justify-between gap-3 px-4 py-3">
                    <span>Mark the email address as verified</span>
                    <form action={act('verify-email')}>
                      <input type="hidden" name="id" value={u.id} />
                      <SubmitButton className="btn btn-quiet btn-xs"><ActionIcons.BadgeCheckIcon />Mark verified</SubmitButton>
                    </form>
                  </li>
                )}
                {u.mfaEnabled && isOwner(viewer.role) && (
                  <li className="flex flex-wrap items-center justify-between gap-3 px-4 py-3">
                    <span>Remove two-factor (lost phone)</span>
                    <form action={act('reset-mfa')} className="flex items-center gap-2">
                      <input type="hidden" name="id" value={u.id} />
                      {confirmField}
                      <SubmitButton className="btn btn-danger-quiet btn-xs" confirm="Remove this user's two-factor authentication?">
                        <ActionIcons.ShieldCheckIcon />Reset 2FA
                      </SubmitButton>
                    </form>
                  </li>
                )}
                {!self && (
                  <li className="flex flex-wrap items-center justify-between gap-3 px-4 py-3">
                    <span>{u.isActive ? 'Disable the account and sign it out' : 'Re-enable the account'}</span>
                    {u.isActive ? (
                      <form action={act('disable')} className="flex items-center gap-2">
                        <input type="hidden" name="id" value={u.id} />
                        {privileged && confirmField}
                        <SubmitButton className="btn btn-danger-quiet btn-xs" disabled={lastOwner} title={lastOwner ? 'The last owner cannot be disabled' : undefined} confirm="Disable this account?">
                          <ActionIcons.XCircleIcon />Disable
                        </SubmitButton>
                      </form>
                    ) : (
                      <form action={act('enable')}>
                        <input type="hidden" name="id" value={u.id} />
                        <SubmitButton className="btn btn-quiet btn-xs"><ActionIcons.CheckCircleIcon />Enable</SubmitButton>
                      </form>
                    )}
                  </li>
                )}
                {!self && <li className="flex flex-wrap items-center justify-between gap-3 px-4 py-3"><span>Move account to Trash for 30 days</span><form action={act('trash')}><input type="hidden" name="id" value={u.id} /><SubmitButton className="btn btn-danger-quiet btn-xs" disabled={lastOwner} confirm="Move this account to Trash? It can be restored for 30 days, then it is deleted permanently."><ActionIcons.TrashIcon />Move to Trash</SubmitButton></form></li>}
              </ul>
            </Card>
          )}

          <Card title="Active sessions" icon={<ServerIcon className="h-4 w-4" />}>
            {d.sessions.length ? (
              <ul className="divide-y divide-rule text-sm">
                {d.sessions.map((s) => (
                  <li key={s.id} className="px-4 py-2.5">
                    <p className="truncate text-xs text-ink-2" title={s.userAgent ?? ''}>
                      {s.userAgent ?? 'Unknown device'}
                    </p>
                    <p className="text-xs text-muted">
                      Signed in {date(s.createdAt, true)} · last active {date(s.lastSeenAt, true)} {s.mfa && '· 2FA'}
                    </p>
                  </li>
                ))}
              </ul>
            ) : (
              <p className="p-4 text-sm text-muted">No active sessions.</p>
            )}
          </Card>

          <Card title="Security history" icon={<HistoryIcon className="h-4 w-4" />}>
            {d.history.length ? (
              <ul className="max-h-96 divide-y divide-rule overflow-y-auto text-sm">
                {d.history.map((h) => (
                  <li key={h.id} className="flex justify-between gap-3 px-4 py-2">
                    <span>
                      <code className="text-xs">{h.action}</code>
                      {h.actor && <span className="ml-2 text-xs text-muted">by {h.actor}</span>}
                    </span>
                    <span className="whitespace-nowrap text-xs text-muted">{date(h.createdAt, true)}</span>
                  </li>
                ))}
              </ul>
            ) : (
              <p className="p-4 text-sm text-muted">Nothing recorded yet.</p>
            )}
          </Card>
        </div>
      </div>
    </>
  );
}
