"use client";

import { Input } from "@/components/ui/input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";

import {
  AMOUNT_CONSERVING_OPERATORS,
  RATIO_OPERATORS,
  RATIO_OPERATOR_LABELS,
  type RatioOperator,
} from "../_lib/schema";

type Props = {
  id?: string;
  operator: RatioOperator;
  factor: string;
  onOperatorChange: (operator: RatioOperator) => void;
  onFactorChange: (factor: string) => void;
  disabled?: boolean;
};

export function RatioInput({
  id,
  operator,
  factor,
  onOperatorChange,
  onFactorChange,
  disabled,
}: Props) {
  return (
    <div className="flex gap-2">
      <Select
        value={operator}
        onValueChange={(next) => onOperatorChange(next as RatioOperator)}
        disabled={disabled}
      >
        <SelectTrigger className="w-36 shrink-0">
          <SelectValue />
        </SelectTrigger>
        <SelectContent>
          {RATIO_OPERATORS.map((value) => (
            <SelectItem key={value} value={value}>
              {RATIO_OPERATOR_LABELS[value]}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>
      <Input
        id={id}
        value={factor}
        onChange={(event) => onFactorChange(event.target.value)}
        inputMode="decimal"
        placeholder="10"
        disabled={disabled}
      />
    </div>
  );
}

/**
 * Restates the ratio as its effect on a holding, so the operator can catch an
 * inverted factor before it reaches the preview.
 */
export function RatioHint({
  operator,
  factor,
}: {
  operator: RatioOperator;
  factor: string;
}) {
  const parsed = Number(factor);

  if (!factor.trim() || !Number.isFinite(parsed) || parsed === 0) {
    return (
      <span className="text-muted-foreground">
        The ratio applies to quantity. Price moves the opposite way.
      </span>
    );
  }

  if (!AMOUNT_CONSERVING_OPERATORS.includes(operator)) {
    return (
      <span className="text-amber-600 dark:text-amber-500">
        {operator === "+" ? "Adds" : "Subtracts"} {parsed} to each quantity. This has
        no matching price move, so the amount will change — every affected row is
        flagged in the preview.
      </span>
    );
  }

  const quantityFactor = operator === "*" ? parsed : 1 / parsed;
  const display = (value: number) =>
    Number.isInteger(value) ? String(value) : value.toFixed(4).replace(/0+$/, "");

  return (
    <span className="text-muted-foreground">
      For every <strong>1</strong> share you get{" "}
      <strong>{display(quantityFactor)}</strong>. Price is divided by the same
      factor, so the amount stays unchanged.
    </span>
  );
}
