"use client"
import { formatDate, setHours, setMinutes } from "date-fns"
import React, { useState } from "react"
import { Schedule } from "../../icons"
import { classNames } from "../../utils"
import { DatePicker, DatePickerProps } from "../DatePicker"
import { FlexCenter } from "../FlexCenter"
import { Input, InputProps } from "../Input"

export type DateTimePickerProps = Pick<
  DatePickerProps,
  | "selected"
  | "onSelect"
  | "size"
  | "placeholder"
  | "format"
  | "disabled"
  | "error"
  | "portal"
> & {
  className?: string
  overrides?: {
    DatePicker?: Partial<DatePickerProps>
    TimeInput?: Partial<InputProps>
  }
}

const HTML_TIME_INPUT = "HH:mm"

export function DateTimePicker({
  className,
  overrides,
  selected,
  onSelect,
  size = "md",
  format: formatFn,
  placeholder,
  disabled,
  error,
  portal,
}: DateTimePickerProps) {
  const iconSize = size === "lg" ? 24 : size === "xs" ? 16 : 20
  const [time, setTime] = useState<string | undefined>(
    selected ? formatDate(selected, HTML_TIME_INPUT) : "00:00",
  )

  const updateDateWithTime = (date: Date, time: string) => {
    const [hours, minutes] = time.split(":").map(Number)
    return setMinutes(setHours(date, hours), minutes)
  }

  const disabledInput = typeof disabled === "boolean" && disabled

  return (
    <FlexCenter className={classNames("gap-4", className)}>
      <DatePicker
        disabled={disabled}
        error={error}
        format={formatFn}
        placeholder={placeholder}
        portal={portal}
        selected={selected}
        size={size}
        onSelect={(date: Date | undefined) => {
          if (!date) {
            return
          }

          const updatedDate = time ? updateDateWithTime(date, time) : date
          onSelect?.(updatedDate)
        }}
        {...overrides?.DatePicker}
      />
      <Input
        disabled={disabledInput}
        endEnhancer={<Schedule size={iconSize} />}
        error={error}
        overrides={{
          Input: {
            ...overrides?.TimeInput?.overrides?.Input,
            className: classNames(
              "font-mono [&::-webkit-calendar-picker-indicator]:hidden",
              overrides?.TimeInput?.overrides?.Input?.className,
            ),
          },
        }}
        size={size}
        type="time"
        value={time}
        onChange={e => {
          const time = e.target.value
          setTime(time)

          if (!selected) {
            return
          }

          const updatedDate = updateDateWithTime(selected, time)
          onSelect?.(updatedDate)
        }}
        {...overrides?.TimeInput}
        className={classNames("w-fit", overrides?.TimeInput?.className)}
      />
    </FlexCenter>
  )
}
