
import * as ActionIcons from '@/components/Icons';
import { api, me, FIRM_ROLE_LABEL } from '@/lib/api';
import { date } from '@/lib/format';
import { Card, Flash, PageHeader, Pill, type SP } from '@/components/ui';
import { SubmitButton } from '@/components/Actions';
import { PlusIcon, UsersIcon } from '@/components/Icons';
import { changeFirmMemberRole, inviteFirmMember, removeFirmMember } from '../../../actions';

type M = { userId: number; email: string; name: string | null; accountRole: string; lawyerId: number | null; role: string; status: string; joinedAt: string | null; lastLoginAt: string | null; mfaEnabled: boolean };
type Team = { members: M[]; seats: { plan: string; used: number; limit: number }; myRole: string; roles: { value: string; label: string }[] };

const ROLE_HELP: Record<string, string> = {
  owner: 'Everything, including owners, admins and billing',
  admin: 'Firm profile, lawyers, team, enquiries, integrations',
  billing: 'Plans and payments only',
  member: 'Firm enquiries',
};

export default async function FirmTeam({ searchParams }: { searchParams: SP }) {
  const sp = await searchParams;
  const [d, user] = await Promise.all([api<Team>('/firm/members'), me()]);
  const owner = d.myRole === 'owner';
  const manage = owner || d.myRole === 'admin';
  const full = d.seats.used >= d.seats.limit;
  const grantable = d.roles.filter((r) => r.value !== 'owner' && (owner || r.value !== 'admin'));
  return (
    <>
      <PageHeader
        title="Team"
        icon={<UsersIcon className="h-5 w-5" />}
        description={`${d.seats.used} of ${d.seats.limit} seats used on the ${d.seats.plan.replace('_', ' ')} plan. Seats cover team members and lawyers with their own login.`}
      />
      <Flash ok={sp.ok} err={sp.err} />
      <div className="grid gap-6 xl:grid-cols-[1.6fr_1fr]">
        <Card title="Members">
          <div className="overflow-x-auto">
            <table className="tbl">
              <thead>
                <tr>
                  <th>Person</th>
                  <th>Firm role</th>
                  <th>Status</th>
                  <th>Last sign-in</th>
                  {manage && <th />}
                </tr>
              </thead>
              <tbody>
                {d.members.map((m) => {
                  const self = m.userId === user.id;
                  const canEdit = manage && !self && (owner || !['owner', 'admin'].includes(m.role));
                  return (
                    <tr key={m.userId}>
                      <td>
                        <span className="font-semibold">{m.name ?? m.email}</span>
                        {self && <span className="ml-2 rounded bg-sunken px-1.5 py-0.5 text-[10px] font-semibold text-muted">you</span>}
                        <span className="block text-xs text-muted">
                          {m.email}
                          {m.lawyerId ? ' · lawyer' : ''}
                        </span>
                      </td>
                      <td>
                        {canEdit ? (
                          <form action={changeFirmMemberRole} className="flex gap-1.5">
                            <input type="hidden" name="userId" value={m.userId} />
                            <select name="role" defaultValue={m.role} aria-label="Firm role" className="field h-8 text-xs">
                              {d.roles
                                .filter((r) => owner || !['owner', 'admin'].includes(r.value))
                                .map((r) => (
                                  <option key={r.value} value={r.value}>
                                    {r.label}
                                  </option>
                                ))}
                            </select>
                            <SubmitButton className="btn btn-quiet btn-xs"><ActionIcons.SaveIcon />Save</SubmitButton>
                          </form>
                        ) : (
                          <Pill value={FIRM_ROLE_LABEL[m.role] ?? m.role} tone={m.role === 'owner' ? 'good' : 'info'} />
                        )}
                      </td>
                      <td className="space-x-1 whitespace-nowrap">
                        <Pill value={m.status} tone={m.status === 'active' ? 'good' : 'info'} />
                        {m.status === 'active' && !m.mfaEnabled && <Pill value="no 2FA" tone="warn" />}
                      </td>
                      <td className="whitespace-nowrap text-xs text-muted">{m.lastLoginAt ? date(m.lastLoginAt, true) : 'Never'}</td>
                      {manage && (
                        <td>
                          {canEdit && (
                            <form action={removeFirmMember}>
                              <input type="hidden" name="userId" value={m.userId} />
                              <SubmitButton className="btn btn-danger-quiet btn-xs" confirm={`Remove ${m.email} from the firm? They’ll be signed out.`}>
                                <ActionIcons.TrashIcon />Remove
                              </SubmitButton>
                            </form>
                          )}
                        </td>
                      )}
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </Card>

        <div className="space-y-6">
          {manage && (
            <Card title="Invite a team member" icon={<PlusIcon className="h-4 w-4" />}>
              <form action={inviteFirmMember} className="grid gap-3 p-5 text-sm">
                <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 />Firm role</span>
                  <select name="role" defaultValue="member" className="field">
                    {grantable.map((r) => (
                      <option key={r.value} value={r.value}>
                        {r.label}
                      </option>
                    ))}
                  </select>
                </label>
                <div>
                  <SubmitButton disabled={full} title={full ? 'All seats are in use' : undefined} pendingLabel="Sending…">
                    <ActionIcons.SendIcon />Send invitation
                  </SubmitButton>
                  {full && <p className="mt-2 text-xs text-brass">All seats are in use. Remove someone or upgrade to the Firm plan.</p>}
                </div>
              </form>
            </Card>
          )}
          <Card title="Firm roles">
            <dl className="divide-y divide-rule text-sm">
              {Object.entries(ROLE_HELP).map(([role, help]) => (
                <div key={role} className="px-4 py-2.5">
                  <dt className="font-medium">{FIRM_ROLE_LABEL[role]}</dt>
                  <dd className="text-xs text-muted">{help}</dd>
                </div>
              ))}
            </dl>
          </Card>
        </div>
      </div>
    </>
  );
}
