
import { PasswordInput } from '@/components/PasswordInput';

import * as ActionIcons from '@/components/Icons';
import { UsersManager, type ManagedUser } from '@/components/UsersManager';
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 { ListChecksIcon, PlusIcon } from '@/components/Icons';
import { inviteUser } from '../../actions';

type U = {
  id: number;
  email: string;
  name: string | null;
  role: string;
  mfaEnabled: boolean;
  isActive: boolean;
  lastLoginAt: string | null;
  emailVerifiedAt: string | null;
  mustChangePassword: boolean;
  invitePending: boolean;
  activeSessions: number;
};

const ROLE_TONE: Record<string, 'good' | 'info' | 'warn' | 'muted'> = { owner: 'good', admin: 'good', editor: 'info', verifier: 'info', professional: 'warn', firm_admin: 'warn' };

export default async function Users({ searchParams }: { searchParams: SP }) {
  const sp = await searchParams;
  const viewer = await me();
  if (!isAdmin(viewer.role)) return <Forbidden what="user management" />;
  const trash = sp.view === 'trash';
  const { users, roles, trashCount } = await api<{ users: ManagedUser[]; roles: { value: string; label: string }[]; trashCount: number }>(`/admin/users?view=${trash ? 'trash' : 'users'}`);
  // Admins may only grant non-privileged roles; owners may grant any
  const grantable = roles.filter((r) => isOwner(viewer.role) || !['owner', 'admin'].includes(r.value));
  return (
    <>
      <PageHeader
        title="Users and roles"
        icon={<ListChecksIcon className="h-5 w-5" />}
        description="Owners have full authority and are the only ones who can manage owners and admins. Admins manage editors, verifiers, professionals and firm admins. The last owner can never be disabled or demoted."
      />
      <Flash ok={sp.ok} err={sp.err} />

      <div className="mb-6 flex flex-wrap items-center gap-3"><Link href="/users" className={`btn btn-sm ${trash ? 'btn-quiet' : 'btn-primary'}`}><ActionIcons.UsersIcon />Users</Link><Link href="/users?view=trash" className={`btn btn-sm ${trash ? 'btn-primary' : 'btn-quiet'}`}><ActionIcons.TrashIcon />Trash ({trashCount})</Link>{trash && <p className="text-sm text-muted">Accounts can be restored for 30 days. Expired accounts are permanently deleted automatically.</p>}</div>

      {!trash && <Card title="Invite a user" icon={<PlusIcon className="h-4 w-4" />} className="mb-6">
        <form action={inviteUser} className="grid gap-4 p-5 text-sm md:grid-cols-3">
          <label className="block">
            <span className="field-label"><ActionIcons.MailIcon />Email</span>
            <input name="email" type="email" required maxLength={255} className="field" />
          </label>
          <label className="block">
            <span className="field-label"><ActionIcons.UserIcon />Name</span>
            <input name="name" required minLength={2} maxLength={150} className="field" />
          </label>
          <label className="block">
            <span className="field-label"><ActionIcons.ShieldCheckIcon />Role</span>
            <select name="role" required defaultValue="editor" className="field">
              {grantable.map((r) => (
                <option key={r.value} value={r.value}>
                  {r.label}
                </option>
              ))}
            </select>
          </label>
          <label className="block">
            <span className="field-label"><ActionIcons.UsersIcon />Lawyer id (professionals)</span>
            <input name="lawyerId" inputMode="numeric" pattern="\d*" className="field" />
          </label>
          <label className="block">
            <span className="field-label"><ActionIcons.BuildingIcon />Organization id (firm admins)</span>
            <input name="organizationId" inputMode="numeric" pattern="\d*" className="field" />
          </label>
          {isOwner(viewer.role) && (
            <label className="block">
              <span className="field-label"><ActionIcons.KeyIcon />Your password for privileged actions</span>
              <PasswordInput name="confirmPassword"  autoComplete="current-password" className="field" />
            </label>
          )}
          <div className="md:col-span-3">
            <SubmitButton pendingLabel="Sending…"><ActionIcons.SendIcon />Send invitation</SubmitButton>
            <span className="ml-3 text-xs text-muted">They get an email link to set their own password. Nobody — including you — ever sees it.</span>
          </div>
        </form>
      </Card>}

      <UsersManager users={users} viewerId={viewer.id} viewerRole={viewer.role} trash={trash} />
    </>
  );
}
