import { View } from "@tarojs/components";
import {
  Picker,
  PickerOption,
  PickerValue,
  PickerOptions,
} from "@nutui/nutui-react-taro";
import React, { useState, useEffect } from "react";
import dayjs from "dayjs";

interface IDateTimeRangePicker {
  trigger: React.ReactNode;
  onFinish: (dateRange: dayjs.Dayjs[]) => void;
}

export default function DateTimeRangePicker(props: IDateTimeRangePicker) {
  const { trigger, onFinish } = props;
  const [visible, setVisible] = useState(false);
  const [columns, setColumns] = useState<PickerOptions>([]);
  const [selectedValue, setSelectedValue] = useState<PickerValue[]>([]);

  // 生成月份选项 (格式: MM/DD)
  const generateMonthOptions = (startFromToday = true) => {
    const months: PickerOptions = [];
    const currentDate = dayjs();
    const startMonth = startFromToday ? currentDate : currentDate.add(1, "day");

    for (let i = 0; i < 7; i++) {
      const date = startMonth.add(i, "day");
      months.push({
        value: date.format("YYYY/MM/DD"),
        label: date.format("YYYY/MM/DD").substring(5),
      });
    }
    return months;
  };

  // 生成小时选项 (整点)
  const generateHourOptions = (startFromNow = true, isStart = true) => {
    const hours: PickerOptions = [];
    const currentHour = dayjs().hour();
    const startHour = startFromNow
      ? isStart
        ? Math.ceil(currentHour)
        : currentHour
      : 0;

    for (let i = startHour; i < 24; i++) {
      const hour = `${i.toString().padStart(2, "0")}:00`;
      hours.push({
        value: hour,
        label: hour,
      });
    }
    return hours;
  };

  // 构建嵌套的级联数据结构
  const buildCascadeData = (): PickerOptions => {
    const startMonths = generateMonthOptions(true);

    return startMonths.map((startMonth) => {
      // 判断是否当天
      const startFromNow = startMonth.value === dayjs().format("YYYY/MM/DD");
      const startHours = generateHourOptions(startFromNow, true);

      return {
        ...startMonth,
        children: startHours.map((startHour) => {
          return {
            value: startHour.value,
            label: startHour.label,
            children: [
              {
                value: "-",
                label: "-",
                children: buildEndOptions(startMonth.value, startHour.value),
              },
            ],
          };
        }),
      };
    });
  };

  // 构建结束时间选项
  const buildEndOptions = (
    startMonth: PickerOption["value"],
    startHour: PickerOption["value"],
  ) => {
    const startDate = dayjs(
      `${startMonth} ${startHour.toString().split(":")[0]}`,
      "YYYY/MM/DD/HH",
    );
    const maxEndDate = startDate.add(24, "hour");

    // 生成可选的结束日期
    const endMonths: PickerOptions = [];
    let currentDate = dayjs(startMonth, "YYYY/MM/DD");
    const endDate = dayjs(maxEndDate.format("YYYY/MM/DD"), "YYYY/MM/DD");

    while (currentDate.isBefore(endDate) || currentDate.isSame(endDate)) {
      endMonths.push({
        value: currentDate.format("YYYY/MM/DD"),
        label: currentDate.format("YYYY/MM/DD").substring(5),
      });
      currentDate = currentDate.add(1, "day");
    }

    return endMonths.map((endMonth) => {
      // 计算该日期下可选的小时
      const endHours: PickerOptions = [];
      const endMonthDate = dayjs(endMonth.value, "YYYY/MM/DD");

      if (endMonthDate.isSame(startDate, "day")) {
        // 同一天
        const startHourValue = parseInt(startHour.toString().split(":")[0]);
        const maxHour = Math.min(23, startHourValue + 12);

        for (let i = startHourValue + 1; i <= maxHour; i++) {
          endHours.push({
            value: `${i.toString().padStart(2, "0")}:00`,
            label: `${i.toString().padStart(2, "0")}:00`,
          });
        }
      } else if (endMonthDate.isSame(maxEndDate, "day")) {
        // 结束日期
        const maxHour = maxEndDate.hour();
        for (let i = 0; i <= maxHour; i++) {
          endHours.push({
            value: `${i.toString().padStart(2, "0")}:00`,
            label: `${i.toString().padStart(2, "0")}:00`,
          });
        }
      } else {
        // 中间日期，全天可选
        for (let i = 0; i < 24; i++) {
          endHours.push({
            value: `${i.toString().padStart(2, "0")}:00`,
            label: `${i.toString().padStart(2, "0")}:00`,
          });
        }
      }

      return {
        ...endMonth,
        children: endHours,
      };
    });
  };

  // 初始化选择值
  const initSelectedValue = (data: any[]): PickerValue[] => {
    const values: PickerValue[] = [];
    let currentLevel = data;

    // 遍历每一级获取默认值
    for (let i = 0; i < 5; i++) {
      if (currentLevel && currentLevel.length > 0) {
        values.push(currentLevel[0].value);
        currentLevel = currentLevel[0].children;
      }
    }

    return values;
  };

  useEffect(() => {
    const cascadeData = buildCascadeData();
    setColumns(cascadeData);
    const date = initSelectedValue(cascadeData);
    setSelectedValue(date);
    onFinish([dayjs(date[0] + " " + date[1]), dayjs(date[3] + " " + date[4])]);
  }, []);

  return (
    <View>
      <Picker
        visible={visible}
        onClose={() => setVisible(false)}
        onConfirm={(_options, values) => {
          setSelectedValue(values);
          setVisible(false);
        }}
        value={selectedValue}
        onChange={(params) => {
          console.log("params", params, typeof params.value);
          setSelectedValue(params.value);
          const date = params.value;
          onFinish([
            dayjs(date[0] + " " + date[1]),
            dayjs(date[3] + " " + date[4]),
          ]);
        }}
        options={[columns]}
        title="选择时间范围"
      />

      <View onClick={() => setVisible(true)}>{trigger}</View>
    </View>
  );
}
