import React, { useEffect, useState} from 'react';

import _service from '@netuno/service-client';

import { useParams } from "react-router-dom";

import { Button, Spin, Row, Col, notification } from 'antd';

import { CheckCircleOutlined } from '@ant-design/icons';

import PublicationForm from '../../containers/PublicationForm';
import PublicationsList from '../../containers/PublicationsList';

import "./index.less";

export default ()=> {
    const [data, setData] = useState(null);
    const [following, setFollowing] = useState(false);
    const { uid } = useParams();

    useEffect(()=> {
        _service({
            method: 'GET',
            url: "api/communities/detail",
            data: { uid },
            success: (response) => {
                setData(response.json);
                setFollowing(response.json.following);
            },
            fail: (e) => {
                console.log("Service Error", e);
                notification["error"]({
                    message: 'Informações',
                    description: 'Não foi possível carregar a informação.',
                });
            }
        });
    }, []);

    const onFollow = ()=> {
        _service({
            method: 'PUT',
            url: "api/communities/follow",
            data: {uid: data.uid},
            success: (response) => {
                setFollowing(response.json.result);
            },
            fail: (e) => {
                console.log("Service Error", e);
                notification["error"]({
                    message: 'Informações',
                    description: 'Não foi possível carregar a informação.',
                });
            }
        });
    };
    const servicePrefix = _service.config().prefix;

    if (data == null) {
        return <Spin />;
    }
    return (
        <div className="community">
            <div className="community__banner" style={{ backgroundImage: `url(${ servicePrefix }/api/communities/image?uid=${ data.uid })` }}>
                <h1>{ data.name } { following ? <CheckCircleOutlined /> : <Button type="link" onClick={onFollow}>Seguir</Button> }</h1>
            </div>
            <Row>
                <Col span={8}>Pessoas: {data.people}</Col>
                <Col span={8}>Publicações: {data.publications}</Col>
                <Col span={8}>{ following ? <><CheckCircleOutlined /> Seguindo</> : <Button type="link" onClick={onFollow}>Seguir</Button> }</Col>
            </Row>
            <PublicationForm communityUid={uid} />
            <PublicationsList communityUid={uid} />
        </div>
    );
};
