"use client";
import { cx } from "@karma/cva";
import { ChevronDownIcon } from "@karma/icon";
import React from "react";
import { DayPicker } from "react-day-picker";
import { Button } from "../button";
import DayButton from "./dayButton";
import Dropdown from "./dropdown";

export type CalendarProps = React.ComponentProps<typeof DayPicker> & {
  handleClearDates?: () => void;
  showPreviousMonth?: boolean;
  className?: string;
  showClearDates?: boolean;
  showYearDropdown?: boolean;
  showContinueButton?: {
    setOpenPopup: (value: boolean) => void;
  };
};

const Calendar: React.FC<CalendarProps> = ({
  handleClearDates,
  showPreviousMonth = false,
  className,
  showClearDates = false,
  showYearDropdown = false,
  showContinueButton,
  ...props
}) => {
  const isBackButtonVisible = (selectedMonth: Date | undefined) => {
    if (showPreviousMonth) return true;
    if (!selectedMonth) return false;

    const now = new Date();
    return !(
      selectedMonth.getFullYear() === now.getFullYear() &&
      selectedMonth.getMonth() === now.getMonth()
    );
  };

  const isNextButtonVisible = (selectedMonth: Date | undefined) => {
    if (!props?.endMonth || !selectedMonth) return true;

    return !(
      selectedMonth.getFullYear() >= props?.endMonth.getFullYear() &&
      selectedMonth.getMonth() >= props?.endMonth.getMonth()
    );
  };

  return (
    <div
      className={cx(
        `relative mx-auto h-[400px] w-fit max-w-2xl rounded-lg bg-background p-4 shadow-lg`,
        className,
      )}
    >
      <DayPicker
        {...props}
        className="border-none"
        classNames={{
          root: "rounded-2xl p-1 relative",
          months: `text-primary justify-center flex ${
            (props.numberOfMonths ?? 1) > 1 ? "space-x-4" : ""
          }`,
          month: "h-full",
          caption_label: `text-lg font-medium flex items-center justify-center ${showYearDropdown && "hidden"}`,
          nav: "space-x-1 flex items-center w-full absolute top-4 justify-between",
          button_next: isNextButtonVisible(props.month)
            ? "absolute right-1 text-black opacity-50 hover:opacity-100 disabled:opacity-0"
            : "hidden",
          button_previous: isBackButtonVisible(props.month)
            ? "absolute left-1 text-black opacity-50 hover:opacity-100"
            : "hidden",
          month_grid: "w-full h-full mt-4",
          weekday: "text-center text-muted rounded-md w-9 font-normal",
          day: `h-10 w-10 p-0 font-normal ${props.mode !== "range" && "aria-selected:rounded-full"}`,
          day_button: "border-0 h-full w-full p-0",
          chevron: "text-primary",
          disabled:
            "text-muted [&.aria-selected\\:bg-accent-light]:bg-accent-light",
          selected:
            "bg-accent font-normal text-white hover:bg-accent rounded-full hover:text-white focus:bg-accent focus:text-white",
          today: "text-accent",
          range_middle:
            "bg-accent-light text-black font-normal disabled:bg-accent-light !rounded-none",
          range_end:
            "bg-accent text-white hover:bg-accent hover:text-white focus:bg-accent focus:text-white rounded-l-none !rounded-r-full font-normal",
          range_start:
            "bg-accent text-white hover:bg-accent hover:text-white focus:bg-accent focus:text-white rounded-r-none !rounded-l-full font-normal",
          hidden: "invisible",
          outside: "invisible",
          month_caption: "text-lg font-medium",
          dropdowns: "gap-4 flex items-center justify-center",
        }}
        components={{
          Dropdown: Dropdown,
          DayButton: DayButton,
          NextMonthButton: (props) => <NextMonthButton {...props} />,
          PreviousMonthButton: (props) => <PreviousMonthButton {...props} />,
        }}
        {...(showYearDropdown && { captionLayout: "dropdown" })}
      />
      {(showClearDates || showContinueButton) && (
        <div className="absolute bottom-4 right-6 flex items-center">
          {showClearDates && (
            <Button
              className="text-xs text-muted "
              variant="none"
              onClick={handleClearDates}
            >
              Clear Dates
            </Button>
          )}
          {showContinueButton && (
            <Button
              className="text-xs"
              variant="accent"
              onClick={() => showContinueButton.setOpenPopup(false)}
            >
              Continue
            </Button>
          )}
        </div>
      )}
    </div>
  );
};

export * from "./useCalendar";
export { Calendar };

const NextMonthButton: React.FC<
  React.ComponentProps<typeof ChevronDownIcon>
> = (props) => {
  return (
    <Button variant="none" {...props} className={`p-0 ${props.className}`}>
      <ChevronDownIcon className="-rotate-90 text-primary dark:text-white" />
    </Button>
  );
};

const PreviousMonthButton: React.FC<
  React.ComponentProps<typeof ChevronDownIcon>
> = (props) => {
  return (
    <Button variant="none" {...props} className={`p-0 ${props.className}`}>
      <ChevronDownIcon className="rotate-90 text-primary dark:text-white" />
    </Button>
  );
};
