"use client";

import { Checkbox } from "@/components/ui/checkbox";
import { cn } from "@/lib/utils";

import { MODULE_GROUPS, PARENT_TO_SALE, type ModuleUsageMap } from "../constants";

type Props = {
  id?: string;
  value: string[];
  onChange: (value: string[]) => void;
  className?: string;
  /** Modules already linked on other macros — disabled here (exclusive mapping). */
  moduleUsage?: ModuleUsageMap;
};

function uniqueCodes(codes: string[]): string[] {
  return [...new Set(codes)];
}

export function ModuleMultiSelect({
  id,
  value,
  onChange,
  className,
  moduleUsage = {},
}: Props) {
  const isTaken = (code: string) => (moduleUsage[code]?.length ?? 0) > 0;

  const toggle = (parentCode: string, checked: boolean) => {
    const saleCode = PARENT_TO_SALE[parentCode];

    if (checked) {
      if (isTaken(parentCode) || (saleCode && isTaken(saleCode))) return;
      const next = [...value, parentCode];
      if (saleCode) next.push(saleCode);
      onChange(uniqueCodes(next));
      return;
    }

    onChange(value.filter((item) => item !== parentCode && item !== saleCode));
  };

  return (
    <div
      id={id}
      className={cn(
        "grid max-h-64 gap-x-4 gap-y-1 overflow-y-auto rounded-lg border bg-muted/20 p-3 sm:grid-cols-2 lg:grid-cols-3",
        className,
      )}
    >
      {MODULE_GROUPS.map(({ parent, sale }) => {
        const checked = value.includes(parent.value);
        const fieldId = `${id ?? "modules"}-${parent.value}`;
        const usedBy = [
          ...(moduleUsage[parent.value] ?? []),
          ...(sale ? (moduleUsage[sale.value] ?? []) : []),
        ].filter((name, index, all) => all.indexOf(name) === index);
        const disabled = !checked && usedBy.length > 0;

        return (
          <label
            key={parent.value}
            htmlFor={fieldId}
            className={cn(
              "flex items-start gap-2 rounded-md px-1.5 py-1.5 text-sm",
              disabled
                ? "cursor-not-allowed opacity-60"
                : "cursor-pointer hover:bg-muted/60",
            )}
          >
            <Checkbox
              id={fieldId}
              checked={checked}
              disabled={disabled}
              className="mt-0.5"
              onCheckedChange={(next) => toggle(parent.value, next === true)}
            />
            <span className="min-w-0 leading-tight">
              <span className={cn("block", disabled && "text-muted-foreground")}>
                {parent.label}
              </span>
              {disabled ? (
                <span className="mt-0.5 block text-[11px] text-amber-700 dark:text-amber-400">
                  Mapped to {usedBy.join(", ")}
                </span>
              ) : null}
            </span>
          </label>
        );
      })}
    </div>
  );
}
