import ArrowForwardIcon from "@mui/icons-material/ArrowForward";
import {
  Button,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  Divider,
} from "@mui/material";
import React from "react";
import { InboxEntry } from "../api/InboxApi";
import { Movement } from "../api/MovementsApi";
import { MovementSelect } from "../widgets/forms/MovementSelect";
import { InboxEntryWidget } from "../widgets/InboxEntryWidget";

export function AttachMultipleInboxEntriesDialog(p: {
  open: boolean;
  entries: InboxEntry[];
  movements: Movement[][];
  onClose: () => void;
  onSelected: (mapping: (Movement | undefined)[]) => void;
}): React.ReactElement {
  const [mapping, setMapping] = React.useState<(Movement | undefined)[]>(
    p.movements.map(() => undefined)
  );

  const handleSubmit = () => {
    p.onSelected(mapping);
  };

  return (
    <Dialog open={p.open} onClose={p.onClose} fullScreen>
      <DialogTitle>Attach multiple entries to movements</DialogTitle>
      <DialogContent>
        {p.entries.map((entry, num) => {
          return (
            <div key={entry.id}>
              <div
                style={{
                  padding: "5px",
                  display: "flex",
                  alignItems: "center",
                }}
              >
                <span style={{ flex: 1 }}>
                  <InboxEntryWidget entry={entry} />
                </span>
                <ArrowForwardIcon />
                <span
                  style={{ flex: 1, display: "flex", justifyContent: "end" }}
                >
                  {p.movements[num].length > 0 ? (
                    <MovementSelect
                      list={p.movements[num]}
                      value={mapping[num]}
                      onChange={(v) => {
                        setMapping((m) => {
                          const n = [...m];
                          n[num] = v;
                          return n;
                        });
                      }}
                    />
                  ) : (
                    <>No movement found</>
                  )}
                </span>
              </div>
              <Divider />
            </div>
          );
        })}
      </DialogContent>
      <DialogActions>
        <Button onClick={p.onClose}>Cancel</Button>
        <Button onClick={handleSubmit} autoFocus>
          Perform mapping
        </Button>
      </DialogActions>
    </Dialog>
  );
}
