import { format } from 'date-fns';

import { ComponentPropsWithRef, FC } from 'react';
import { Button } from '@/components/ui/button';
import { Calendar } from '@/components/ui/calendar';
import { Icon } from '@/components/ui/icon';
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from '@/components/ui/popover';
import { cn } from '@/lib/utils';

type DataPickerProps = Omit<
  ComponentPropsWithRef<'button'>,
  'value' | 'onChange'
> & {
  value: Date;
  onChange?: (date: Date | undefined) => void;
};

export const DatePicker: FC<DataPickerProps> = ({
  value,
  onChange,
  ...props
}) => {
  return (
    <Popover>
      <PopoverTrigger asChild>
        <Button
          variant={'outline'}
          className={cn(
            'w-[280px] justify-start text-left font-normal',
            !value && 'text-muted-foreground',
          )}
          {...props}
        >
          <Icon className="i-tabler:calendar mr-2 size-4" />
          {value ? format(value, 'PPP') : <span>Pick a date</span>}
        </Button>
      </PopoverTrigger>
      <PopoverContent className="w-auto p-0">
        <Calendar
          mode="single"
          selected={value}
          onSelect={onChange}
          autoFocus
          required={false}
        />
      </PopoverContent>
    </Popover>
  );
};
