import AccessTimeOutlined from "@mui/icons-material/AccessTimeOutlined";
import ChevronLeftOutlined from "@mui/icons-material/ChevronLeftOutlined";
import ChevronRightOutlined from "@mui/icons-material/ChevronRightOutlined";
import KeyboardArrowDownOutlined from "@mui/icons-material/KeyboardArrowDownOutlined";
import IconButton from "@mui/material/IconButton";
import MenuItem from "@mui/material/MenuItem";
import Popover from "@mui/material/Popover";
import TextField from "@mui/material/TextField";
import { useMemo, useState } from "react";
import { Button } from "@/shared/ui/Button.jsx";
import {
    calendarDays,
    formatRangePart,
    monthTitle,
    normalizeMs,
    pad2,
    sameDay,
} from "@/shared/ui/TimeRangeFilter.jsx";
import styles from "@/shared/ui/TimeRangeFilter.module.css";

const weekLabels = ["一", "二", "三", "四", "五", "六", "日"];

// 单点业务时间与区间筛选复用同一套日历、时分下拉和动效，避免财务表单退回浏览器原生 datetime 输入。
export function DateTimePicker({ className = "", disabled = false, label = "时间", onChange, value }) {
    const selectedMs = normalizeMs(value);
    // 空值只用于首次内部 state 占位；真正打开时在点击事件中读取当前时间，保持 render 纯函数。
    const selectedDate = useMemo(() => new Date(selectedMs || 0), [selectedMs]);
    const [anchorEl, setAnchorEl] = useState(null);
    const [draft, setDraft] = useState(selectedDate);
    const [viewDate, setViewDate] = useState(selectedDate);
    const open = Boolean(anchorEl);
    const days = useMemo(() => calendarDays(viewDate), [viewDate]);

    const openPopover = (event) => {
        if (disabled) {
            return;
        }
        const current = new Date(selectedMs || Date.now());
        setDraft(current);
        setViewDate(current);
        setAnchorEl(event.currentTarget);
    };
    const closePopover = () => setAnchorEl(null);
    const changeMonth = (offset) => {
        setViewDate((current) => new Date(current.getFullYear(), current.getMonth() + offset, 1));
    };
    const changeDay = (day) => {
        // 切换日期时保留已选时分，便于补录前天同一时刻的订单，而不是悄悄归零到当天零点。
        setDraft(
            (current) =>
                new Date(
                    day.getFullYear(),
                    day.getMonth(),
                    day.getDate(),
                    current.getHours(),
                    current.getMinutes(),
                    0,
                    0,
                ),
        );
        setViewDate(new Date(day.getFullYear(), day.getMonth(), 1));
    };
    const changeTime = (unit, valueText) => {
        setDraft((current) => {
            const next = new Date(current);
            if (unit === "hour") {
                next.setHours(Number(valueText));
            } else {
                next.setMinutes(Number(valueText));
            }
            next.setSeconds(0, 0);
            return next;
        });
    };
    const selectNow = () => {
        const now = new Date();
        setDraft(now);
        setViewDate(now);
    };
    const submit = (event) => {
        event.preventDefault();
        // Popover 通过 portal 渲染，必须截断 submit 冒泡，否则确认时间会误提交外层“创建币商充值”表单。
        event.stopPropagation();
        onChange(draft.getTime());
        closePopover();
    };

    return (
        <>
            <Button
                aria-expanded={open}
                aria-haspopup="dialog"
                className={[styles.trigger, className].filter(Boolean).join(" ")}
                disabled={disabled}
                onClick={openPopover}
            >
                <span className={styles.triggerMeta}>
                    <AccessTimeOutlined fontSize="inherit" />
                    <span>{label}</span>
                </span>
                <span className={styles.triggerText}>{formatRangePart(selectedMs) || "请选择"}</span>
                <KeyboardArrowDownOutlined className={styles.triggerChevron} fontSize="small" />
            </Button>
            <Popover
                anchorEl={anchorEl}
                open={open}
                anchorOrigin={{ horizontal: "left", vertical: "bottom" }}
                slotProps={{ paper: { className: styles.paper } }}
                transformOrigin={{ horizontal: "left", vertical: "top" }}
                onClose={closePopover}
            >
                <form className={styles.panel} onSubmit={submit}>
                    <div className={styles.quickRanges}>
                        <Button className={styles.quickButton} onClick={selectNow}>
                            现在
                        </Button>
                    </div>
                    <div className={styles.calendarHeader}>
                        <IconButton aria-label="上个月" size="small" onClick={() => changeMonth(-1)}>
                            <ChevronLeftOutlined fontSize="small" />
                        </IconButton>
                        <span className={styles.calendarTitle}>{monthTitle(viewDate)}</span>
                        <IconButton aria-label="下个月" size="small" onClick={() => changeMonth(1)}>
                            <ChevronRightOutlined fontSize="small" />
                        </IconButton>
                    </div>
                    <div className={styles.calendarGrid}>
                        {weekLabels.map((weekday) => (
                            <span className={styles.weekday} key={weekday}>
                                {weekday}
                            </span>
                        ))}
                        {days.map((day) => (
                            <button
                                aria-label={`${day.getFullYear()}-${pad2(day.getMonth() + 1)}-${pad2(day.getDate())}`}
                                className={[
                                    styles.dayButton,
                                    day.getMonth() !== viewDate.getMonth() ? styles.dayOutside : "",
                                    sameDay(day, draft) ? styles.daySelected : "",
                                ]
                                    .filter(Boolean)
                                    .join(" ")}
                                key={`${day.getFullYear()}-${day.getMonth()}-${day.getDate()}`}
                                type="button"
                                onClick={() => changeDay(day)}
                            >
                                {day.getDate()}
                            </button>
                        ))}
                    </div>
                    <div className={styles.timeGrid}>
                        <TextField
                            label="时"
                            select
                            size="small"
                            value={String(draft.getHours())}
                            onChange={(event) => changeTime("hour", event.target.value)}
                        >
                            {Array.from({ length: 24 }, (_, hour) => (
                                <MenuItem key={hour} value={String(hour)}>
                                    {pad2(hour)}
                                </MenuItem>
                            ))}
                        </TextField>
                        <TextField
                            label="分"
                            select
                            size="small"
                            value={String(draft.getMinutes())}
                            onChange={(event) => changeTime("minute", event.target.value)}
                        >
                            {Array.from({ length: 60 }, (_, minute) => (
                                <MenuItem key={minute} value={String(minute)}>
                                    {pad2(minute)}
                                </MenuItem>
                            ))}
                        </TextField>
                    </div>
                    <div className={styles.actions}>
                        <Button onClick={closePopover}>取消</Button>
                        <Button type="submit" variant="primary">
                            确定
                        </Button>
                    </div>
                </form>
            </Popover>
        </>
    );
}
