import React, { useMemo, useState } from "react";
import { RulePill } from "../../../Segment/RulePill";
import {
  Calendar,
  Icon,
  KomiPopover,
} from "@komi-app/components";

import classnames from "classnames";
import "../RuleBlock.scss";
import "./DateRuleBlock.scss";
import { noop } from "../../../utils/fns";
import { format } from "date-fns";
import { dateStringToUtcTimeStamp, utcTimeStampToDateString } from "./utils";

export interface DateSelectRuleBlockProps
  extends React.HTMLProps<HTMLDivElement> {
  date?: string;
  minValue?: string;
  maxValue?: string;
  onValueChange?: (range: string) => void;
}
export const DateSelectRuleBlock: React.FC<DateSelectRuleBlockProps> = ({
  date: injectedDateRange,
  onValueChange: onValueChange = noop,
  minValue,
  maxValue,
  ...props
}) => {
  
  //Convert Date string ('YYYY-MM-DD') to timestamp in UTC.
  const [selectedDate, setSelectedDate] = useState<number>(
    dateStringToUtcTimeStamp(injectedDateRange)
  );

  //Covert selected date to display format
  const label = useMemo(
    () => format(selectedDate, "MMM d, yyyy"),
    [selectedDate]
  );

  const onDateRangeChange = (updatedDate: number | null) => {
    const selectedValue = utcTimeStampToDateString(updatedDate);

    
    setSelectedDate(updatedDate || Date.now());
    onValueChange(selectedValue);
  };

  const classNames = classnames("rule-block-datepicker", props.className);
  const minDate = minValue ? dateStringToUtcTimeStamp(minValue) : undefined;
  const maxDate = maxValue ? dateStringToUtcTimeStamp(maxValue) : undefined;
  return (
    <div className={classNames}>
      <KomiPopover
        panel={({ close }) => (
          <Calendar
            value={selectedDate}
            minDate={minDate}
            maxDate={maxDate}
            onChange={(v) => {
              onDateRangeChange(v);
              close();
            }}
          />
        )}
      >
        <RulePill className="rule-block__pill rule-block-datepicker__pill">
          <Icon className="rule-block__pill-icon" name="calendar" />
          {label}
        </RulePill>
      </KomiPopover>
    </div>
  );
};
