import type { ReactNode, SelectHTMLAttributes } from "react";
import { cn } from "@/lib/utils";
import type { ApiProductUnit } from "@/lib/api/types";

export const inputClass =
  "w-full rounded-lg border border-gray-200 px-3 py-2 text-sm focus:border-[#CC1414] focus:outline-none focus:ring-1 focus:ring-[#CC1414]";

export function RequiredMark() {
  return <span className="text-red-500"> *</span>;
}

export function ErrorText({ message }: { message?: string }) {
  if (!message) return null;
  return <p className="mt-1 text-xs text-red-600">{message}</p>;
}

export function SectionCard({
  title,
  subtitle,
  children,
  className,
}: {
  title: string;
  subtitle?: string;
  children: ReactNode;
  className?: string;
}) {
  return (
    <section className={cn("rounded-xl bg-white p-5 shadow-sm ring-1 ring-gray-100", className)}>
      <div className="mb-4">
        <h3 className="text-sm font-semibold text-gray-900">{title}</h3>
        {subtitle ? <p className="mt-0.5 text-xs text-gray-500">{subtitle}</p> : null}
      </div>
      {children}
    </section>
  );
}

/**
 * The units dropdown, from the admin-managed `product_units` master.
 *
 * `current` keeps a previously saved unit selectable even after an admin
 * retires it: a <select> whose value matches no option falls back to blank, and
 * saving the step would then quietly wipe a value the seller never touched.
 */
export function UnitSelect({
  units,
  current,
  placeholder = "Select unit",
  className,
  ...rest
}: {
  units: ApiProductUnit[];
  current?: string;
  placeholder?: string;
} & SelectHTMLAttributes<HTMLSelectElement>) {
  const saved = (current ?? "").trim();
  const isRetired = saved !== "" && !units.some((unit) => unit.short_name === saved);

  return (
    <select {...rest} className={cn(inputClass, className)}>
      <option value="">{placeholder}</option>
      {units.map((unit) => (
        <option key={unit.id} value={unit.short_name}>
          {unit.short_name} — {unit.name}
        </option>
      ))}
      {isRetired ? <option value={saved}>{saved} (no longer listed)</option> : null}
    </select>
  );
}

export function Field({
  label,
  required,
  error,
  hint,
  className,
  children,
}: {
  label: string;
  required?: boolean;
  error?: string;
  /** Small grey note under the control. */
  hint?: string;
  className?: string;
  children: ReactNode;
}) {
  return (
    <div className={className}>
      <label className="mb-1 block text-xs font-medium text-gray-700">
        {label}
        {required ? <RequiredMark /> : null}
      </label>
      {children}
      {hint && !error ? <p className="mt-1 text-xs text-gray-500">{hint}</p> : null}
      <ErrorText message={error} />
    </div>
  );
}
