import * as React from "react";
import { cn } from "@/lib/utils";
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";

export type LoanOptionItem = {
  value: string;
  label: string;
};

export type LoanOptionGroupProps = {
  title?: string;
  options: LoanOptionItem[];
  /** Current value for single-select. Mutually exclusive with `values`. */
  value?: string;
  /** Current values for multi-select. Mutually exclusive with `value`. */
  values?: string[];
  onChange: (next: string | string[]) => void;
  multiple?: boolean;
  /** When `multiple`, maximum number of options that can be selected. */
  max?: number;
  /** Show rank badge on multi-selected items (#1, #2, #3). */
  showRank?: boolean;
  /** Allow deselecting the current selection. */
  allowUnSelect?: boolean;
  error?: boolean;
  helperText?: string;
  disabled?: boolean;
  className?: string;
};

export function LoanOptionGroup({
  title,
  options,
  value,
  values = [],
  onChange,
  multiple = false,
  max,
  showRank = false,
  allowUnSelect = true,
  error = false,
  helperText,
  disabled = false,
  className,
}: LoanOptionGroupProps) {
  const controlledValue: readonly string[] = multiple
    ? values
    : value
      ? [value]
      : [];

  const handleValueChange = (next: readonly string[]) => {
    if (multiple) {
      if (max !== undefined && next.length > max) return;
      onChange([...next]);
    } else {
      if (next.length === 0 && !allowUnSelect) return;
      onChange(next[0] ?? "");
    }
  };

  return (
    <div className={cn("flex flex-col gap-3 font-sans", className)}>
      {title && (
        <p
          className={cn(
            "text-label-medium text-foreground",
            error && "text-destructive",
          )}
        >
          {title}
        </p>
      )}
      <ToggleGroup
        value={controlledValue}
        onValueChange={handleValueChange}
        variant="outline"
        type={multiple ? "multiple" : "single"}
        spacing={2}
        disabled={disabled}
        className="flex-wrap justify-start"
      >
        {options.map((opt) => {
          const rank = showRank && multiple ? values.indexOf(opt.value) : -1;
          return (
            <ToggleGroupItem
              key={opt.value}
              value={opt.value}
              className="h-auto px-4 py-2 text-label-medium"
            >
              {rank >= 0 && (
                <span className="text-button-xs opacity-70">#{rank + 1}</span>
              )}
              {opt.label}
            </ToggleGroupItem>
          );
        })}
      </ToggleGroup>
      {error && helperText && (
        <p className="text-caption text-destructive">{helperText}</p>
      )}
    </div>
  );
}
