import Searchbar from "../../Components/common/Searchbar";
import DetailIcon from "../../assets/images/DetailIcon.svg";
import PaperIcon from "../../assets/images/PaperIcon.svg";
import DescriptionIcon from "../../assets/images/DescriptionIcon.svg";
import ChecklistIcon from "../../assets/images/ChecklistIcon.svg"
import wallet from "../../assets/images/wallet.svg"
import propertiesIcon from "../../assets/images/properties.svg"
import FloatingItems from "../../Components/common/FloatingItems";
import ProductsGrid from "../../Components/products/ProductsGrid";
import products from "../../assets/images/products.svg"
import {useParams} from "react-router-dom";
import React, {useEffect, useState} from "react";
import PublicApi from "../../api/PublicAPi";
import SelectProperty from "../../Components/properties/SelectProperty";
import AdminApi from "../../api/AdminApi";
import {userToken} from "../../api/TokenApi";
import AddProperty from "../../Components/properties/AddProperty";
import deleteIcon from "../../assets/images/DeleteIcon.svg";
import {Modal} from "react-bootstrap";
import LoadingTemplate from "../../Components/common/LoadingTemplate";
import DangerButton from "../../Components/DangerButton";
import SecondaryButton from "../../Components/SecondaryButton";
import PlusIcon from "../../assets/images/PlusGray.svg";

export default function CategoryDetail() {
    const [deleteLoading, setDeleteLoading] = useState(false)
    const [showDeleteModal, setShowDeleteModal] = useState(false)
    const [allProperties, setAllProperties] = useState([])
    const [category, setCategory] = useState({
        title: "",
        description: "",
        products: [],
        properties: []
    })
    const [disableSubmitTitleDescription, setDisableSubmitTitleDescription] = useState(true)

    const {id} = useParams()

    const getCategory = async () => {
        const fetchedCategory = await PublicApi.get(`categories/show/${id}`)
        setCategory(fetchedCategory)
    }

    const getProperties = async () => {
        const fetchedProperties = await PublicApi.get(`properties/index/${await userToken()}`)
        setAllProperties(fetchedProperties)
    }

    useEffect(() => {
        getCategory()
        getProperties()
    }, [])

    const handleSearch = (e) => {
        console.log(e.target.value)
    }

    const attachProperty = async (propertyId, categoryId) => {
        await AdminApi.post(`properties/${propertyId}/attachCategory/${categoryId}`, {})
    }

    const detachProperty = async (propertyId, categoryId) => {
        await AdminApi.post(`properties/${propertyId}/detachCategory/${categoryId}`, {})
    }

    const handleDeleteProperty = (title) => {
        const propertyId = category.properties.filter(prop => prop.title === title)[0].id
        detachProperty(propertyId, id).then(() => getCategory())
    }

    const handleChangePropertyStatus = (property) => {
        if (category.properties.filter((prop) => prop.id === property.id).length === 1) {
            handleDeleteProperty(property.title)
        } else {
            attachProperty(property.id, id).then(() => getCategory())
        }
    }

    const handleDeleteModal = () => {
        setShowDeleteModal(!showDeleteModal)
    }
    
    const handleDelete = async () => {
        setDeleteLoading(true)
        await AdminApi.delete(`categories/delete/${id}`).then(() => {
            window.location = '/panel/categories'
        })
        setDeleteLoading(false)
    }
    
    const handleChangeTitleDescription = (e) => {
        setDisableSubmitTitleDescription(false)
        setCategory({
            ...category,
            [e.target.name]: e.target.value
        })
    }

    const handleSubmitTitleDescription = async () => {
        await AdminApi.post(`categories/update/${id}`, {
            title: category.title,
            description: category.description,
            _method: 'PUT',
        })
        setDisableSubmitTitleDescription(true)
    }

    const handleChangeImage = async (e) => {
        const files = [...e.target.files]
        for (let i = 0; i < files.length; i++) {
            const formData = new FormData();
            formData.append('image', files[i])
            formData.append('title', files[i].name)
            formData.append('alt', files[i].name)
            await AdminApi.imagePost(`images/pim/createOn/Category/${id}`, formData).then(() => getCategory())
        }
    }

    const handleImageDelete = async(id) => {
        await AdminApi.post(`images/delete/${id}`)
        getCategory();
    }
    return (
        <div className={'flex flex-col'}>
            <div className={'flex items-center justify-start'}>
                <Searchbar onChange={handleSearch}/>
            </div>

            <div>
                <div className={'py-4 px-4 my-3 flex flex-col bg-white border-1 border-[#E6E6E6] rounded-lg'}>
                    <div className="flex items-start justify-start overflow-x-scroll">
                        <label
                            htmlFor="image-input"
                            className="flex items-center justify-center rounded-lg ml-3 cursor-pointer bg-[#CDCDCD] hover:bg-[#ABABAB]">
                            <div className="flex items-center justify-center w-[10vw] h-[10vw]">
                                <img alt={'click to upload'} src={PlusIcon}/>
                            </div>
                            <input id="image-input" accept={'image/*'} multiple type="file" className="hidden"
                                   onChange={handleChangeImage}/>
                        </label>
                        {
                            category.images?.map((image, index) => (
                                <div key={index} className="relative flex flex-col items-center justify-center">
                                    <button onClick={() => handleImageDelete(image.id)} className="absolute w-full h-full top-0 right-0 px-3 rounded-lg">
                                        <div className="flex items-center justify-center h-full w-full transition opacity-0 hover:opacity-100 bg-red-500/25 rounded-lg">
                                            <svg className="w-12 h-12 stroke-red-500" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" >
                                            <path stroke-linecap="round" stroke-linejoin="round" d="m14.74 9-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 0 1-2.244 2.077H8.084a2.25 2.25 0 0 1-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 0 0-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 0 1 3.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 0 0-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 0 0-7.5 0" />
                                            </svg>

                                        </div>
                                    </button>
                                    <img className={'preview-image mx-3 rounded-lg shadow-xl'}  src={image.path} alt={image.title}/>
                                </div>
                            ))
                        }
                    </div>
                </div>
                <div className={'flex items-center justify-between mt-8'}>
                    <div className={'flex items-center'}>
                        <img alt={''} src={DetailIcon}/>
                        <span className={'font-[dana] mr-2 text-[#333333]'}>جزئیات دسته بندی</span>
                    </div>
                    <img className={'ml-2 cursor-pointer'} alt={'delete'} src={deleteIcon} onClick={handleDeleteModal}/>
                </div>
                <div className={'py-4 px-4 mt-3 flex flex-col bg-white border-1 border-[#E6E6E6] rounded-lg'}>
                    <div className={'flex flex-row items-center my-2'}>
                        <img alt={''} src={PaperIcon}/>
                        <span className={'font-[Vazirmatn] mr-2 text-[#828282] text-sm'}>نام:</span>
                        <input onChange={handleChangeTitleDescription} className={'font-[Vazirmatn] pr-1 mr-2 my-0 rounded-lg w-full text-[#333333] text-sm border-0'} name={'title'} value={category.title}/>
                    </div>
                    <div className={'flex flex-row items-center my-2'}>
                        <img alt={''} src={DescriptionIcon}/>
                        <span className={'font-[Vazirmatn] mr-2 text-[#828282] text-sm'}>توضیحات:</span>
                        <input onChange={handleChangeTitleDescription} className={'font-[Vazirmatn] pr-1 mr-2 rounded-lg text-[#333333] w-full text-sm border-0'} name={'description'} value={category.description}/>
                    </div>
                    <div className={'flex flex-row items-center my-4'}>
                        <img alt={''} src={ChecklistIcon}/>
                        <span className={'font-[Vazirmatn] mr-2 text-[#828282] text-sm'}>تعداد محصولات:</span>
                        <span
                            className={'font-[Vazirmatn] mr-2 text-[#333333] text-sm'}>{category.products.length} عدد</span>
                    </div>
                    <button
                        className={'font-[Vazirmatn] bg-zinc-900 text-white rounded-lg h-full py-2 px-6 text-center w-full hover:bg-zinc-700 disabled:opacity-50 disabled:hover:bg-zinc-900'}
                        onClick={handleSubmitTitleDescription}
                        disabled={disableSubmitTitleDescription}
                    >
                        ثبت تغییرات
                    </button>
                </div>
            </div>
            <div>
                <div className={'flex items-center mt-8'}>
                    <img alt={''} src={propertiesIcon}/>
                    <span className={'font-[dana] mr-2 text-[#333333]'}>ویژگی ها</span>
                </div>
                <div className={'py-4 px-4 mt-3 flex flex-col bg-white border-1 border-[#E6E6E6] rounded-lg'}>
                    <SelectProperty
                        properties={allProperties}
                        selectedProperties={category.properties}
                        handleChangePropertyStatus={handleChangePropertyStatus}
                    />
                    <FloatingItems
                        containerClassName={'flex flex-wrap items-center justify-start mt-5'}
                        itemClassName={'my-2'}
                        onDelete={handleDeleteProperty}
                        itemsList={category.properties.map(prop => prop.title)}
                    />
                    <AddProperty categoryId={id} callback={() => {
                        getProperties().then()
                    }}/>

                </div>
            </div>
            <div>
                <div className={'flex items-center mt-8 mb-3'}>
                    <img alt={''} src={products}/>
                    <span className={'font-[dana] mr-2 text-[#333333]'}>محصولات</span>
                </div>
                <ProductsGrid category={category.title} products={category.products}/>
                <div className={'flex flex-row py-6 pl-4'} dir={'ltr'}>
                </div>
            </div>
            <Modal size={'sm'} centered show={showDeleteModal} onHide={handleDeleteModal}>
                <Modal.Header closeButton={true} className={'flex flex-row-reverse'}>
                    <Modal.Title className={'font-[Vazirmatn] text-[1rem]'}>حذف دسته بندی</Modal.Title>
                </Modal.Header>
                <Modal.Body>
                    <div className={'w-full flex flex-row items-center justify-between px-5'}>
                        <LoadingTemplate loading={deleteLoading} className={'mx-2'} marginLeft={'-12px'}>
                            <DangerButton className={'font-[Vazirmatn] w-full flex justify-center items-center tracking-tight'} onClick={handleDelete}>حذف</DangerButton>
                        </LoadingTemplate>
                        <SecondaryButton disabled={deleteLoading} className={'font-[Vazirmatn] w-full flex justify-center items-center mx-2 tracking-tight'} onClick={handleDeleteModal}>لغو</SecondaryButton>
                    </div>
                </Modal.Body>
            </Modal>
        </div>
    )
}