"use client"
import { useEffect, useRef, useState } from "react"
import { useFormContext, useWatch } from "react-hook-form"

import { dt } from "@/lib/dt"

import Body from "@/components/TempDesignSystem/Text/Body"
import useLang from "@/hooks/useLang"

import DatePicker from "./DatePicker"

import styles from "./date-picker.module.css"

import type { DateRange } from "react-day-picker"

import type { DatePickerFormProps } from "@/types/components/datepicker"

export default function DatePickerForm({ name = "date" }: DatePickerFormProps) {
  const lang = useLang()
  const [isOpen, setIsOpen] = useState(false)
  const selectedDate = useWatch({ name })
  const { register, setValue } = useFormContext()
  const ref = useRef<HTMLDivElement | null>(null)

  function close() {
    setIsOpen(false)
  }

  function handleOnClick() {
    setIsOpen((prevIsOpen) => !prevIsOpen)
  }

  function handleSelectDate(selected: DateRange) {
    setValue(name, {
      from: dt(selected.from).format("YYYY-MM-DD"),
      to: dt(selected.to).format("YYYY-MM-DD"),
    })
  }

  useEffect(() => {
    function handleClickOutside(evt: Event) {
      const target = evt.target as HTMLElement
      if (ref.current && target && !ref.current.contains(target)) {
        setIsOpen(false)
      }
    }

    document.addEventListener("click", handleClickOutside)

    return () => {
      document.removeEventListener("click", handleClickOutside)
    }
  }, [setIsOpen])

  const selectedFromDate = dt(selectedDate.from)
    .locale(lang)
    .format("ddd D MMM")
  const selectedToDate = dt(selectedDate.to).locale(lang).format("ddd D MMM")

  return (
    <div className={styles.container} data-isopen={isOpen} ref={ref}>
      <button className={styles.btn} onClick={handleOnClick} type="button">
        <Body className={styles.body}>
          {selectedFromDate} - {selectedToDate}
        </Body>
      </button>
      <input {...register("date.from")} type="hidden" />
      <input {...register("date.to")} type="hidden" />
      <div aria-modal className={styles.hideWrapper} role="dialog">
        <DatePicker
          close={close}
          handleOnSelect={handleSelectDate}
          initialSelected={selectedDate}
        />
      </div>
    </div>
  )
}
