'use client';

import { ChevronDown } from 'lucide-react';
import React, { forwardRef, useId } from 'react';

interface DropdownProps extends React.SelectHTMLAttributes<HTMLSelectElement> {
  label?: string;
  error?: string;
}

export const Dropdown = forwardRef<HTMLSelectElement, DropdownProps>(
  ({ label, error, className = '', id, children, ...props }, ref) => {
    const genId = useId();
    const selectId = id ?? genId;

    return (
      <div className="w-full">
        {label && (
          <label
            htmlFor={selectId}
            className="block text-sm font-medium text-text-secondary mb-1"
          >
            {label}
          </label>
        )}

        <div className="relative">
          <select
            ref={ref}
            id={selectId}
            className={`
              form-select w-full appearance-none rounded-[var(--radius-md)] border
              ${error ? 'border-red-500' : 'border-border'}
              bg-background-card text-text-primary
              pl-4 pr-14 py-2.5 sm:py-2 text-base sm:text-sm
              focus:outline-none focus:ring-2 focus:ring-primary/35 focus:border-border-strong
              disabled:opacity-50 disabled:cursor-not-allowed
              transition-all duration-200 shadow-[inset_0_1px_0_rgba(255,255,255,0.02)]
              ${className}
            `}
            {...props}
          >
            {children}
          </select>

          <div
            className="pointer-events-none absolute inset-y-0 right-5 flex items-center text-text-muted"
            aria-hidden
          >
            <ChevronDown className="h-4 w-4 icon-flat" />
          </div>
        </div>

        {error && (
          <p className="mt-1 text-sm text-red-500">
            {error}
          </p>
        )}
      </div>
    );
  },
);

Dropdown.displayName = 'Dropdown';
