import { type ReactElement, useState, type ComponentProps } from "react";
import { CheckIcon, MinusIcon } from "lucide-react";
import { Checkbox as CheckboxPrimitive } from "@base-ui/react/checkbox";
import { cn } from "@/lib/utils";

/**
 * Checkbox — shadcn/WealthX Design System
 * Figma: https://www.figma.com/design/9V9F0NGVsif8LGmEhVjOcT/Design-System---shadcn?node-id=72-2723
 *
 * States: unchecked | checked | indeterminate × default | disabled | error
 * White-label: checked/indeterminate use `primary` token → adapts to tenant color.
 * Error+checked/indeterminate: stacked variant overrides primary with destructive (higher specificity).
 */
export type CheckboxProps = ComponentProps<typeof CheckboxPrimitive.Root>;

function Checkbox({ className, ...props }: CheckboxProps): ReactElement {
  return (
    <CheckboxPrimitive.Root
      className={cn(
        "peer group inline-flex size-4 shrink-0 border border-input shadow-xs transition-all outline-none",
        "focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50",
        "disabled:cursor-not-allowed disabled:opacity-50",
        "aria-invalid:border-destructive aria-invalid:ring-destructive/20",
        "data-checked:border-primary data-checked:bg-primary data-checked:text-primary-foreground",
        "data-indeterminate:border-primary data-indeterminate:bg-primary data-indeterminate:text-primary-foreground",
        // Dark mode (upstream shadcn)
        "dark:bg-input/30 dark:aria-invalid:ring-destructive/40 dark:data-checked:bg-primary",
        // Stacked (2 attr selectors) → wins over single-attr rules above
        "aria-invalid:data-checked:border-destructive aria-invalid:data-checked:bg-destructive aria-invalid:data-checked:text-destructive-foreground",
        "aria-invalid:data-indeterminate:border-destructive aria-invalid:data-indeterminate:bg-destructive aria-invalid:data-indeterminate:text-destructive-foreground",
        className,
      )}
      data-slot="checkbox"
      {...props}
    >
      <CheckboxPrimitive.Indicator
        className="grid place-content-center text-current transition-none"
        data-slot="checkbox-indicator"
      >
        <CheckIcon className="size-3.5 group-data-indeterminate:hidden" />
        <MinusIcon className="size-3.5 hidden group-data-indeterminate:block" />
      </CheckboxPrimitive.Indicator>
    </CheckboxPrimitive.Root>
  );
}

/**
 * CheckboxCard — card wrapper with label + optional description.
 * Figma: Checkbox_card (3029:12381)
 *
 * Card background: primary/5 when checked/indeterminate; destructive/5 when error+checked.
 * White-label: opacity modifier on primary token → adapts to tenant color.
 */
export type CheckboxCardProps = ComponentProps<
  typeof CheckboxPrimitive.Root
> & {
  label: string;
  description?: string;
  error?: boolean;
};

function CheckboxCard({
  className,
  checked,
  defaultChecked,
  onCheckedChange,
  disabled,
  error,
  label,
  description,
  ...props
}: CheckboxCardProps): ReactElement {
  const [internalChecked, setInternalChecked] = useState<boolean>(
    Boolean(defaultChecked),
  );

  const resolvedChecked = checked ?? internalChecked;
  const isTinted = resolvedChecked;

  return (
    <label
      className={cn(
        "flex items-start gap-3 border border-border p-4 font-sans transition-colors cursor-pointer",
        error
          ? ["border-destructive", isTinted && "bg-destructive/5"]
          : isTinted && "border-primary bg-primary/5",
        disabled && "cursor-not-allowed opacity-50",
        className,
      )}
      data-slot="checkbox-card"
    >
      <Checkbox
        aria-invalid={error || undefined}
        checked={resolvedChecked}
        className="mt-0.5"
        disabled={disabled}
        onCheckedChange={(value, event) => {
          setInternalChecked(value as boolean);
          onCheckedChange?.(value, event);
        }}
        {...props}
      />
      <div className="flex flex-col gap-1">
        <span className="text-label-medium leading-none">{label}</span>
        {description ? (
          <span className="text-body-small text-muted-foreground">
            {description}
          </span>
        ) : null}
      </div>
    </label>
  );
}

export { Checkbox, CheckboxCard };
