import React, { useState, useEffect, useRef } from "react";
import CommonPopup from "@/components/CommonPopup";
import Taro from "@tarojs/taro";
import { View } from "@tarojs/components";
import CalendarUI, {
  CalendarUIRef,
} from "@/components/Picker/CalendarUI/CalendarUI";
import dayjs from "dayjs";
import styles from "../CalendarDialog/index.module.scss";
export interface DayDialogProps {
  value?: Date | Date[];
  searchType?: "single" | "range" | "multiple";
  onChange?: (date: string | string[]) => void;
  visible: boolean;
  onClose: () => void;
  title?: React.ReactNode;
}

const DayDialog: React.FC<DayDialogProps> = ({
  visible,
  searchType,
  onClose,
  title,
  value,
  onChange,
}) => {
  const [selected, setSelected] = useState<Date | Date[]>(value || new Date());
  const calendarRef = useRef<CalendarUIRef>(null);
  const [type, setType] = useState<"year" | "month" | "time">("year");
  const [pendingJump, setPendingJump] = useState<{
    year: number;
    month: number;
  } | null>(null);
  const handleConfirm = () => {
    console.log(selected, 'selectedselected');
    if (!selected) {
      Taro.showToast({
        title: '请选择日期',
        icon: "none",
      });
      return;
    }
    const finalDate = dayjs(selected as Date).format("YYYY-MM-DD");
      if (onChange){
        onChange(finalDate)
      }
      onClose();
  };
  const dialogClose = () => {
    setType("year");
    onClose();
  }

  const handleChange = (d: Date | Date[]) => {
    if (Array.isArray(d)) {
      setSelected(d[0]);
    } else {
      setSelected(d);
    }
  };
  const onHeaderClick = (date: Date) => {
    console.log("onHeaderClick", date);
    setSelected(date);
    setType("month");
  };
  const getConfirmText = () => {
    return "完成"
  };
  const onCancel = () => {
    onClose();
  };

  useEffect(() => {
    if (visible && value) {
      setSelected(value || new Date());
    }
  }, [value, visible]);

  useEffect(() => {
    if (type === "year" && pendingJump && calendarRef.current) {
      calendarRef.current.jumpTo(pendingJump.year, pendingJump.month);
      setPendingJump(null);
    }
  }, [type, pendingJump]);


  return (
    <CommonPopup
      visible={visible}
      onClose={dialogClose}
      onCancel={onCancel}
      showHeader={!!title}
      title={title}
      hideFooter={false}
      cancelText="取消"
      confirmText={getConfirmText()}
      onConfirm={handleConfirm}
      className={styles["calendar-popup"]}
      position="bottom"
      round
      zIndex={1000}
    >
      <View className={styles["calendar-container"]}>
        <CalendarUI
            ref={calendarRef}
            type={searchType}
            value={selected}
            onChange={handleChange}
            showQuickActions={false}
            onHeaderClick={onHeaderClick}
            />
        </View>
    </CommonPopup>
  );
};

export default DayDialog;
