"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 { 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)

  const [isSelectingFrom, setIsSelectingFrom] = useState(true)

  function close() {
    setIsOpen(false)
  }

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

  function handleSelectDate(selected: Date) {
    if (isSelectingFrom) {
      setValue(name, {
        fromDate: dt(selected).format("YYYY-MM-DD"),
        toDate: undefined,
      })
      setIsSelectingFrom(false)
    } else {
      const fromDate = dt(selectedDate.fromDate)
      const toDate = dt(selected)
      if (toDate.isAfter(fromDate)) {
        setValue(name, {
          fromDate: selectedDate.fromDate,
          toDate: toDate.format("YYYY-MM-DD"),
        })
      } else {
        setValue(name, {
          fromDate: toDate.format("YYYY-MM-DD"),
          toDate: selectedDate.fromDate,
        })
      }
      setIsSelectingFrom(true)
    }
  }

  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.fromDate)
    .locale(lang)
    .format("ddd D MMM")
  const selectedToDate = !!selectedDate.toDate
    ? dt(selectedDate.toDate).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.fromDate")} type="hidden" />
      <input {...register("date.toDate")} 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>
  )
}
