import { LocalizationProvider } from "@mui/x-date-pickers";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import { DatePicker } from "@mui/x-date-pickers/DatePicker";
import dayjs from "dayjs";
import "dayjs/locale/fr";
import { fmtUnixDate } from "../../utils/time_utils";
import { PropEdit } from "./PropEdit";
import { Checkbox, FormControlLabel } from "@mui/material";

export function PropDateInput(p: {
  editable: boolean;
  label: string;
  value: number | undefined;
  onChange: (v: number | undefined) => void;
  lastSecOfDay?: boolean;
  minDate?: number;
  maxDate?: number;
  canSetMiddleDay?: boolean;
}): React.ReactElement {
  // Check for mid-day value
  let isMidDay = false;
  if (p.value) {
    const d = new Date(p.value * 1000);
    isMidDay =
      d.getHours() === 12 && d.getMinutes() === 0 && d.getSeconds() === 0;
  }

  // Shift value
  let shiftV = p.value;
  if (shiftV && p.lastSecOfDay) {
    const d = new Date(shiftV * 1000);
    if (d.getHours() === 0) {
      shiftV -= 1;
    }
  }

  if (!p.editable) {
    if (!shiftV) return <></>;

    return (
      <PropEdit editable={false} label={p.label} value={fmtUnixDate(shiftV)} />
    );
  }

  const value = dayjs(
    shiftV && p.value! > 0 ? new Date(shiftV * 1000) : undefined
  );

  const minDate = p.minDate ? dayjs(new Date(p.minDate * 1000)) : undefined;
  const maxDate = p.maxDate ? dayjs(new Date(p.maxDate * 1000)) : undefined;

  return (
    <>
      <div style={{ height: "10px" }}></div>
      <LocalizationProvider dateAdapter={AdapterDayjs} adapterLocale="fr">
        <DatePicker
          label={p.label}
          value={value}
          onChange={(v) => {
            if (v && p.lastSecOfDay) {
              v = v.set("hours", 23);
              v = v.set("minutes", 59);
              v = v.set("seconds", 59);
            }
            p.onChange?.(v ? v.unix() : undefined);
          }}
          minDate={minDate}
          maxDate={maxDate}
        />
      </LocalizationProvider>
      {p.canSetMiddleDay && (
        <FormControlLabel
          disabled={!p.value}
          control={
            <Checkbox
              checked={isMidDay}
              onChange={(_ev, midDay) => {
                let v = value;
                if (midDay) {
                  v = v.set("hours", 12);
                  v = v.set("minutes", 0);
                  v = v.set("seconds", 0);
                } else if (p.lastSecOfDay) {
                  v = v.set("hours", 23);
                  v = v.set("minutes", 59);
                  v = v.set("seconds", 59);
                } else {
                  v = v.set("hours", 0);
                  v = v.set("minutes", 0);
                  v = v.set("seconds", 0);
                }

                p.onChange(v.unix());
              }}
            />
          }
          label="Mi-journée"
        />
      )}
      <div style={{ height: "30px" }}></div>
    </>
  );
}
