import React, { useEffect, useState } from 'react'
import { Form, Input, Select, Button, notification } from 'antd';
import _service from "@netuno/service-client";
import "./index.less"

const layout = {
    labelCol: {
      span: 24,
    },
    wrapperCol: {
      span: 24,
    },
  };

function NewPublication(){
  const [communities, setCommunities] = useState([])

  useEffect(() => {
    _service({
      url:"api/communities",
      method: "GET",
      success: (response) => {
          setCommunities(response.json);
        },
      fail: () => {
          notification.error({
              message: "Erro to load communities"
          })
      }
  })
  }, [])

  const onFinish = (values) => {
    _service({
      url: "api/publications",
      method: "PUT",
      data: {community_uid: values.community, message: values.message},
      success: () => {
        notification.success({
          message: "Mensagem publicada com sucesso."
        })
      },
      fail: () => {
        notification.error({
          message: "Ocorreu um erro"
        })
      }
    })
  };

    return(
        <>
        <Form {...layout} name="nest-messages" layout="vertical" onFinish={onFinish}>
      <Form.Item name="message" label="Nova publicação">
        <Input.TextArea />
      </Form.Item>
      <Form.Item name="community">
        <Select placeholder="Selecione uma comunidade">
          {communities.map(community => {
            return(
              <Select.Option value={community.uid}>{community.nome}</Select.Option>

            )
          })}
        </Select>
      </Form.Item>
      <Form.Item wrapperCol={{ ...layout.wrapperCol, offset: 0 }}>
        <Button type="primary" htmlType="submit">
          Publicar
        </Button>
      </Form.Item>
    </Form>
        </>
    )
}

export default NewPublication