import React, { useEffect, useState } from 'react';
import ApartamentService from '../../API/ApartamentService';
import {useFetching} from '../../hooks/useFetching';
import {getPageCount} from '../../utils/Pages';

import CardApartament from '../CardApartament/CardApartament';
import Pagination from '../UI/Pagination/Pagination';

const FavoritesApartamentsList = () => {
    const [apartamentsFavorites, setApartamentsFavorites] = useState([])
    const [totalPages, setTotalPages] = useState(0);
    const [page, setPage] = useState(1);
    const [limit, setLimit] = useState(1);

    const [fetchApartaments, isApartamentsLoading, apartamentsError] = useFetching(async (limit) => {
        let offset = (page - 1)  * limit;
        const response = await ApartamentService.getAll(limit, offset);
        setApartamentsFavorites(response.data.results)
        let totalCount = response.data.count;
        setTotalPages(getPageCount(totalCount, limit))
    })
    
    useEffect(() => {
      fetchApartaments(limit)
    }, [page, limit])

    const changePage = (page) => {
        setPage(page)
    }

    const viewAll = () => {
        setLimit(totalPages * limit)
        setPage(1)
    }

    // TODO: Переделать, сейчас сделанно для MVP (то есть заглушки)
    if (!apartamentsFavorites.length && !isApartamentsLoading && !apartamentsError) {
        return (
            <h1 style={{textAlign: 'center'}}>В избранном ничего нет :/</h1>
        )
    }

    if (apartamentsError){
        return(
            <h1 style={{textAlign: 'center'}}>Произошла ошибка ({apartamentsError})</h1>
        )
    }

    return (
        <>
            {isApartamentsLoading &&
                <h1 style={{textAlign: 'center'}}>Идет загрузка...</h1>
            }
            {apartamentsFavorites.map((apartament, index) =>
                <>
                    <CardApartament results={apartament}/>
                    <div className="separationLine"></div>
                </> 
            )}
            <Pagination page={page} changePage={changePage} viewAll={viewAll} totalPages={totalPages}/>
        </>
    );
};

export default FavoritesApartamentsList;