import { View } from "@tarojs/components";
import { Popup, DatetimePicker } from "@taroify/core";
import { useEffect, useMemo, useState } from "react";
import "./index.css";
import { DatetimePickerType } from "@taroify/core/datetime-picker/datetime-picker.shared";

interface FormDatePickerProps {
  value: Date;
  onChange: (value: Date) => void;
  picker?: "date" | "month" | "time";
}

const FormDatePicker = (props: FormDatePickerProps) => {
  const { value, onChange, picker = "month" } = props;
  const [show, setShow] = useState(false);
  const [date, setDate] = useState(new Date());

  const info = useMemo(() => {
    if (picker === "time") {
      let dateDesc = "";
      if (value instanceof Date) {
        const hour = value.getHours();
        const min = value.getMinutes();
        const second = value.getSeconds();
        dateDesc = `${hour}:${min}:${second}`;
      }
      return {
        type: "time",
        title: "选择时间",
        value: dateDesc,
      };
    }
    if (picker === "date") {
      let dateDesc = "";
      if (value instanceof Date) {
        const year = value.getFullYear();
        const month = value.getMonth() + 1;
        const day = value.getDate();
        dateDesc = `${year}-${month > 9 ? month : "0" + month}-${day}`;
      }
      return {
        type: "date",
        title: "选择日期",
        value: dateDesc,
      };
    }
    if (picker === "month") {
      let dateDesc = "";
      if (value instanceof Date) {
        const year = value.getFullYear();
        const month = value.getMonth() + 1;
        dateDesc = `${year}-${month > 9 ? month : "0" + month}`;
      }
      return {
        type: "year-month",
        title: "选择月份",
        value: dateDesc,
      };
    }
  }, [picker, value]);

  useEffect(() => {
    if (value instanceof Date) {
      setDate(value);
    }
  }, [value]);

  const openModal = () => {
    setShow(true);
  };
  return (
    <>
      <View className="date_container" onClick={openModal}>
        {info?.value ? (
          info.value
        ) : (
          <View style={{ color: "GrayText" }}>请选择时间</View>
        )}
      </View>
      <Popup open={show} placement="bottom" style={{ height: "40%" }}>
        <DatetimePicker
          type={(info?.type as DatetimePickerType) ?? "date"}
          value={date}
          onChange={(e) => {
            setDate(e);
          }}
          onCancel={() => {
            setShow(false);
          }}
          onConfirm={() => {
            onChange(date);
            setShow(false);
          }}
        >
          <DatetimePicker.Toolbar>
            <DatetimePicker.Button>取消</DatetimePicker.Button>
            <DatetimePicker.Title>{info?.title}</DatetimePicker.Title>
            <DatetimePicker.Button>确认</DatetimePicker.Button>
          </DatetimePicker.Toolbar>
        </DatetimePicker>
      </Popup>
    </>
  );
};

export default FormDatePicker;
