"use client";

import { forwardRef, type SelectHTMLAttributes, type ReactNode } from "react";

interface SelectProps extends SelectHTMLAttributes<HTMLSelectElement> {
  label?: string;
  error?: string;
  leftIcon?: ReactNode;
  options: { value: string; label: string; disabled?: boolean }[];
}

const Select = forwardRef<HTMLSelectElement, SelectProps>(
  ({ label, error, leftIcon, options, className = "", ...props }, ref) => {
    return (
      <div className="w-full">
        {label && (
          <label className="mb-1.5 block text-sm font-medium text-[var(--text-secondary)]">
            {label}
          </label>
        )}
        <div
          className={`flex items-center gap-3 rounded-xl border bg-[var(--input-bg)] px-3 py-2.5 transition focus-within:border-[var(--accent)] focus-within:ring-1 focus-within:ring-[var(--accent)]/20 ${
            error ? "border-red-500" : "border-[var(--border)]"
          }`}
        >
          {leftIcon && (
            <span className="flex shrink-0 text-[var(--text-muted)]">{leftIcon}</span>
          )}
          <select
            ref={ref}
            className={`w-full appearance-none bg-transparent text-sm text-[var(--text-primary)] outline-none disabled:opacity-60 ${className}`}
            {...props}
          >
            {options.map((opt) => (
              <option key={opt.value} value={opt.value} disabled={opt.disabled}>
                {opt.label}
              </option>
            ))}
          </select>
          <svg
            className="h-4 w-4 shrink-0 text-[var(--text-muted)]"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
          >
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
          </svg>
        </div>
        {error && <p className="mt-1 text-xs text-red-500">{error}</p>}
      </div>
    );
  }
);

Select.displayName = "Select";

export default Select;
