import Layout from '@/Layouts/Layout';
import Searchbar from '@/Components/Searchbar';
import CreateButton from '@/Components/CreateButton';


import { useState } from 'react'
import { router } from '@inertiajs/react'

export default function Index({ products, links, categories }){

    let [createOpen, setCreateOpen] = useState(false);

    function handleCancel(){
        setCreateOpen(false);
    }
    function handleCreateClick(){
        setCreateOpen(true);
    }

    function handleCreate(){
        setCreateOpen(false);
        router.refresh();
    }

    const product_list = products.map((product) => (
        <div className="flex flex-col items-center justify-center bg-white rounded-lg w-full h-full">
            {product.images[0] ? <img src={ product.images[0].thumbnail } alt={ product.images[0].alt } className="h-52 w-full object-cover rounded-t-lg shadow-md" /> : null}
            <div className="p-4 py-6 flex flex-col items-center justify-center space-y-4">
                <span className="text-xl">{product.title}</span>
                <span className="text-gray-600 text-center">{product.description}</span>
            </div>
        </div>
    ));

    return (
        <div className="relative flex flex-col h-full w-full space-y-6">
            {createOpen ? <div className="flex items-center justify-center absolute top-0 z-10 backdrop-blur h-full w-full rounded-lg backdrop-brightness-75">
                <ProductForm onCancel = {handleCancel} categories={ categories }/>
            </div> : ''}
            <div className="flex  justify-between h-fit">
                <Searchbar />
                <CreateButton onClick={ handleCreateClick } title="افزودن محصول"/>
            </div>
            <div className="grid grid-cols-4 gap-8">
                {product_list}
            </div>
            <ProductTable items={ products } links={ links } title="محصولات" />
        </div>  
    );
}

Index.layout = page => <Layout children={page} />