import Link from "next/link";
import type {
  AppUserDetail,
  IdentityVerificationStatus,
} 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 { updateAppUser } from "../actions";
import { ProfileAvatar } from "@/components/profile-avatar";

export default async function AppUserDetailPage({
  params,
  searchParams,
}: {
  params: Promise<{ userId: string }>;
  searchParams: Promise<{ success?: string; error?: string }>;
}) {
  const [{ userId }, query] = await Promise.all([params, 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 token = await getAccessToken();
  const user = token ? await loadUser(token, userId, locale) : null;
  if (!user) {
    return (
      <section className="surface placeholder">
        <h1>{copy.notFound}</h1>
        <Link href="/app-users">{copy.back}</Link>
      </section>
    );
  }
  const canEdit = currentUser.permissions.includes("users:manage");

  return (
    <>
      <div className="page-heading app-user-detail-heading">
        <div>
          <Link className="back-link" href="/app-users">
            {copy.back}
          </Link>
          <p className="eyebrow">{copy.details}</p>
          <h1>{user.displayName}</h1>
          <p className="page-description" dir="ltr">
            {user.phone}
          </p>
        </div>
        <div className="app-user-detail-profile">
          <ProfileAvatar
            className="app-user-detail-avatar profile-image-avatar"
            image={user.profileImage}
            displayName={user.displayName}
            priority
          />
          <span className="badge">
            {levelLabel(user.verificationLevel, copy)}
          </span>
        </div>
      </div>

      {query.success ? <p className="success-message">{copy.success}</p> : null}
      {query.error ? <p className="error">{copy.error}</p> : null}

      <section className="app-user-detail-grid">
        <article className="surface">
          <h2>{copy.identitySection}</h2>
          <dl className="review-details">
            <Detail label={copy.firstName} value={user.firstName} />
            <Detail label={copy.lastName} value={user.lastName} />
            <Detail label={copy.phone} value={user.phone} ltr />
            <Detail
              label={copy.nationalCode}
              value={user.nationalCodeMasked ?? "—"}
              ltr
            />
            <Detail
              label={copy.registered}
              value={formatTimestamp(user.registeredAt, locale)}
            />
            <Detail
              label={copy.lastUpdated}
              value={formatTimestamp(user.updatedAt, locale)}
            />
          </dl>
        </article>

        <article className="surface">
          <h2>{copy.securitySection}</h2>
          <dl className="review-details">
            <Detail
              label={copy.levelOne}
              value={formatTimestamp(user.levelOneVerifiedAt, locale)}
            />
            <Detail
              label={copy.levelTwo}
              value={formatOptionalDate(user.levelTwoVerifiedAt, locale)}
            />
            <Detail
              label={copy.levelThree}
              value={formatOptionalDate(user.levelThreeVerifiedAt, locale)}
            />
            <Detail
              label={copy.passwordChanged}
              value={formatOptionalDate(user.passwordChangedAt, locale)}
            />
            <Detail
              label={copy.activeSessions}
              value={String(user.activeSessionCount)}
            />
          </dl>
        </article>
      </section>

      <section className="surface app-user-edit">
        <div className="surface-heading">
          <div>
            <h2>{copy.editTitle}</h2>
            <p className="muted">
              {canEdit ? copy.editHint : copy.readonlyHint}
            </p>
          </div>
        </div>
        {canEdit ? (
          <form action={updateAppUser} className="app-user-edit-form">
            <input type="hidden" name="userId" value={user.id} />
            <label>
              <span>{copy.firstName}</span>
              <input
                name="firstName"
                defaultValue={user.firstName}
                minLength={2}
                maxLength={80}
                required
              />
            </label>
            <label>
              <span>{copy.lastName}</span>
              <input
                name="lastName"
                defaultValue={user.lastName}
                minLength={2}
                maxLength={80}
                required
              />
            </label>
            <button className="primary-button" type="submit">
              {copy.save}
            </button>
          </form>
        ) : null}
      </section>

      <section className="surface review-section">
        <div className="surface-heading">
          <h2>{copy.verificationSection}</h2>
          <span className="badge">{user.verifications.length}</span>
        </div>
        {user.verifications.length === 0 ? (
          <p className="muted">{copy.noVerifications}</p>
        ) : (
          <div className="review-list">
            {user.verifications.map((verification) => (
              <article key={verification.id}>
                <div className="review-list-heading">
                  <strong>{verification.kind.replaceAll("_", " ")}</strong>
                  <StatusBadge status={verification.status} />
                </div>
                <dl className="review-details compact">
                  <Detail label={copy.provider} value={verification.provider} />
                  <Detail
                    label={copy.tracking}
                    value={verification.trackingId ?? "—"}
                    ltr
                  />
                  <Detail
                    label={copy.purpose}
                    value={verification.purpose ?? "—"}
                  />
                  <Detail
                    label={copy.lastUpdated}
                    value={formatTimestamp(verification.createdAt, locale)}
                  />
                </dl>
              </article>
            ))}
          </div>
        )}
      </section>

      <section className="surface review-section">
        <div className="surface-heading">
          <h2>{copy.sessionSection}</h2>
          <span className="badge">{user.sessions.length}</span>
        </div>
        {user.sessions.length === 0 ? (
          <p className="muted">{copy.noSessions}</p>
        ) : (
          <div className="review-list">
            {user.sessions.map((session) => (
              <article key={session.id}>
                <div className="review-list-heading">
                  <strong>{session.deviceId}</strong>
                  <span
                    className={`status-pill ${session.active ? "approved" : "inactive"}`}
                  >
                    {session.active ? copy.sessionActive : copy.sessionInactive}
                  </span>
                </div>
                <p className="session-agent" dir="ltr">
                  {session.userAgent ?? "—"}
                </p>
                <dl className="review-details compact">
                  <Detail
                    label={copy.ip}
                    value={session.ipAddress ?? "—"}
                    ltr
                  />
                  <Detail
                    label={copy.lastSeen}
                    value={formatTimestamp(session.lastUsedAt, locale)}
                  />
                  <Detail
                    label={copy.expires}
                    value={formatTimestamp(session.expiresAt, locale)}
                  />
                </dl>
              </article>
            ))}
          </div>
        )}
      </section>
    </>
  );
}

function Detail({
  label,
  value,
  ltr = false,
}: {
  label: string;
  value: string;
  ltr?: boolean;
}) {
  return (
    <div>
      <dt>{label}</dt>
      <dd dir={ltr ? "ltr" : undefined}>{value}</dd>
    </div>
  );
}

function StatusBadge({ status }: { status: IdentityVerificationStatus }) {
  return (
    <span className={`status-pill ${status.toLowerCase()}`}>{status}</span>
  );
}

const loadUser = async (
  token: string,
  userId: string,
  locale: Locale,
): Promise<AppUserDetail | null> => {
  try {
    const response = await fetch(
      `${process.env.API_URL ?? "http://localhost:3001/api/v1"}/panel/app-users/${encodeURIComponent(userId)}`,
      {
        headers: {
          authorization: `Bearer ${token}`,
          "accept-language": locale,
        },
        cache: "no-store",
      },
    );
    return response.ok ? ((await response.json()) as AppUserDetail) : null;
  } catch {
    return null;
  }
};

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

const formatOptionalDate = (value: string | null, locale: Locale) =>
  value ? formatTimestamp(value, locale) : "—";
