import Link from "next/link";
import type {
  AppUserSummary,
  IdentityVerificationLevel,
  Paginated,
} from "@capila/contracts";
import { getDictionary, type Locale } from "@/lib/i18n";
import { getLocale } from "@/lib/locale";
import { getAccessToken, getCurrentUser } from "@/lib/session";
import { formatTimestamp } from "@/lib/date-time";
import { ProfileAvatar } from "@/components/profile-avatar";

type SearchParams = {
  query?: string;
  verificationLevel?: string;
  page?: string;
};

export default async function AppUsersPage({
  searchParams,
}: {
  searchParams: Promise<SearchParams>;
}) {
  const params = await searchParams;
  const locale = await getLocale();
  const copy = getDictionary(locale).appUsers;
  const currentUser = await getCurrentUser(locale);
  if (!currentUser?.permissions.includes("users:read")) {
    return (
      <section className="surface placeholder">
        <h1>{copy.denied}</h1>
      </section>
    );
  }
  const page = Math.max(1, Number(params.page) || 1);
  const token = await getAccessToken();
  const result = token
    ? await loadUsers(token, {
        page,
        ...(params.query ? { query: params.query } : {}),
        ...(params.verificationLevel
          ? { verificationLevel: params.verificationLevel }
          : {}),
        locale,
      })
    : emptyResult(page);

  return (
    <>
      <div className="page-heading">
        <div>
          <p className="eyebrow">{copy.eyebrow}</p>
          <h1>{copy.title}</h1>
          <p className="page-description">{copy.description}</p>
        </div>
        <span className="badge">{result.meta.total}</span>
      </div>

      <form className="surface app-user-filters" method="get">
        <label>
          <span>{copy.search}</span>
          <input
            name="query"
            defaultValue={params.query}
            placeholder={copy.searchPlaceholder}
          />
        </label>
        <label>
          <span>{copy.level}</span>
          <select
            name="verificationLevel"
            defaultValue={params.verificationLevel ?? ""}
          >
            <option value="">{copy.allLevels}</option>
            <option value="LEVEL_1">{copy.levelOne}</option>
            <option value="LEVEL_2">{copy.levelTwo}</option>
            <option value="LEVEL_3">{copy.levelThree}</option>
          </select>
        </label>
        <button className="primary-button" type="submit">
          {copy.apply}
        </button>
      </form>

      {result.data.length === 0 ? (
        <section className="surface placeholder">
          <p>{copy.empty}</p>
        </section>
      ) : (
        <section className="app-user-grid">
          {result.data.map((user) => (
            <article className="surface app-user-card" key={user.id}>
              <div className="app-user-card-heading">
                <ProfileAvatar
                  className="app-user-avatar profile-image-avatar"
                  image={user.profileImage}
                  displayName={user.displayName}
                />
                <div>
                  <h2>{user.displayName}</h2>
                  <p dir="ltr">{user.phone}</p>
                </div>
                <span className="badge">
                  {levelLabel(user.verificationLevel, copy)}
                </span>
              </div>
              <dl className="app-user-card-details">
                <div>
                  <dt>{copy.nationalCode}</dt>
                  <dd dir="ltr">{user.nationalCodeMasked ?? "—"}</dd>
                </div>
                <div>
                  <dt>{copy.activeSessions}</dt>
                  <dd>{user.activeSessionCount}</dd>
                </div>
                <div>
                  <dt>{copy.registered}</dt>
                  <dd>
                    {formatTimestamp(user.registeredAt, locale, {
                      dateOnly: true,
                    })}
                  </dd>
                </div>
              </dl>
              <Link className="app-user-link" href={`/app-users/${user.id}`}>
                {copy.view}
              </Link>
            </article>
          ))}
        </section>
      )}

      {result.meta.pageCount > 1 ? (
        <nav className="pagination" aria-label={copy.title}>
          <PaginationLink
            label={copy.previous}
            page={page - 1}
            disabled={page <= 1}
            params={params}
          />
          <span>
            {result.meta.page} / {result.meta.pageCount}
          </span>
          <PaginationLink
            label={copy.next}
            page={page + 1}
            disabled={page >= result.meta.pageCount}
            params={params}
          />
        </nav>
      ) : null}
    </>
  );
}

function PaginationLink({
  label,
  page,
  disabled,
  params,
}: {
  label: string;
  page: number;
  disabled: boolean;
  params: SearchParams;
}) {
  if (disabled) return <span className="pagination-disabled">{label}</span>;
  const query = new URLSearchParams();
  query.set("page", String(page));
  if (params.query) query.set("query", params.query);
  if (params.verificationLevel)
    query.set("verificationLevel", params.verificationLevel);
  return <Link href={`/app-users?${query.toString()}`}>{label}</Link>;
}

const loadUsers = async (
  token: string,
  input: {
    page: number;
    query?: string;
    verificationLevel?: string;
    locale: Locale;
  },
): Promise<Paginated<AppUserSummary>> => {
  const params = new URLSearchParams({
    page: String(input.page),
    pageSize: "20",
  });
  if (input.query) params.set("query", input.query);
  if (input.verificationLevel)
    params.set("verificationLevel", input.verificationLevel);
  try {
    const response = await fetch(
      `${process.env.API_URL ?? "http://localhost:3001/api/v1"}/panel/app-users?${params}`,
      {
        headers: {
          authorization: `Bearer ${token}`,
          "accept-language": input.locale,
        },
        cache: "no-store",
      },
    );
    return response.ok
      ? ((await response.json()) as Paginated<AppUserSummary>)
      : emptyResult(input.page);
  } catch {
    return emptyResult(input.page);
  }
};

const emptyResult = (page: number): Paginated<AppUserSummary> => ({
  data: [],
  meta: { page, pageSize: 20, total: 0, pageCount: 0 },
});

const levelLabel = (
  level: IdentityVerificationLevel,
  copy: ReturnType<typeof getDictionary>["appUsers"],
) =>
  level === "LEVEL_3"
    ? copy.levelThree
    : level === "LEVEL_2"
      ? copy.levelTwo
      : copy.levelOne;
