import { cn } from '@/lib/utils';
import { useEffect, useRef } from 'react';

const TIMES = Array.from({ length: 96 }, (_, i) => {
  const hours = Math.floor(i / 4);
  const minutes = (i % 4) * 15;
  const h12 = hours % 12 || 12;
  const ampm = hours < 12 ? 'AM' : 'PM';
  return {
    value: i,
    label: `${String(h12).padStart(2, '0')}:${String(minutes).padStart(2, '0')} ${ampm}`,
    hours,
    minutes,
  };
});

export function TimePicker({
  value,
  onChange,
  className,
}: {
  value?: Date;
  onChange: (date: Date) => void;
  className?: string;
}) {
  const listRef = useRef<HTMLDivElement>(null);
  const selectedRef = useRef<HTMLButtonElement>(null);

  const selectedIndex = value
    ? value.getHours() * 4 + Math.floor(value.getMinutes() / 15)
    : -1;

  useEffect(() => {
    selectedRef.current?.scrollIntoView({ block: 'nearest' });
  }, []);

  return (
    <div
      ref={listRef}
      className={cn('h-[280px] w-28 overflow-y-auto p-1', className)}
    >
      {TIMES.map(({ value: idx, label, hours, minutes }) => {
        const isSelected = idx === selectedIndex;
        return (
          <button
            key={label}
            ref={isSelected ? selectedRef : undefined}
            type="button"
            onClick={() => {
              const next = value ? new Date(value) : new Date();
              next.setHours(hours, minutes, 0, 0);
              onChange(next);
            }}
            className={cn(
              'flex w-full cursor-pointer items-center rounded px-2 py-1.5 text-left text-sm transition-colors',
              isSelected
                ? 'bg-primary text-primary-foreground'
                : 'hover:bg-black/5 dark:hover:bg-white/10',
            )}
          >
            {label}
          </button>
        );
      })}
    </div>
  );
}
