import { differenceInCalendarDays } from "date-fns"
import React, { ComponentPropsWithoutRef, ElementRef, forwardRef } from "react"
import { useDuration } from "../../hooks/useDuration"
import { classNames } from "../../utils/classNames"
import { AnimatedNumber } from "../AnimatedNumber"
import { CenterAligned } from "../CenterAligned"
import { Flex } from "../Flex"
import { Text } from "../Text"

export type CountdownProps = {
  end: Date
  className?: string
  showDaysOnly?: boolean
  size?: "sm" | "lg"
} & ComponentPropsWithoutRef<"div">

function CountdownCell({
  value,
  unit,
  size,
}: {
  value: number
  unit: "years" | "months" | "days" | "hours" | "mins" | "secs"
  size: "sm" | "lg"
}) {
  return (
    <CenterAligned
      className={classNames("rounded-lg bg-bg-primary", {
        "size-[50px]": size === "sm",
        "size-[60px]": size === "lg",
      })}
    >
      <Text className="font-mono" size="sm" weight="semibold">
        <AnimatedNumber value={value} />
      </Text>
      <Text
        className="font-mono uppercase text-text-secondary"
        size={size === "sm" ? "xs" : "sm"}
        weight="semibold"
      >
        {unit}
      </Text>
    </CenterAligned>
  )
}

export const Countdown = forwardRef<ElementRef<"div">, CountdownProps>(
  function Countdown({ className, end, showDaysOnly, size = "lg" }, ref) {
    const now = Date.now()
    const duration = useDuration(end)

    const {
      years = 0,
      months = 0,
      days = 0,
      hours = 0,
      minutes = 0,
      seconds = 0,
    } = duration

    const actualDays =
      showDaysOnly && (years > 0 || months > 0)
        ? differenceInCalendarDays(end, now)
        : days

    return (
      <Flex className={classNames("flex gap-4", className)} ref={ref}>
        {!showDaysOnly && years && (
          <CountdownCell size={size} unit="years" value={years} />
        )}
        {!showDaysOnly && months && (
          <CountdownCell size={size} unit="months" value={months} />
        )}
        <CountdownCell size={size} unit="days" value={actualDays} />
        <CountdownCell size={size} unit="hours" value={hours} />
        <CountdownCell size={size} unit="mins" value={minutes} />
        <CountdownCell size={size} unit="secs" value={seconds} />
      </Flex>
    )
  },
)
