"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,
  hint,
  children,
  className,
}: {
  label?: string;
  error?: string;
  hint?: 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}
      {hint && !error ? <p className="text-xs text-[var(--muted)]">{hint}</p> : null}
      {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);
        // Clone event target value so RHF watch/Controller always sees digits (not display commas).
        const next = {
          ...e,
          target: { ...e.target, value: parsed, name: (props.name as string) || e.target.name },
          currentTarget: {
            ...e.currentTarget,
            value: parsed,
            name: (props.name as string) || e.currentTarget.name,
          },
        } as typeof e;
        onChange?.(next);
      }}
      onBlur={(e) => {
        const parsed = toRialInteger(parseMoneyInput(e.target.value));
        if (!isControlled) setInner(parsed);
        const next = {
          ...e,
          target: { ...e.target, value: parsed, name: (props.name as string) || e.target.name },
          currentTarget: {
            ...e.currentTarget,
            value: parsed,
            name: (props.name as string) || e.currentTarget.name,
          },
        } as typeof e;
        onBlur?.(next);
      }}
    />
  );
});
