import { Calendar } from '@/components/ui/calendar';
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from '@/components/ui/popover';
import { TimePicker } from '@/components/ui/time-picker';
import { cn } from '@/lib/utils';
import { CalendarBlankIcon } from '@phosphor-icons/react';
import dayjs from 'dayjs';
import { useTranslation } from 'react-i18next';

export function DatetimePicker({
  value,
  onChange,
  placeholder = 'Pick date & time',
  className,
  disabled,
}: {
  value?: string;
  onChange: (value: string) => void;
  placeholder?: string;
  className?: string;
  disabled?: boolean;
}) {
  const date = value ? new Date(value) : undefined;
  const { t } = useTranslation();

  const handleDateSelect = (selected: Date | undefined) => {
    if (!selected) return;
    const next = date ? new Date(date) : new Date(selected);
    next.setFullYear(
      selected.getFullYear(),
      selected.getMonth(),
      selected.getDate(),
    );
    onChange(dayjs(next).format('YYYY-MM-DD HH:mm:ss'));
  };

  const handleTimeChange = (next: Date) => {
    onChange(dayjs(next).format('YYYY-MM-DD HH:mm:ss'));
  };

  return (
    <Popover>
      <PopoverTrigger asChild>
        <button
          type="button"
          disabled={disabled}
          className={cn(
            'flex h-11 w-full items-center justify-between rounded-md border border-black/5 bg-black/5 px-3 text-left text-sm transition-colors',
            'hover:bg-black/10 focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none',
            'disabled:cursor-not-allowed disabled:opacity-50',
            !date && 'text-muted-foreground',
            className,
          )}
        >
          <span>
            {date ? dayjs(date).format('MMM D, YYYY hh:mm A') : placeholder}
          </span>
          <CalendarBlankIcon className="size-4 shrink-0 opacity-50" />
        </button>
      </PopoverTrigger>
      <PopoverContent className="w-auto p-0" align="start">
        <div className="flex">
          <Calendar mode="single" selected={date} onSelect={handleDateSelect} />
          <div className="flex flex-col border-l border-black/10">
            <p className="px-3 pt-3 pb-1 text-sm font-medium text-foreground">
              {t('Time')}
            </p>
            <TimePicker
              value={date}
              onChange={handleTimeChange}
              className="h-full max-h-80"
            />
          </div>
        </div>
      </PopoverContent>
    </Popover>
  );
}
