import React, { useContext } from "react";
import {
  CreateQueueRequest,
  Queue,
  useCreateQueueMutation,
} from "../../slice/QueueApi";
import "../styles.css";
import { Button, Form, Input, Spin } from "antd";
import Title from "antd/es/typography/Title";
import tr from "../../config/translation";
import { MessageContext } from "../../App";
import { useNavigate } from "react-router-dom";
import { PlusCircleOutlined } from "@ant-design/icons";

const CreateQueueCard = (): JSX.Element => {
  const messageApi = useContext(MessageContext);
  const navigate = useNavigate();

  const [form] = Form.useForm();
  const [createQueue, { isLoading }] = useCreateQueueMutation();

  const submit = (formData: CreateQueueRequest) => {
    createQueue(formData)
      .unwrap()
      .then((data: Queue) => navigate(`/dashboard/queue/${data.id}`))
      .then(() => messageApi.success(tr("Queue created")))
      .catch(() => messageApi.error(tr("Failed to create queue")));
  };

  return (
    <div className="card">
      <Spin spinning={isLoading}>
        <Title level={2}>{tr("New queue")}</Title>
        <Form
          form={form}
          layout="vertical"
          requiredMark={false}
          onFinish={(formData: CreateQueueRequest) => submit(formData)}
        >
          <Form.Item
            name={"name"}
            label={tr("Name")}
            rules={[
              {
                required: true,
                message: tr("Please input queue name!"),
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name={"description"}
            label={tr("Description") + " " + tr("(optional)")}
          >
            <Input />
          </Form.Item>
          <Button
            style={{ width: "100%" }}
            icon={<PlusCircleOutlined />}
            type="primary"
            onClick={() => form.submit()}
          >
            {tr("Create")}
          </Button>
        </Form>
      </Spin>
    </div>
  );
};
export default CreateQueueCard;
