/**
 * @Author: ??
 * @Date: ??
 */
import React, { ForwardedRef, forwardRef, useEffect, useImperativeHandle, useState } from "react";
import { DatePickerProps, DatePickerRefFuncProps } from "./interface";
import { default as RCDatePicker } from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
import "./index.css";
import { CustomDpInput } from "./CustomDpInput";
import { timeValue, YMD, YMDHms } from "@utils/time";
import dayjs from "dayjs";

/**
 * ### 引用方法
 * ```tsx
 * import { DatePicker } from "@atomintl/exchange-ui";
 * ```
 * ##### 更多react-datepicker props详见 https://reactdatepicker.com/#example-custom-header-with-two-months-displayed
 */
export const DatePicker: React.FC<DatePickerProps> = props => {
  const { onDateStrChange, timeQuantum, resetButton, queryButton, className, initSinceWhen, onRef } = props;
  const [[startDate, endDate], setDateRange] = useState<[Date | null, Date | null]>([null, null]);
  const [sinceWhen, setSince] = useState<"d" | "w" | "m" | "3m" | "">(initSinceWhen || "");
  const start_end = startDate && endDate;
  
  const CustomInput = forwardRef(({ value, onClick }: any, ref: ForwardedRef<HTMLDivElement>) => {
    return <CustomDpInput refObj={ref} value={value} onClick={onClick} />;
  });
  
  useEffect(() => {
    onDateStrChange?.([
      {
        startV: startDate ? timeValue(startDate) : "",
        endV: startDate ? timeValue(endDate) : ""
      },
      {
        startDate: startDate ? YMDHms(startDate) : "",
        endDate: endDate ? YMDHms(endDate) : ""
      }
    ]);
  }, [startDate, endDate]);
  
  const renderDayContents = (day: any, date: Date) => {
    const tooltipText = YMD(date);
    return <span title={tooltipText}>{day}</span>;
  };
  
  useEffect(() => {
    if (sinceWhen) {
      let today = dayjs(),
        targetDay = undefined;
      switch (sinceWhen) {
        case "d":
          targetDay = dayjs().add(1, "day");
          break;
        case "w":
          targetDay = dayjs().add(1, "w");
          break;
        case "m":
          targetDay = dayjs().add(1, "M");
          break;
        case "3m":
          targetDay = dayjs().add(3, "M");
          break;
      }
      
      setDateRange([new Date(today.toString()), new Date(targetDay?.toString())]);
    }
  }, [sinceWhen]);
  
  const TimeList = React.memo(() => {
    return timeQuantum ? (
      <>
        <div
          className={`rounded-[2px] px-[13px] py-[4px] cursor-pointer ${
            sinceWhen === "d" ? "text-blue bg-derive-10" : "text-derive-11"
          }`}
          onClick={() => setSince("d")}
        >
          一天
        </div>
        <div
          className={`px-[13px] py-[4px] cursor-pointer ${
            sinceWhen === "w" ? "text-blue bg-derive-10" : "text-derive-11"
          }`}
          onClick={() => setSince("w")}
        >
          一周
        </div>
        <div
          className={`px-[13px] py-[4px] cursor-pointer ${
            sinceWhen === "m" ? "text-blue bg-derive-10" : "text-derive-11"
          }`}
          onClick={() => setSince("m")}
        >
          一个月
        </div>
        <div
          className={`px-[13px] py-[4px] mr-[13px] cursor-pointer ${
            sinceWhen === "3m" ? "text-blue bg-derive-10" : "text-derive-11"
          }`}
          onClick={() => setSince("3m")}
        >
          三个月
        </div>
        <div className="text-derive-11 mr-[16px]">时间</div>
      </>
    ) : null;
  });
  
  const CheckWidget = () => {
    return queryButton ? <div>查询</div> : null;
  };
  
  const ResetWidget = () => {
    return resetButton ? (
      <div
        className={`${
          start_end ? "text-black" : "text-derive-11-200"
        } px-[8px] py-[3px] hover:bg-derive-10 rounded-[4px] ml-[8px] cursor-pointer`}
        onClick={() => setDateRange([null, null])}
      >
        重置
      </div>
    ) : null;
  };
  
  useImperativeHandle(onRef, () => ({ setDateRange, setSince }));
  
  return (
    <div className={`flex items-center z-[999] relative ${className}`}>
      <TimeList />
      <RCDatePicker
        selectsRange={true}
        startDate={startDate}
        endDate={endDate}
        onChange={e => {
          console.log(e);
          setDateRange(e);
        }}
        monthsShown={2}
        showPopperArrow={false}
        dateFormat={"yyyy-MM-dd"}
        customInput={<CustomInput />}
        renderDayContents={renderDayContents}
        // renderCustomHeader={({
        //   date,
        //   changeYear,
        //   changeMonth,
        //   decreaseMonth,
        //   increaseMonth,
        //   prevMonthButtonDisabled,
        //   nextMonthButtonDisabled,
        // }) => (<div></div>)}
        {...props}
      />
      <CheckWidget />
      <ResetWidget />
    </div>
  );
};

DatePicker.defaultProps = {};

export type { DatePickerProps, DatePickerRefFuncProps };
export default DatePicker;
