"use client";

import * as React from "react";
import { cn } from "@/lib/utils";
import { formatMoneyGrouped, parseMoneyInput, toRialInteger } from "@/lib/utils";

export function Select({
  className,
  children,
  ...props
}: React.SelectHTMLAttributes<HTMLSelectElement>) {
  return (
    <select
      className={cn(
        "flex h-10 w-full rounded-xl border border-[var(--border)] bg-[var(--surface)] px-3 text-sm text-secondary",
        "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/30",
        "disabled:cursor-not-allowed disabled:opacity-50",
        className
      )}
      {...props}
    >
      {children}
    </select>
  );
}

export function FormField({
  label,
  error,
  children,
  className,
}: {
  label?: string;
  error?: string;
  children: React.ReactNode;
  className?: string;
}) {
  return (
    <div className={cn("space-y-1.5", className)}>
      {label ? <label className="block text-sm font-medium text-secondary">{label}</label> : null}
      {children}
      {error ? <p className="text-xs text-red-600">{error}</p> : null}
    </div>
  );
}

export function Checkbox({
  label,
  className,
  ...props
}: React.InputHTMLAttributes<HTMLInputElement> & { label?: string }) {
  return (
    <label className={cn("flex items-center gap-2 text-sm text-secondary", className)}>
      <input
        type="checkbox"
        className="h-4 w-4 rounded border-[var(--border)] text-primary focus:ring-primary/30"
        {...props}
      />
      {label}
    </label>
  );
}

/**
 * Money field with live thousand separators.
 * RHF value stays as plain integer Rial digits (e.g. "1500000"); display shows "1,500,000".
 * No decimal places — Iranian Rial.
 */
export const MoneyInput = React.forwardRef<
  HTMLInputElement,
  Omit<React.InputHTMLAttributes<HTMLInputElement>, "type">
>(function MoneyInput({ className, value, defaultValue, onChange, onBlur, ...props }, ref) {
  const isControlled = value !== undefined;
  const [inner, setInner] = React.useState(() =>
    toRialInteger(defaultValue != null ? String(defaultValue) : "")
  );

  const raw = isControlled ? toRialInteger(value == null ? "" : String(value)) : inner;
  const display = formatMoneyGrouped(raw);

  return (
    <input
      {...props}
      ref={ref}
      type="text"
      inputMode="numeric"
      dir="ltr"
      autoComplete="off"
      value={display}
      className={cn(
        "flex h-10 w-full rounded-xl border border-[var(--border)] bg-[var(--surface)] px-3 py-2 text-sm tabular-nums text-secondary",
        "placeholder:text-[var(--muted)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/30",
        "disabled:cursor-not-allowed disabled:opacity-50",
        className
      )}
      onChange={(e) => {
        // Keep typing fluid; strip non-digits / separators, then integerize.
        const parsed = toRialInteger(parseMoneyInput(e.target.value));
        if (!isControlled) setInner(parsed);
        e.target.value = parsed;
        onChange?.(e);
      }}
      onBlur={(e) => {
        const parsed = toRialInteger(e.target.value);
        if (!isControlled) setInner(parsed);
        e.target.value = parsed;
        onBlur?.(e);
      }}
    />
  );
});
