import React, { useEffect, useState } from "react";
import _service from "@netuno/service-client";
import { Card, Row, Col, notification, Button } from "antd";
import { Link } from "react-router-dom";

import "./index.less";

const { Meta } = Card;

function Result({astroType}) {
  const servicePrefix = _service.config().prefix;
  const [list, setList] = useState([]);
  const [page, setPage] = useState(1);
  const [showMore, setShowMore] = useState(true);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (page > 1) {
      onLoadData({astroType, page, list});
    }
  }, [page]);

  useEffect( () => {
    onLoadData({astroType, page:1, list:[]});
    return () => {
      // cleanup...
      setPage(1);
      setShowMore(true);
      setList([]);
    }
  }, [astroType]);

  const onLoadData = ({astroType, page, list}) => {
    setLoading(true);
    _service({
      url: "/astro/list",
      data: {astroType, page},
      success: (response) => {
        if (response.json.length < 6) {
          setShowMore(false);
        }
        setList([...list, ...response.json]);
        setLoading(false);
      },
      fail: (e) => {
        console.error("Service Error", e);
        notification.error({
          message:"Erro",
          description:"Não foi possível encontrar o astro."
        });
        setLoading(false);
      },
    });
  };
  return (
    <>
    <Row className="astro-list__result"
      gutter={[20,20]}
    >
      {list.map((item) => {
        return (
          <Col
            xs={24}
            sm={12}
            md={8}
            lg={6}
            xl={6}
          >
            <Link to={`/pt/astro/${item.id}`}>
              <Card 
                hoverable
                style={{}}
                cover={
                    <img
                      src={`${servicePrefix}/astro/image?uid=${item.id}`}
                      alt="Imagem do Astro"
                    />
                }
              >
                <div className="shadow"><br/></div>
                <Meta 
                  title={item.name} 
                  description={<p>(Mais Detalhes)</p>}
                />
              </Card>
            </Link>
          </Col>
        );
      })}
    </Row>
    { showMore && <Button loading={loading} onClick={()=> setPage(page + 1) }>Mostrar mais</Button> }
    </> 
  );
}
export default Result;