import {
  permissions,
  roles,
  type PanelUserSummary,
  type Permission,
  type Role,
} from "@capila/contracts";
import { getDictionary } from "@/lib/i18n";
import { getLocale } from "@/lib/locale";
import { getAccessToken, getCurrentUser } from "@/lib/session";
import { createPanelUser, updatePanelUserAccess } from "./actions";

export default async function PanelUsersPage({
  searchParams,
}: {
  searchParams: Promise<{ success?: string; error?: string }>;
}) {
  const params = await searchParams;
  const locale = await getLocale();
  const dictionary = getDictionary(locale);
  const copy = dictionary.panelUsers;
  const currentUser = await getCurrentUser(locale);
  if (!currentUser?.permissions.includes("users:manage")) {
    return (
      <section className="surface placeholder">
        <h1>{copy.denied}</h1>
      </section>
    );
  }
  const token = await getAccessToken();
  const users = token ? await loadUsers(token) : [];

  return (
    <>
      <div className="page-heading">
        <div>
          <p className="eyebrow">{copy.eyebrow}</p>
          <h1>{copy.title}</h1>
          <p className="page-description">{copy.description}</p>
        </div>
      </div>
      {params.success ? (
        <p className="success-message">{copy.success}</p>
      ) : null}
      {params.error ? <p className="error">{copy.error}</p> : null}

      <section className="surface panel-user-create">
        <h2>{copy.createTitle}</h2>
        <form action={createPanelUser} className="panel-user-form">
          <div className="auth-grid">
            <Field label={copy.firstName} name="firstName" />
            <Field label={copy.lastName} name="lastName" />
            <Field
              label={copy.countryCode}
              name="phoneCountryCode"
              defaultValue="+98"
              dir="ltr"
            />
            <Field
              label={copy.phone}
              name="phoneNumber"
              placeholder="09121234567"
              dir="ltr"
            />
            <Field label={copy.password} name="password" type="password" />
          </div>
          <AccessChecks
            title={copy.roles}
            name="roles"
            values={roles}
            defaults={["admin"]}
            locale={locale}
          />
          <AccessChecks
            title={copy.permissions}
            name="permissions"
            values={permissions}
            defaults={["dashboard:read", "domains:read", "users:read"]}
            locale={locale}
          />
          <button className="primary-button" type="submit">
            {copy.create}
          </button>
        </form>
      </section>

      <section className="panel-user-list">
        <div className="surface-heading">
          <h2>{copy.listTitle}</h2>
        </div>
        {users.length === 0 ? <p className="muted">{copy.empty}</p> : null}
        <div className="panel-user-grid">
          {users.map((user) => (
            <article className="surface panel-user-card" key={user.id}>
              <div>
                <strong>{user.displayName}</strong>
                <small dir="ltr">{user.phone}</small>
              </div>
              <form action={updatePanelUserAccess} className="panel-user-form">
                <input type="hidden" name="userId" value={user.id} />
                <AccessChecks
                  title={copy.roles}
                  name="roles"
                  values={roles}
                  defaults={user.roles}
                  locale={locale}
                />
                <AccessChecks
                  title={copy.permissions}
                  name="permissions"
                  values={permissions}
                  defaults={user.permissions}
                  locale={locale}
                />
                <button
                  className="primary-button"
                  type="submit"
                  disabled={user.id === currentUser.id}
                >
                  {copy.save}
                </button>
              </form>
            </article>
          ))}
        </div>
      </section>
    </>
  );
}

function Field({
  label,
  ...input
}: {
  label: string;
  name: string;
  defaultValue?: string;
  placeholder?: string;
  dir?: "ltr";
  type?: string;
}) {
  return (
    <div>
      <label htmlFor={input.name}>{label}</label>
      <input
        id={input.name}
        required
        minLength={input.type === "password" ? 8 : undefined}
        {...input}
      />
    </div>
  );
}

function AccessChecks<T extends Role | Permission>({
  title,
  name,
  values,
  defaults,
  locale,
}: {
  title: string;
  name: string;
  values: readonly T[];
  defaults: readonly T[];
  locale: "fa" | "en";
}) {
  return (
    <fieldset className="access-checks">
      <legend>{title}</legend>
      {values.map((value) => (
        <label key={value}>
          <input
            type="checkbox"
            name={name}
            value={value}
            defaultChecked={defaults.includes(value)}
          />
          <span>{accessLabel(value, locale)}</span>
        </label>
      ))}
    </fieldset>
  );
}

const accessLabel = (value: string, locale: "fa" | "en") =>
  locale === "en"
    ? value.replaceAll("_", " ")
    : ((
        {
          super_admin: "مدیر ارشد",
          admin: "مدیر",
          support: "پشتیبانی",
          merchant: "پذیرنده",
          clinic_specialist: "متخصص کلینیک",
          advertiser: "تبلیغ‌دهنده",
          financial_operator: "اپراتور مالی",
          content_moderator: "ناظر محتوا",
          "dashboard:read": "مشاهده داشبورد",
          "users:read": "مشاهده کاربران",
          "users:manage": "مدیریت کاربران",
          "domains:read": "مشاهده دامنه‌ها",
          "support:manage": "مدیریت پشتیبانی",
          "finance:read": "مشاهده مالی",
          "content:moderate": "نظارت محتوا",
        } as Record<string, string>
      )[value] ?? value);

const loadUsers = async (token: string): Promise<PanelUserSummary[]> => {
  try {
    const response = await fetch(
      `${process.env.API_URL ?? "http://localhost:3001/api/v1"}/panel/users`,
      { headers: { authorization: `Bearer ${token}` }, cache: "no-store" },
    );
    return response.ok ? ((await response.json()) as PanelUserSummary[]) : [];
  } catch {
    return [];
  }
};
