import * as React from 'react';
import Tabs from '@mui/material/Tabs';
import Tab from '@mui/material/Tab';
import Box from '@mui/material/Box';
import {useEffect, useState} from "react";
import TextArea from "../../Components/common/TextArea";
import image1 from './../../assets/Card4_399895799.jpg'
import image2 from './../../assets/0jF1GcYgKK4FQ8CkIjW4jXx20m2pC3Q2_cover_580.jpg'
import CmsAPi from "../../api/CmsAPi";
import AdminApi from "../../api/AdminApi";
import {userToken} from "../../api/TokenApi";
export default function Contents() {
    const [data, setData] = useState([]);
    const getProducts = async () => {
        const fetchedContents = await CmsAPi.get(`pages/index/${await userToken()}`)
        setData(() => fetchedContents)
    }
    useEffect(() => {
        getProducts()
    }, [])

    const [tabNumber, setTabNumber] = React.useState(0)

    const handleChange = (event) => {

        const newData = [...data]
        const changedTab = newData.find(tab => tab.url === event.target.name)
        const indexOfChangedTab = newData.indexOf(changedTab)
        const changedContent = changedTab.contents.find(content => content.id === Number(event.target.id))
        const indexOfChangedContent = changedTab.contents.indexOf(changedContent)
        if (changedContent.type === 'text') {
            changedContent.body = event.target.value
        } else if (changedContent.type === 'image') {
            changedContent.body = URL.createObjectURL(event.target.files[0])
        }
        changedTab.contents[indexOfChangedContent] = changedContent
        newData[indexOfChangedTab] = changedTab
        setData(newData);
    }
    const handleChangeTab = (event, newTabNumber) => {
        setTabNumber(newTabNumber);
    }

    async function handlePostContents (id, body, type){
        let postArticleRes = undefined
    
        const formData = new FormData();
        if(type === 'image'){
            let img = document.getElementById(id).files[0];
            formData.append('image', img);
        }
        formData.append('body', body);
        postArticleRes = await AdminApi.imagePost(`content/update/${id}`, formData);

        if (postArticleRes) {
            alert("ثبت شد");
        } else {
            alert('خطا! لطفا از پرکردن فیلد ها مطمئن شوید و دوباره تلاش کنید. در غیر این صورت با پشتیبانی تماس بفرمایید')
        }
    }

    return (
        <Box sx={{width: '100%', borderRadius: '10px'}}>
            <Tabs
                sx={{width: '100%', display: 'flex', flexDirection: 'row-reverse', margin: 0}}
                textColor="inherit"
                TabIndicatorProps={{
                    style: {
                        backgroundColor: "#371067"
                    }
                }}
                value={tabNumber}
                dir={'rtl'}
                onChange={handleChangeTab}
                variant="scrollable"
                scrollButtons
                allowScrollButtonsMobile
                aria-label="scrollable force tabs example"
            >
                {
                    data.map((tab, index) => (
                        <Tab key={index}
                             className={'font-[Vazirmatn] rounded-t-md ml-5 bg-[#D1D5DB] text-dark'}
                             label={tab.url}/>
                    ))
                }
            </Tabs>
            {
                data.map((tab, i) => (
                    <TabPanel value={tabNumber} index={i}>
                        {
                            tab.contents.map((content, j) => (
                                content.type === 'text' ?
                                    <div key={j} className={`flex flex-col items-center justify-end mb-10 mt-5`}>
                                        <label>{content.title}</label>
                                        <TextArea
                                            index={j}
                                            className="py-3 my-3 font-[Vazirmatn] flex text-right w-full placeholder:text-sm placeholder-[#828282] border-[#B3B3B3] bg-gray-100"
                                            onChange={handleChange}
                                            value={content.body}
                                            name={tab.url}
                                            id={content.id}
                                        />
                                        <button
                                            className={'font-[Vazirmatn] bg-zinc-900 text-white rounded-lg h-full mx-10 py-2 px-6 text-center w-full hover:bg-zinc-700 disabled:opacity-50 disabled:hover:bg-zinc-900'}
                                            onClick={() => handlePostContents(content.id, content.body)}
                                        >
                                            ثبت تغییرات
                                        </button>
                                    </div>
                                    : content.type === 'image' ?
                                        <div key={j} className={`flex flex-col items-center justify-end mb-10 mt-5`}>
                                            <label>{content.title}</label>
                                            <div className={'w-full flex items-center justify-start rounded-lg mb-3'}>
                                                <label
                                                    htmlFor={content.id}
                                                    className="cursor-pointer hover:opacity-70">
                                                    <img className={'content-images rounded-lg'}
                                                         src={content.body} alt={''}
                                                         loading={'lazy'}
                                                    />
                                                    <input id={content.id} accept={'image/*'} type="file"
                                                           className="hidden"
                                                           name={tab.url}
                                                           onChange={handleChange}
                                                    />
                                                </label>
                                            </div>
                                            <button
                                                className={'font-[Vazirmatn] bg-zinc-900 text-white rounded-lg h-full mx-10 py-2 px-6 text-center w-full hover:bg-zinc-700 disabled:opacity-50 disabled:hover:bg-zinc-900'}
                                                onClick={() => handlePostContents(content.id, content.body, 'image')}
                                            >
                                                ثبت تغییرات
                                            </button>
                                        </div>
                                         : null
                            ))
                        }
                    </TabPanel>
                ))
            }
        </Box>
    )
}

function TabPanel({children, value, index, ...other}) {
    return (
        <div
            className={' font-[Vazirmatn] text-sm text-dark mx-10 rounded-lg pt-3 mt-3'}
            hidden={value !== index}
            {...other}
        >
            {value === index && (
                <div>{children}</div>
            )}
        </div>
    );
}