import {useParams} from "react-router-dom";
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 ImageIcon from "../../assets/images/ImageIcon.svg";
import React, {useEffect, useState} from "react";
import PlusIcon from "../../assets/images/PlusGray.svg";
import CategoryIcon from "../../assets/images/CategoryIcon.svg";
import Checkbox from "../../Components/common/Checkbox";
import PublicApi from "../../api/PublicAPi";
import AdminApi from "../../api/AdminApi";

export default function ProductDetail() {
    const [product, setProduct] = useState({})
    const [propertiesValues, setPropertiesValues] = useState([])
    const [properties, setProperties] = useState([]);
    const [disableSubmitTitleDescription, setDisableSubmitTitleDescription] = useState(true)
    const [bestSeller, setBestSeller] = useState(false);
    const {id} = useParams()
    const getProduct = async () => {
        const fetchedProduct = await PublicApi.get(`products/show/${id}`)
        setProduct(fetchedProduct.data)
        setProperties(fetchedProduct.data.category_properties)
        setPropertiesValues(fetchedProduct.data.details)
    }
    useEffect(() => {
        getProduct().then()
    }, [])

    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/Product/${id}`, formData).then(() => getProduct())
        }
    }
    const handleChangeProperty = async (slug, value) => {
        setDisableSubmitTitleDescription(false)
        const changedProperty = propertiesValues.find(prop => prop.slug === slug)
        let newProperties = [...propertiesValues]
        if(changedProperty) {
            const indexOfChanged = propertiesValues.indexOf(changedProperty)
            changedProperty.value = value
            newProperties[indexOfChanged] = changedProperty
        } else {
            newProperties = [{slug, value}, ...propertiesValues]
        }
        setPropertiesValues((prevState) => {return newProperties})
    }
    const handleChangeTitleDescription = (e) => {
        setDisableSubmitTitleDescription(false)
        setProduct({
            ...product,
            [e.target.name]: e.target.value
        })
    }

    const handleImageDelete = async(id) => {
        await AdminApi.post(`images/delete/${id}`)
        getProduct()
    }

    const handleSubmitTitleDescription = async () => {
        let newData = {}
        console.log(propertiesValues);
        for (const index in propertiesValues) {
            newData = {
                ...newData,
                [propertiesValues[index].slug]: propertiesValues[index].value
            }
        }
        console.log(newData);
        await AdminApi.post(`products/update/${id}`, {
            title: product.title,
            description: product.description,
            inventory: product.inventory,
            bestSeller: bestSeller,
            ...newData,
            _method: 'PUT',
        })
        setDisableSubmitTitleDescription(true)
    }
    return (
        <div className={'flex flex-col'}>
            <div>
                <div className={'flex items-center mt-8'}>
                    <img alt={''} src={ImageIcon}/>
                    <span className={'font-[dana] mr-2 text-[#333333]'}>تصاویر</span>
                </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>
                        {
                            product.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>
                </div>
                <div className={'p-4 mt-4 grid grid-cols-6 bg-white rounded-lg'}>
                    <div className={'flex flex-col col-span-4 p-4'}>
                        <div className="flex pb-2">
                            <img className="w-5 h-5 ml-2" alt={''} src={PaperIcon}/>
                            <span className={'font-[Vazirmatn] text-gray-600'}>نام</span>
                        </div>
                        <input onChange={handleChangeTitleDescription} className={'font-[Vazirmatn] w-full rounded-lg border-gray-300'} name={'title'} value={product.title}/>
                    </div>
                    <div className={'flex flex-col col-span-2 p-4'}>
                        <div className="flex pb-2">
                            <img className="w-5 h-5 ml-2" alt={''} src={PaperIcon}/>
                            <span className={'font-[Vazirmatn] text-gray-600'}>موجودی</span>
                        </div>
                        <input onChange={handleChangeTitleDescription} className={'font-[Vazirmatn] w-full rounded-lg border-gray-300'} name={'inventory'} value={product.inventory}/>
                    </div>
                    <div className={'flex flex-col col-span-2 p-4'}>
                        <div className="flex">
                            <img className="w-5 h-5 ml-2" alt={''} src={CategoryIcon}/>
                            <span className={'font-[Vazirmatn] text-gray-600'}>دسته بندی</span>
                        </div>
                        <span className={'font-[Vazirmatn] mr-2 text-[#333333] text-sm'}>{product.category?.title}</span>
                    </div>
                    <div className={'flex flex-col col-span-6 p-4'}>
                        <div className="flex">
                            <img className="w-5 h-5 ml-2" alt={''} src={DescriptionIcon}/>
                            <span className={'font-[Vazirmatn] text-gray-600'}>توضیحات</span>
                        </div>
                        <textarea onChange={handleChangeTitleDescription} className={'font-[Vazirmatn] w-full rounded-lg text-[#333333] border'} name={'description'} value={product.description}/>
                    </div>
                    <label className="flex items-center">
                        <span className="mx-2 text-sm font-[Vazirmatn]">پر فروش</span>
                        <Checkbox
                            onChange={(e) => {setDisableSubmitTitleDescription(false); setBestSeller(e.target.checked)}}
                            name="bestSeller"
                        />
                    </label>
                    {
                        properties.map((property, index) => (
                            <div key={index} className={'flex flex-col ms-center my-2 p-4'}>
                                <div className="flex">
                                    <span className={'font-[Vazirmatn] text-gray-600 mr-1'}>{property.title}</span>
                                    {property.isVariable ? <span className="text-sm text-gray-600">(چندگانه، مقادیر با با , جدا کنید)</span> : ""}
                                </div>
                                <input onChange={(e) => handleChangeProperty(property.slug, e.target.value)} className={'font-[Vazirmatn] rounded-lg w-full border-gray-300'} value={propertiesValues.filter(detail=>property.slug === detail.slug)[0]?.value}/>
                            </div>
                        ))
                    }
                    <button
                        className={'font-[Vazirmatn] bg-zinc-900 text-white rounded-lg h-full py-2 text-center w-full hover:bg-zinc-700 disabled:opacity-50 disabled:hover:bg-zinc-900 col-span-6'}
                        onClick={handleSubmitTitleDescription}
                        disabled={disableSubmitTitleDescription}
                    >
                        ثبت تغییرات
                    </button>
                </div>
            </div>
        </div>
    )
}