"use client"
import { da, de, fi, nb, sv } from "date-fns/locale"
import { useEffect, useRef, useState } from "react"
import { useFormContext, useWatch } from "react-hook-form"

import { Lang } from "@/constants/languages"
import { dt } from "@/lib/dt"

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

import DatePickerDesktop from "./Screen/Desktop"
import DatePickerMobile from "./Screen/Mobile"

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

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

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

const locales = {
  [Lang.da]: da,
  [Lang.de]: de,
  [Lang.fi]: fi,
  [Lang.no]: nb,
  [Lang.sv]: sv,
}

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.body.addEventListener("click", handleClickOutside)
    return () => {
      document.body.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">
        <DatePickerDesktop
          close={close}
          handleOnSelect={handleSelectDate}
          locales={locales}
          selectedDate={selectedDate}
        />
        <DatePickerMobile
          close={close}
          handleOnSelect={handleSelectDate}
          locales={locales}
          selectedDate={selectedDate}
        />
      </div>
    </div>
  )
}
