"use client";

import { useMemo } from "react";
import { useTranslation } from "react-i18next";

import { AdminNoResourceState } from "@/components/admin/admin-no-resource-state";
import { cn } from "@/lib/utils";
import {
  applyProfileLevel,
  permissionProfileForGroup,
  resolveProfileLevel,
  type PermissionAccessLevel,
  type PermissionGroupProfile,
} from "@/lib/admin-permission-profiles";
import type { AdminPermissionCatalogData } from "@/types/api/admin-user";

type PackageSelectorProps = {
  catalog: AdminPermissionCatalogData | null;
  selectedSlugs: string[];
  onChange: (next: string[]) => void;
  resolveGroupLabel: (key: string, fallback: string) => string;
  isSuperAdmin?: boolean;
  emptyText: string;
  heightClassName?: string;
};

type RenderGroup = {
  key: string;
  label: string;
  profile: PermissionGroupProfile;
  levels: Array<{ key: PermissionAccessLevel; label: string; slugs: string[] }>;
};

export function AdminPermissionPackageSelector({
  catalog,
  selectedSlugs,
  onChange,
  resolveGroupLabel,
  isSuperAdmin = false,
  emptyText,
  heightClassName = "h-[52vh]",
}: PackageSelectorProps): React.ReactElement {
  const { t } = useTranslation("adminUsers");
  const catalogSlugSet = useMemo(
    () => new Set((catalog?.permissions ?? []).map((permission) => permission.slug)),
    [catalog],
  );

  const groups = useMemo<RenderGroup[]>(() => {
    const defs = catalog?.permission_menu_groups ?? [];
    const out: RenderGroup[] = [];

    for (const group of defs) {
      const profile = permissionProfileForGroup(group.key);
      if (profile === undefined) {
        continue;
      }
      if (profile.platformOnly && !isSuperAdmin) {
        continue;
      }

      const levels = profile.levels
        .map((level) => ({
          key: level.key,
          label: t(level.labelKey),
          slugs: level.slugs.filter((slug) => catalogSlugSet.has(slug)),
        }))
        .filter((level) => level.key === "none" || level.slugs.length > 0);

      if (levels.length <= 1) {
        continue;
      }

      out.push({
        key: group.key,
        label: resolveGroupLabel(group.key, group.label),
        profile,
        levels,
      });
    }

    return out;
  }, [catalog, catalogSlugSet, isSuperAdmin, resolveGroupLabel, t]);

  if (groups.length === 0) {
    return (
      <div className="rounded-lg border border-dashed p-4">
        <AdminNoResourceState compact className="py-4" message={emptyText} />
      </div>
    );
  }

  const setGroupLevel = (group: RenderGroup, levelKey: PermissionAccessLevel) => {
    onChange(applyProfileLevel(group.profile, levelKey, selectedSlugs));
  };

  return (
    <div className={cn("overflow-y-auto rounded-lg border bg-card", heightClassName)}>
      <ul className="divide-y divide-border/60">
        {groups.map((group) => {
          const activeLevel = resolveProfileLevel(group.profile, selectedSlugs);

          return (
            <li
              key={group.key}
              className="flex flex-col gap-2.5 px-4 py-3 sm:flex-row sm:items-center sm:justify-between"
            >
              <span className="min-w-[7rem] shrink-0 text-sm font-medium text-foreground">{group.label}</span>
              <div className="flex flex-wrap gap-1.5">
                {group.levels.map((level) => {
                  const active = activeLevel === level.key;
                  return (
                    <button
                      key={`${group.key}.${level.key}`}
                      type="button"
                      aria-pressed={active}
                      className={cn(
                        "rounded-md border px-2.5 py-1 text-xs transition-colors",
                        active
                          ? "border-primary bg-primary text-primary-foreground"
                          : "border-border/70 bg-background text-foreground hover:bg-muted/50",
                      )}
                      onClick={() => setGroupLevel(group, level.key)}
                    >
                      {level.label}
                    </button>
                  );
                })}
              </div>
            </li>
          );
        })}
      </ul>
    </div>
  );
}