"use client";
import { useEffect, useLayoutEffect, useState } from "react";
import Cards from "./Cards";
import mecredApi from "@/axiosConfig";
import { Button, Divider } from "@mui/material";
import Link from "next/link";

export default function GroupCardsCollections({ id, title, cardsPerRow }) {
    const [expanded, setExpanded] = useState(false);
    const [showButton, setShowButton] = useState(false);
    const [collections, setCollections] = useState([]);



    useEffect(() => {
        fetchcollections(id);
    }, [cardsPerRow]);


    const handleResize = (data) => {
        if (data.length <= cardsPerRow) {
            setShowButton(false);
        }
    };


    const fetchcollections = async (id) => {
        mecredApi
            .get(`/users/${id}/collections?offset=0&limit=${cardsPerRow}`)
            .then(({ data }) => {
                setCollections(data);
                handleResize(data);
                console.log(data);
            });
    };


    const toggleContent = () => {
        setExpanded(!expanded);
    };


    return (
        <div className="flex flex-col">
            <div className="mx-1 flex flex-col">
                <div className="ml-6 inline-block">
                    <h1 className="text-xl font-bold mb-4 text-gray-600">
                        <Link href="/perfil" className="pl-1">
                            {title}
                        </Link>
                    </h1>
                </div>
                <div className={`flex content flex-wrap justify-center ${expanded ? "" : "overflow-y-hidden h-[300px]"}`}>
                    {collections.map((item, index) => {
                        
                        return (
                            <Cards
                                key={index}
                                title={item["name"]}
                                author={item["owner"]["name"]}
                                avatar={item["owner"]["avatar"]}
                                image={item["items_thumbnails"]}
                            />
                        );
                    })}
                </div>
            </div>
            <Divider className="mr-8 max-md:mr-0 mb-8">
                {showButton ?
                    (
                        <Button
                            fullWidth
                            disableElevation
                            variant="outlined"
                            className="mt-2 border-secondary rounded-xl hover:border-secondary-hover text-gray-700 normal-case flex gap-2"
                            onClick={toggleContent}
                        >
                            {expanded ? "Fechar" : "Carregar mais"}
                        </Button>
                    ) : null}
            </Divider>
        </div>
    );
}