"use client"

import { faAngleLeft, faAngleRight, faAnglesLeft, faAnglesRight, faXmark, faAngleDown } from "@fortawesome/free-solid-svg-icons"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import { Button, Calendar, Popover, Typography } from "antd"
import dayjs, { Dayjs } from "dayjs"
import { useTranslations } from "next-intl"
import Image from "next/image"
import Link from "next/link"
import { forwardRef, useEffect, useImperativeHandle, useState } from "react"

interface DatePickerRef {
  updateDatePicker: (start: number, end: number) => void
}

type IProps = {
  onDateChange?: (start: number, end: number) => void
  className?: string
}

const rangePresets = [
  {
    label: "To Day",
    value: "today",
  },
  {
    label: "Yesterday",
    value: "yesterday",
  },
  {
    label: "Last 7 Days",
    value: "last7day",
  },
  {
    label: "Last 30 Days",
    value: "last30day",
  },
  {
    label: "This Month",
    value: "thismonth",
  },
  {
    label: "Last Month",
    value: "lastmonth",
  },
  {
    label: "Custom Range",
    value: "custom",
  },
]

export const DatePickerCustom = forwardRef<DatePickerRef, IProps>(({ onDateChange, className }, ref) => {
  const [customDate, setCustomDate] = useState<any>([])
  const [presets, setPresets] = useState<any>(null)
  const [openFilter, setOpenFilter] = useState(false)
  const [leftDateView, setLeftDateView] = useState<Dayjs>(dayjs())
  const trans = useTranslations("general")

  useEffect(() => {
    if (customDate.length === 2) {
      onDateChange?.(customDate[0].unix(), customDate[1].unix())
    } else if (customDate.length === 0) {
      onDateChange?.(0, 0)
    }
  }, [customDate])

  useImperativeHandle(ref, () => ({
    updateDatePicker(start: number, end: number) {
      setPresets({
        label: "Custom Range",
        value: "custom",
      })
      const newStart = dayjs.unix(start)
      const newEnd = dayjs.unix(end)
      setCustomDate([newStart, newEnd])
      setLeftDateView(newStart)
    },
  }))

  const handleOpenChange = (open: boolean) => {
    setOpenFilter(open)
  }

  const disabledDate = (current: Dayjs) => {
    return current && (current > dayjs().endOf("day") || current < dayjs().subtract(3, "year").startOf("year"))
  }

  useEffect(() => {
    const rightView = leftDateView.add(1, "month")
    if (rightView.isAfter(dayjs())) {
      setLeftDateView(dayjs().subtract(1, "month"))
    }
  }, [leftDateView])

  const getRightDateView = () => {
    const nextMonth = leftDateView.add(1, "month")
    return nextMonth.isAfter(dayjs()) ? dayjs() : nextMonth
  }

  const onClickPreset = (item: any) => {
    if (item.value !== "custom") setOpenFilter(false)
    setPresets(item)
    let dates: any[] = []
    switch (item.value) {
      case "today":
        dates = [dayjs().startOf("day"), dayjs().endOf("day")]
        break
      case "yesterday":
        dates = [dayjs().add(-1, "d").startOf("day"), dayjs().add(-1, "d").endOf("day")]
        break
      case "last7day":
        dates = [dayjs().subtract(1, "week").startOf("week").add(1, "d"), dayjs().subtract(1, "week").endOf("week").add(1, "d")]
        break
      case "last30day":
        dates = [dayjs().startOf("day").subtract(29, "day"), dayjs().endOf("day")]
        break
      case "thismonth":
        dates = [dayjs().startOf("month"), dayjs().endOf("month")]
        break
      case "lastmonth":
        dates = [dayjs().subtract(1, "month").startOf("month"), dayjs().subtract(1, "month").endOf("month")]
        break
      default:
        dates = []
    }
    if (item.value !== "custom") {
      setCustomDate(dates)
    }
  }

  const onSelectDate = (date: Dayjs) => {
    if (!customDate) {
      setCustomDate([date])
      setLeftDateView(date)
    } else if (customDate[0] && !customDate[1]) {
      if (date.isBefore(customDate[0])) {
        setCustomDate([date, customDate[0]])
        setLeftDateView(date)
      } else {
        setCustomDate([customDate[0], date])
      }
      setOpenFilter(false)
    } else {
      setCustomDate([date])
      setLeftDateView(date)
    }
  }

  const headerRender = ({ value, onChange, type }: any, isLeft: boolean) => {
    const safeValue = value && dayjs.isDayjs(value) ? value : dayjs()

    const decreaseMonth = () => {
      const newValue = safeValue.subtract(1, "month")
      if (isLeft) {
        setLeftDateView(newValue)
      }
    }

    const increaseMonth = () => {
      const newValue = safeValue.add(1, "month")
      if (newValue.isAfter(dayjs())) return
      if (isLeft) {
        setLeftDateView(newValue)
      }
    }

    const decreaseYear = () => {
      const newValue = safeValue.subtract(1, "year")
      if (isLeft) {
        setLeftDateView(newValue)
      }
    }

    const increaseYear = () => {
      const newValue = safeValue.add(1, "year")
      if (newValue.isAfter(dayjs())) return
      if (isLeft) {
        setLeftDateView(newValue)
      }
    }

    return (
      <div className="p-[8px]">
        <div className="flex items-center">
          <Button
            type="link"
            icon={<FontAwesomeIcon icon={faAnglesLeft} />}
            onClick={decreaseYear}
            disabled={disabledDate(safeValue.subtract(1, "year"))}
          />
          <Button
            type="link"
            icon={<FontAwesomeIcon icon={faAngleLeft} />}
            onClick={decreaseMonth}
            disabled={disabledDate(safeValue.subtract(1, "month"))}
          />
          <Typography className="grow text-center">{safeValue.format("MMMM-YYYY")}</Typography>
          <Button
            type="link"
            icon={<FontAwesomeIcon icon={faAngleRight} />}
            onClick={increaseMonth}
            disabled={safeValue.add(1, "month").isAfter(dayjs())}
          />
          <Button
            type="link"
            icon={<FontAwesomeIcon icon={faAnglesRight} />}
            onClick={increaseYear}
            disabled={safeValue.add(1, "year").isAfter(dayjs())}
          />
        </div>
      </div>
    )
  }

  const fullCellRender = (date: Dayjs, info: { originNode: React.ReactElement; type: string }) => {
    if (info.type !== "date") {
      return info.originNode
    }

    if (disabledDate(date)) {
      return info.originNode
    }

    if (!customDate || !customDate[0] || !customDate[1]) {
      return info.originNode
    }

    const start = customDate[0].startOf("day")
    const end = customDate[1].startOf("day")
    const current = date.startOf("day")

    const renderCellContent = (className: string) => (
      <div className="ant-picker-cell-inner">
        <div className={`${className}`}>{date.date()}</div>
      </div>
    )

    if (current.isSame(start, "day") && current.isSame(end, "day")) {
      return renderCellContent("highlighted-range start end")
    } else if (current.isSame(start, "day")) {
      return renderCellContent("highlighted-range start")
    } else if (current.isSame(end, "day")) {
      return renderCellContent("highlighted-range end")
    } else if (current.isAfter(start, "day") && current.isBefore(end, "day")) {
      return renderCellContent("highlighted-range middle")
    }

    return info.originNode
  }

  const handleClearDate = () => {
    setCustomDate([])
    setLeftDateView(dayjs())
  }

  return (
    <div className={className}>
      <Popover
        title=""
        arrow={false}
        trigger="click"
        open={openFilter}
        onOpenChange={handleOpenChange}
        content={
          <div className="flex items-stretch bg-white">
            <div className="whitespace-nowrap border-solid border-t-0 border-l-0 border-b-0 border-[#eee]">
              <ul className="list-none">
                {rangePresets.map((item: any, index: number) => {
                  return (
                    <li
                      key={index}
                      onClick={() => onClickPreset(item)}
                      className={`py-1.5 pr-6 leading-[20px] pl-2 rounded-md flex items-center border border-secondary-20 mb-2 gap-2.5 ${
                        presets?.value === item.value ? "" : ""
                      }`}>
                      <span
                        className={`rounded-full border w-5 h-5 inline-flex justify-center items-center ${
                          presets?.value === item.value ? "border-primary-70" : "border-secondary-70"
                        }`}>
                        {presets?.value === item.value ? <span className="rounded-full bg-primary-70 w-3 h-3"></span> : null}
                      </span>
                      <a
                        className={`text-black hover:text-primary-70 py-1 ${presets?.value === item.value ? "text-primary-70" : ""}`}>
                        {item.label}
                      </a>
                    </li>
                  )
                })}
              </ul>
            </div>
            {presets?.value === "custom" ? (
              <div className="min-w-[500px] max-w-[800px] flex gap-4 pl-4">
                <div className="w-[250px]">
                  <Calendar
                    fullscreen={false}
                    value={leftDateView}
                    disabledDate={disabledDate}
                    onSelect={onSelectDate}
                    mode="month"
                    headerRender={(props) => headerRender(props, true)}
                    fullCellRender={fullCellRender}
                  />
                </div>
                <div className="w-[250px]">
                  <Calendar
                    fullscreen={false}
                    value={getRightDateView()}
                    disabledDate={disabledDate}
                    onSelect={onSelectDate}
                    mode="month"
                    headerRender={(props) => headerRender(props, false)}
                    fullCellRender={fullCellRender}
                  />
                </div>
              </div>
            ) : null}
          </div>
        }>
        <Button
          icon={
            <Image
              src="/img/icon/calendar_outline.svg"
              alt="Calendar"
              width={20}
              height={20}
              style={{
                width: "20px",
                height: "20px",
              }}
            />
          }
          className="!pl-[11px] !h-[50px] !pr-[50px] relative !min-w-60 flex items-center">
          <span className="grow">
            {customDate && customDate.length
              ? `${customDate[0].format("MMM DD, YYYY")} - ${customDate[1] ? customDate[1].format("MMM DD, YYYY") : ""}`
              : trans("select_date")}
          </span>
          <Link
            href="#"
            scroll={false}
            onClick={handleClearDate}
            className="absolute right-0 top-0 z-10 h-full pr-4 pl-2 inline-flex justify-center items-center !text-secondary-50">
            <FontAwesomeIcon icon={customDate && customDate.length ? faXmark : faAngleDown} />
          </Link>
        </Button>
      </Popover>
    </div>
  )
})
