"use client"

import * as React from "react"
import { Clock8Icon } from "lucide-react"

import { Input } from "@/components/ui/input"
import { cn } from "@/lib/utils"

type TimePickerProps = {
  value?: string | null
  onChange?: (value: string) => void
  className?: string
  placeholder?: string
  stepMinutes?: number
  disabled?: boolean
}

export function TimePicker({ value, onChange, className, placeholder = "Selecionar horário", stepMinutes = 15, disabled }: TimePickerProps) {
  const handleChange = React.useCallback(
    (event: React.ChangeEvent<HTMLInputElement>) => {
      onChange?.(event.target.value)
    },
    [onChange]
  )

  const stepSeconds = React.useMemo(() => {
    if (!stepMinutes || stepMinutes <= 0) return undefined
    return Math.max(1, Math.round(stepMinutes * 60))
  }, [stepMinutes])

  return (
    <div className="relative">
      <div className="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3 text-muted-foreground">
        <Clock8Icon aria-hidden className="size-4" />
      </div>
      <Input
        type="time"
        value={value ?? ""}
        onChange={handleChange}
        step={stepSeconds}
        disabled={disabled}
        aria-label={placeholder}
        className={cn(
          "pl-9 text-sm [appearance:textfield] [&::-webkit-calendar-picker-indicator]:hidden [&::-webkit-calendar-picker-indicator]:appearance-none",
          className
        )}
      />
    </div>
  )
}
