"use client"
import React, { useEffect, useState } from 'react'
import UserTab from '../../components/layout/UserTab'
import useProfile from '../../components/UseProfile'
import toast from 'react-hot-toast'
import { LiaEditSolid } from "react-icons/lia";
import { IoTrashOutline } from "react-icons/io5";

const CategoriesPage = () => {
    const {loading:profileLoading, data:profileData} = useProfile();
    const [categoryName, setCategoryName] = useState('');
    const [categories, setCategories] = useState([]);
    const [editCategory, setEditCategory] = useState(null);


    //create new category && toast promis functionlity
    useEffect(() => {
        fetchCategories();
    }, []);

    function fetchCategories(){
        fetch('api/categories').then(res => {
            res.json().then(categories => {
                setCategories(categories)
            })
        })
    }


    async function handleCategorySubmit(ev){
        ev.preventDefault();
        const creatCategoryPromise = new Promise(async (resolve, reject) => {
            const data = {name:categoryName}; //edit category functionality
            if(editCategory){
                data._id = editCategory._id
            }
            const response = await fetch('api/categories', {
                method: editCategory ? 'PUT' : 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify(data),
            });
            setCategoryName('');
            fetchCategories();
            setEditCategory(null)
            if(response.ok)
                resolve();
            else
                reject(); 
        });
        await toast.promise(creatCategoryPromise, {
            loading: editCategory ? 'Updating...' : 'Creating...',
            success: editCategory ? 'A category is updated' : 'A new category is created',
            error: editCategory ? 'Fail to update category' : 'Fail to create a new category',
        });

    }

    async function handleDeleteCategory(_id){
        const promise = new Promise(async (resolve, reject) => {
            const response = await fetch('/api/categories?_id='+_id, {
                method: 'DELETE',
            })
            if(response.ok){
                resolve();
            }
            else{
                reject();
            }    
        })
        await toast.promise(promise, {
            loading: 'Deleting...',
            success: 'A category is deleted',
            error: 'Fail to delete!',
        });
        fetchCategories();
    }

    
    //loading & admin
    if(profileLoading){
        return <p className='flex justify-center items-center'>Loading...</p>
    }
    if(!profileData.admin){
        return <p className='flex justify-center items-center'>Please login as an admin</p>
    }


  return (
    <div className='px-5 mb-10 max-w-md mx-auto'>
        <UserTab isAdmin={true}/>
        <form className='mt-10' onSubmit={handleCategorySubmit}>
            <div className='flex flex-col'>
                <label className='-mb-1 text-gray-700 font-semibold text-sm flex'>
                    {editCategory ? 'Update category' : 'New category name'}
                    {editCategory && (
                        <div className='font-normal'>: {editCategory.name}</div>
                    )}
                </label>
                <div className='flex gap-2 items-center'>
                    <div className='grow'>
                        <input type='text' value={categoryName} onChange={ev => setCategoryName(ev.target.value)} placeholder='Enter category name'/>
                    </div>
                    <div>
                        <button type='submit' className='bg-pink-500 text-white p-2 rounded-md hover:opacity-80 duration-300'>{editCategory ? 'Update' : 'Create'}</button>
                    </div>
                </div>
            </div>
        </form>
        <div className='mt-5'>
            <label className='-mb-1 text-gray-700 font-semibold text-sm'>Categories</label>
            {categories?.length > 0 && categories.map(c => (
                <div key={c._id} className='w-full p-2 flex justify-between my-2 rounded-md outline-none border border-[#DCA0AE] duration-300'>
                    <p>{c.name}</p>
                    <div className='flex gap-2'>
                        <button type='button' onClick={() => {setEditCategory(c); setCategoryName(c.name)}} className='text-green-600 hover:opacity-60'><LiaEditSolid/></button>
                        <button type='button' onClick={() => handleDeleteCategory(c._id)} className='text-red-600 hover:opacity-60'><IoTrashOutline/></button>
                    </div>
                </div>
            ))}
        </div>
    </div>
  )
}

export default CategoriesPage