import {
  Modal,
  Option,
  Select,
  Sheet,
  ModalClose,
  FormControl,
  FormLabel,
  Input,
  Button,
  Grid,
} from "@mui/joy";
import React, { useState } from "react";
import { api } from "~/utils/api";
import CustomAlert from "~/components/CustomAlert";

export default function OpenRegisterForm({ open, setOpen, registersQuery }) {
  const [customAlert, setAlert] = useState({
    open: false,
    type: "success",
    text: "",
    duration: 6000,
  });

  const createAlert = (settings) => {
    setAlert({ ...settings, open: true });
  };

  const registerMutation = api.register.openRegister.useMutation({
    onSuccess: (data) => {
      setOpen(false);
      registersQuery.refetch();
    },
    onError: (error) => {
      createAlert({
        type: "warning",
        text: error.message,
        duration: 6000,
      });
    },
  });

  const openRegister = (category: any) => {
    registerMutation.mutate(category);
  };

  return (
    <Modal
      open={open}
      onClose={() => setOpen(false)}
      sx={{
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
      }}
    >
      <Sheet
        variant='outlined'
        sx={{
          minWidth: 500,
          borderRadius: "md",
          p: 3,
        }}
      >
        <ModalClose variant='outlined' />
        <form
          onSubmit={(e: React.SyntheticEvent) => {
            e.preventDefault();
            const register = {
              description: e.target[0].value,
            };
            openRegister(register);
          }}
        >
          <Grid
            container
            direction='column'
            justifyContent='center'
            alignItems='stretch'
            spacing={2}
            mt={4}
          >
            <CustomAlert customAlert={customAlert} setAlert={setAlert} />
            <Grid>
              <FormControl>
                <FormLabel>Descrição</FormLabel>
                <Input type='text' name='description' />
              </FormControl>
            </Grid>
            <Grid>
              <Button type='submit' loading={registerMutation.isLoading}>
                Abrir Caixa
              </Button>
            </Grid>
          </Grid>
        </form>
      </Sheet>
    </Modal>
  );
}
