import {
  Button,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
} from "@mui/material";
import React from "react";
import { ServerApi } from "../../api/ServerApi";
import { NewCalendarURL } from "../../api/accommodations/AccommodationsCalendarURLApi";
import { checkConstraint } from "../../utils/form_utils";
import { useAccommodations } from "../../widgets/accommodations/BaseAccommodationsRoute";
import { PropEdit } from "../../widgets/forms/PropEdit";
import { PropSelect } from "../../widgets/forms/PropSelect";

export function CreateAccommodationCalendarURLDialog(p: {
  open: boolean;
  onClose: () => void;
  onSubmitted: (c: NewCalendarURL) => void;
}): React.ReactElement {
  const [calendar, setCalendar] = React.useState<NewCalendarURL>({ name: "" });

  const accommodations = useAccommodations();

  const nameErr = checkConstraint(
    ServerApi.Config.constraints.accommodation_calendar_name_len,
    calendar?.name
  );

  const clearForm = () => {
    setCalendar({ name: "" });
  };

  const cancel = () => {
    clearForm();
    p.onClose();
  };

  const submit = async () => {
    clearForm();
    p.onSubmitted(calendar!);
  };

  return (
    <Dialog open={p.open} onClose={cancel}>
      <DialogTitle>Création d'un calendrier</DialogTitle>
      <DialogContent style={{ display: "flex", flexDirection: "column" }}>
        <PropEdit
          editable
          label="Nom"
          value={calendar?.name}
          onValueChange={(s) =>
            setCalendar((a) => {
              return {
                ...a!,
                name: s!,
              };
            })
          }
          size={ServerApi.Config.constraints.accommodation_calendar_name_len}
          helperText={nameErr}
        />

        <PropSelect
          editing
          label="Logement ciblé"
          onValueChange={(v) => {
            setCalendar((a) => {
              return {
                ...a!,
                accommodation_id: v !== "A" && v ? Number(v) : undefined,
              };
            });
          }}
          options={[
            { label: "Tous les logements", value: "A" },
            ...accommodations.accommodations.fullList.map((a) => {
              return { label: a.name, value: a.id.toString() };
            }),
          ]}
          value={calendar.accommodation_id?.toString() ?? "A"}
        />
      </DialogContent>
      <DialogActions>
        <Button onClick={cancel}>Annuler</Button>
        <Button onClick={submit} disabled={!!nameErr}>
          Créer
        </Button>
      </DialogActions>
    </Dialog>
  );
}
