import type { JSX } from "preact";
import { cn } from "../../utils/cn.ts";
import { Text } from "./Text.tsx";
import { ChevronDown } from "lucide-preact";

type SelectSize = "sm" | "md" | "lg";

export interface SelectProps
  extends Omit<JSX.IntrinsicElements['select'], 'size'> {
  label?: string;
  error?: string;
  size?: SelectSize;
}

export function Select(props: SelectProps): JSX.Element {
  const { class: classProp, label, error, size = "lg", children, ...rest } = props;

  const sizeClasses = {
    sm: "pl-2.5 pr-8 py-0.5 text-xs",
    md: "pl-3 pr-8 py-1 text-sm",
    lg: "pl-4 pr-9 py-2 text-sm",
  };

  const className = cn(
    "block w-full bg-zinc-50 hover:bg-zinc-50/90 dark:bg-zinc-600 dark:hover:bg-zinc-600/90 text-zinc-900 dark:text-zinc-100 border border-zinc-200 dark:border-zinc-500/70 rounded-md cursor-pointer focus:outline-none focus:ring-0 appearance-none",
    sizeClasses[size],
    error
      ? "border-red-300 dark:border-red-500"
      : "",
    classProp,
  );

  return (
    <div>
      {label && (
        <Text as="label" size="sm" variant="label" className="block mb-2">
          {label}
        </Text>
      )}
      <div className="relative">
        <select class={className} {...rest}>
          {children}
        </select>
        <div className="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none">
          <ChevronDown size={16} className="text-zinc-500 dark:text-zinc-400" />
        </div>
      </div>
      {error && (
        <Text as="p" size="xs" variant="error" className="mt-1">
          {error}
        </Text>
      )}
    </div>
  );
}
