import { useCallback, useEffect, useRef, useState } from "preact/hooks";
import { DateTime } from "luxon";
import { useFlash } from "../App/FlashContext";
import { useTimezone } from "../App/TimezoneProvider";

type TimeUpdate = {
    year?: number | null;
    month?: number;
    day?: number;
    hour?: number;
    minute?: number;
    second?: number;
};

export const TimeInput = ({ defaultValue, onInput }) => {
    const ref = useRef(null);

    const [timezone] = useTimezone();
    const [localTime, setLocalTime] = useState(
        defaultValue ? DateTime.fromISO(defaultValue, { zone: "UTC" }).setZone(timezone) : null,
    );

    const updateTime = useCallback(
        (upd: TimeUpdate) => {
            if (upd === null) {
                setLocalTime(null);
            }

            let newTime = localTime;
            if (newTime === null) {
                newTime = DateTime.now().setZone(timezone);
            }
            setLocalTime(newTime.set(upd));
        },
        [localTime, timezone],
    );

    useEffect(() => {
        onInput(localTime?.setZone("UTC").toFormat("yyyy-LL-dd'T'HH:mm:ss"));
    }, [localTime]);

    const flash = useFlash();

    return (
        <>
            <div
                class={"input"}
                onPaste={(ev) => {
                    ev.preventDefault();
                    const pasteValue = ev.clipboardData.getData("text/plain");
                    let dt = DateTime.fromISO(pasteValue, { zone: timezone });

                    if (dt.isValid) {
                        setLocalTime(dt);
                        return;
                    }

                    dt = DateTime.fromSQL(pasteValue);

                    if (dt.isValid) {
                        setLocalTime(dt);
                        return;
                    }

                    flash({
                        message: "Couldn't parse your clipboard data as a valid date-time",
                        type: "error",
                    });
                }}
            >
                <div style={{ flexGrow: "1" }}>
                    <label>
                        <span class="is-sr-only">Years input</span>
                        <input
                            style={{
                                borderStyle: "none",
                                fontFamily: "monospace",
                                width: "calc(4ch + 4px)",
                                fontSize: "1rem",
                            }}
                            type="text"
                            pattern="\d*"
                            maxlength={4}
                            placeholder="YYYY"
                            value={
                                localTime
                                    ? localTime.year.toLocaleString("en-US", {
                                          minimumIntegerDigits: 4,
                                          useGrouping: false,
                                      })
                                    : ""
                            }
                            onBlur={(ev) => {
                                ev.currentTarget.value
                                    ? updateTime({
                                          year: parseInt(ev.currentTarget.value),
                                      })
                                    : updateTime(null);
                            }}
                        ></input>{" "}
                    </label>
                    -
                    <label>
                        <span class="is-sr-only">Months input</span>
                        <input
                            style={{
                                borderStyle: "none",
                                fontFamily: "monospace",
                                width: "calc(2ch + 4px)",
                                fontSize: "1rem",
                            }}
                            type="text"
                            pattern="\d*"
                            maxlength={2}
                            placeholder="MM"
                            value={
                                localTime
                                    ? localTime.month.toLocaleString("en-US", {
                                          minimumIntegerDigits: 2,
                                      })
                                    : ""
                            }
                            onBlur={(ev) => {
                                ev.currentTarget.value
                                    ? updateTime({
                                          month: parseInt(ev.currentTarget.value),
                                      })
                                    : updateTime(null);
                            }}
                        ></input>{" "}
                    </label>
                    -
                    <label>
                        <span class="is-sr-only">Days input</span>
                        <input
                            style={{
                                borderStyle: "none",
                                fontFamily: "monospace",
                                width: "calc(2ch + 4px)",
                                fontSize: "1rem",
                            }}
                            type="text"
                            pattern="\d*"
                            maxlength={2}
                            placeholder="DD"
                            value={
                                localTime
                                    ? localTime.day.toLocaleString("en-US", {
                                          minimumIntegerDigits: 2,
                                      })
                                    : ""
                            }
                            onBlur={(ev) => {
                                ev.currentTarget.value
                                    ? updateTime({
                                          day: parseInt(ev.currentTarget.value),
                                      })
                                    : updateTime(null);
                            }}
                        ></input>{" "}
                    </label>
                    <label style={{ marginLeft: "8px" }}>
                        <span class="is-sr-only">Hours input</span>
                        <input
                            style={{
                                borderStyle: "none",
                                fontFamily: "monospace",
                                width: "calc(2ch + 4px)",
                                fontSize: "1rem",
                            }}
                            type="text"
                            pattern="\d*"
                            maxlength={2}
                            placeholder="hh"
                            value={
                                localTime
                                    ? localTime.hour.toLocaleString("en-US", {
                                          minimumIntegerDigits: 2,
                                      })
                                    : ""
                            }
                            onBlur={(ev) => {
                                ev.currentTarget.value
                                    ? updateTime({
                                          hour: parseInt(ev.currentTarget.value),
                                      })
                                    : updateTime(null);
                            }}
                        ></input>{" "}
                    </label>
                    :
                    <label>
                        <span class="is-sr-only">Minutes input</span>
                        <input
                            style={{
                                borderStyle: "none",
                                fontFamily: "monospace",
                                width: "calc(2ch + 4px)",
                                fontSize: "1rem",
                            }}
                            type="text"
                            pattern="\d*"
                            maxlength={2}
                            placeholder="mm"
                            value={
                                localTime
                                    ? localTime.minute.toLocaleString("en-US", {
                                          minimumIntegerDigits: 2,
                                      })
                                    : ""
                            }
                            onBlur={(ev) => {
                                ev.currentTarget.value
                                    ? updateTime({
                                          minute: parseInt(ev.currentTarget.value),
                                      })
                                    : updateTime(null);
                            }}
                        ></input>{" "}
                    </label>
                    :
                    <label>
                        <span class="is-sr-only">Seconds input</span>
                        <input
                            style={{
                                borderStyle: "none",
                                fontFamily: "monospace",
                                width: "calc(2ch + 4px)",
                                fontSize: "1rem",
                            }}
                            type="text"
                            pattern="\d*"
                            maxlength={2}
                            placeholder="ss"
                            value={
                                localTime
                                    ? localTime.second.toLocaleString("en-US", {
                                          minimumIntegerDigits: 2,
                                      })
                                    : ""
                            }
                            onBlur={(ev) => {
                                ev.currentTarget.value
                                    ? updateTime({
                                          second: parseInt(ev.currentTarget.value),
                                      })
                                    : updateTime(null);
                            }}
                        ></input>{" "}
                    </label>
                </div>
                <button
                    style={{
                        background: "none",
                        border: "none",
                        padding: "1px",
                        marginRight: "-3px",
                    }}
                    onClick={() => {
                        ref.current.showPicker();
                    }}
                >
                    <span class="is-sr-only">Show time picker</span>
                    <span class="icon">
                        <i class="fas fa-calendar"></i>
                    </span>
                </button>
            </div>
            <input
                style={{
                    position: "absolute",
                    left: 0,
                    visibility: "hidden",
                }}
                class={"input"}
                type="datetime-local"
                step="1"
                value={
                    localTime
                        ? localTime.toFormat("yyyy-LL-dd'T'HH:mm:ss")
                        : DateTime.now().setZone(timezone).toFormat("yyyy-LL-dd'T'HH:mm:ss")
                }
                ref={ref}
                onInput={(ev) => {
                    ev.currentTarget.value === ""
                        ? updateTime(null)
                        : setLocalTime(
                              DateTime.fromISO(ev.currentTarget.value, { zone: timezone }),
                          );
                }}
            ></input>
        </>
    );
};
