import { Input, Select, Typography } from "antd";
import { useEffect, useState } from "react";
import styles from "./aboutBusiness.module.scss";
import * as SellerAPI from "../../../../pages/api/seller-api";
import * as CategoryAPI from "../../../../pages/api/category";


const { Option } = Select;
import { PlusCircleOutlined, MinusCircleOutlined, InfoCircleOutlined } from "@ant-design/icons";
import cx from "classnames";
const { Text } = Typography;

const AboutBusiness = (props: any) => {
    const index = 0;
    const [cardValues, setCardValues] = useState([{ sector: null, catogory: null, brands: "" }]);
    const [categoryTree, setCategoryTree] = useState([]);
    const [selectCategoryTree, setSelectCategoryTree] = useState<any[]>([]);
    const [formData, setFormData] = useState<any>({ shop_title: "", productSectors: null, categories_json: [] });
    const handleMore = () => {
        // console.log(formData)  
        setCardValues([...cardValues, { sector: null, catogory: null, brands: "" }]);
        setArrayCatList(categoryTree, 0);
        const formDataCopy: any = { ...formData };
        if (!formDataCopy.productSectors) {
            formDataCopy.productSectors = [];
        }
        formDataCopy.productSectors.push({
            parent: {},
            child: {},
            brands: ""
        });
        setFormData(formDataCopy);

    }
    const handleRemove = (i: any) => {
        const newValue = [...cardValues];
        newValue.splice(i, 1);
        setCardValues(newValue);
        const formDataCopy: any = { ...formData };
        formDataCopy.productSectors.splice(i, 1);
        setFormData(formDataCopy);
    }
    const setArrayCatList = (cats: any, index: number) => {
        const _ar = [...selectCategoryTree];
        const _obj: any = {};
        _obj.parentCat = cats;
        _obj.childCat = null;
        _obj.brands = "";
        _ar.push(_obj);
        setCategoryTree(cats);
        setSelectCategoryTree(_ar);
    }
    const setDefaultCategories = () => {
        const _keydata: any = (sessionStorage.getItem('VendorOnBoarding'));
        // console.log(_keydata,"_keydata")
        if (_keydata != '' && props.current == 1) {
            const data = JSON.parse(_keydata);
            const formDataCopy: any = { ...formData };
            formDataCopy.shop_title = data.shop_title;

            const categories_json = data?.categories_json ? JSON.parse(data?.categories_json) : [];
            if (categories_json && categories_json?.length > 0) {
                for (let i = 0; i < categories_json?.length; i++) {
                    const newValue = [...cardValues];
                    if (!(newValue && newValue.length > 0 && newValue[i])) {
                        newValue[i] = { sector: null, catogory: null, brands: "" };
                    }
                    newValue[i].sector = categories_json[i].sector;
                    newValue[i].catogory = categories_json[i].catogory;
                    newValue[i].brands = categories_json[i].brands;
                    setCardValues(newValue);

                    if (!formDataCopy.productSectors) {
                        formDataCopy.productSectors = [];
                    }
                    if (!formDataCopy.productSectors[i]) {
                        formDataCopy.productSectors[i] = [];
                    }

                    formDataCopy.productSectors[i].parent = getCategoryDetails(categories_json[i].sector);
                    formDataCopy.productSectors[i].child = getSCategoryDetails(formDataCopy.productSectors[i].parent.children, categories_json[i].catogory);
                    formDataCopy.productSectors[i].brands = categories_json[i]?.brands;
                    // formDataCopy.productSectors[i].brands =
                    // console.log(formDataCopy.productSectors[i],"formDataCopy.productSectors[i]")
                    const copy = [...selectCategoryTree];
                    const selectedCat: any[] = categoryTree.filter((c: any) => c.id == categories_json[i].sector);
                    if (selectedCat.length > 0) {

                        if (!copy[i]) {
                            copy[i] = {
                                parentCat: categoryTree,
                                childCat: null,
                                brands: ""
                            }
                        }
                        copy[i].childCat = selectedCat[0].children;
                        copy[i].brands = formDataCopy.productSectors[i].brands;
                    }
                    setSelectCategoryTree(copy);
                }
            }
            setFormData(formDataCopy);
        }

    }
    const getCategories = async () => {
        const cats = await CategoryAPI.fetchCategoryTree();
        setArrayCatList(cats.categories, 0);

    }
    const handleMainCatChangeChange = (itm: any, idx: number) => {
        const copy = [...selectCategoryTree];
        const selectedCat: any[] = categoryTree.filter((c: any) => c.id == itm);
        if (selectedCat.length > 0) {
            copy[idx].childCat = selectedCat[0].children;
            copy[idx].brands = selectedCat[0].brands
        }
        setSelectCategoryTree(copy);
        //Form Data Set on Change
        const formDataCopy: any = { ...formData };
        if (!formDataCopy.productSectors) {
            formDataCopy.productSectors = [];
        }
        if (!formDataCopy.productSectors[idx]) {
            formDataCopy.productSectors[idx] = [];
        }
        formDataCopy.productSectors[idx].parent = getCategoryDetails(itm);
        formDataCopy.productSectors[idx].child = null;
        formDataCopy.productSectors[idx].brands = "";
        const newValue = [...cardValues];
        if ((newValue && newValue.length > 0 && newValue[idx])) {
            newValue[idx].sector = itm;
            newValue[idx].catogory = null;
            setCardValues(newValue);
        }

        setFormData(formDataCopy);
    }
    const handleSubCatChange = (itm: any, idx: number) => {
        //Form Data Set on Change
        //    console.log(itm,"item")
        const formDataCopy: any = { ...formData };
        formDataCopy.productSectors[idx].child = getSCategoryDetails(formDataCopy.productSectors[idx].parent.children, itm);
        setFormData(formDataCopy);
        const newValue = [...cardValues];
        if ((newValue && newValue.length > 0 && newValue[idx])) {
            newValue[idx].catogory = itm;
            setCardValues(newValue);
        }

    }

    const handleBrandChange = (itm: any, idx: number) => {
        //Form Data Set on Change
        // console.log(itm,"item")
        const formDataCopy: any = { ...formData };
        //    console.log(formDataCopy,"formDataCopy")
        formDataCopy.productSectors[idx].brands = itm;
        //    console.log(formDataCopy.productSectors[idx].brands,"formDataCopy fgfg" )
        setFormData(formDataCopy);
        const newValue = [...cardValues];
        if ((newValue && newValue.length > 0 && newValue[idx])) {
            newValue[idx].brands = itm;
            setCardValues(newValue);
        }

    }
    const handleStorenameChange = (e: any) => {
        //Form Data Set on Change
        const formDataCopy: any = { ...formData };
        formDataCopy.shop_title = e.target.value;
        setFormData(formDataCopy);
    }
    const getSCategoryDetails = (_categoryTree: any, categoryId: any) => {

        const _c = _categoryTree.filter((c: any) => c.id == categoryId);
        if (_c.length > 0) {
            return _c[0];
        } else {
            return null;
        }
    }
    const getCategoryDetails = (categoryId: any) => {
        const _c = [...categoryTree].filter((c: any) => c.id == categoryId);
        if (_c.length > 0) {
            return _c[0];
        } else {
            return null;
        }
    }
    useEffect(() => {
        // console.log(sessionStorage.getItem('VendorOnBoarding'),"formData")


        if (props.current == 1)

            props.formData(formData);
    }, [formData]);

    useEffect(() => {

        if (categoryTree.length == 0) {
            getCategories();
        }
    }, [props.current]);


    useEffect(() => {
        if (props.current == 1 && categoryTree.length > 0) {
            //setTimeout(() => {
            setDefaultCategories();
            // })

        }
    }, [categoryTree]);


    const renderCards = () => {
        return (
            <>
                {cardValues.map((val, idx) => {
                    return (<div key={idx} className={cx("ant-row gutterRow mb-4", styles.cardContainer)}>
                        <div className={cx("ant-col ant-col-xs-24 ant-col-sm-24 ant-col-md-12 ant-col-xl-8 gutterCol")}>
                            {selectCategoryTree[idx] && selectCategoryTree[idx].parentCat && (
                                <div className={styles.formLabel}> Product Sector  <span className={styles.starText}>*</span></div>
                            )}
                            {selectCategoryTree[idx] && selectCategoryTree[idx].parentCat && (
                                <Select value={val.sector} className={styles.inputBusiness} allowClear={true} onChange={(e) => { handleMainCatChangeChange(e, idx) }}>
                                    {(selectCategoryTree[idx].parentCat as any).map((cat: any) => (
                                        <Option key={cat.id} value={cat.id}>{cat.name}</Option>
                                    ))}
                                </Select>
                            )}

                        </div>
                        <div className={cx("ant-col ant-col-xs-24 ant-col-sm-24 ant-col-md-12 ant-col-xl-8 gutterCol")}>
                            {selectCategoryTree[idx] && selectCategoryTree[idx].childCat && (
                                <div className={styles.formLabel}> Product Category  <span className={styles.starText}>*</span></div>
                            )}

                            {selectCategoryTree[idx] && selectCategoryTree[idx].childCat && (
                                <Select value={val.catogory} className={styles.inputBusiness} allowClear={true} onChange={(e) => { handleSubCatChange(e, idx) }}>
                                    {(selectCategoryTree[idx].childCat as any).map((cat: any) => (
                                        <Option key={cat.id} value={cat.id}>{cat.name}</Option>
                                    ))}
                                </Select>
                            )}

                        </div>
                        <div className={cx("ant-col ant-col-xs-24 ant-col-sm-24 ant-col-md-12 ant-col-xl-8 gutterCol")}>
                            {selectCategoryTree[idx] && selectCategoryTree[idx].childCat && (
                                <div className={styles.formLabel}>Brand Name  <span className={styles.starText}>*</span></div>)}


                            {/* {selectCategoryTree[idx] && selectCategoryTree[idx].childCat && (
                    <Select value={ val.catogory} className={styles.inputBusiness} allowClear={true} onChange={(e) =>{handleSubCatChange(e,idx)}}>
                    {(selectCategoryTree[idx].childCat as any).map((cat:any) => (
                            <Option key={cat.id} value={cat.id}>{cat.name}</Option>
                        ))}
                        </Select> 
                )} */}
                            {selectCategoryTree[idx] && selectCategoryTree[idx].childCat && (
                                <Input value={val?.brands} onChange={(e) => { handleBrandChange(e.target.value, idx) }} />)}

                        </div>
                        {selectCategoryTree[idx] && selectCategoryTree[idx].parentCat && (<>
                            {idx != 0 ? <div onClick={() => handleRemove(idx)} className={styles.iconContainer}>
                                <MinusCircleOutlined style={{ fontSize: "28px", color: "#3C3C3C" }} />
                            </div> : <div onClick={handleMore} className={styles.iconContainer}>
                                <PlusCircleOutlined style={{ fontSize: "28px" }} />
                            </div>}
                        </>
                        )}
                    </div>)
                })}
            </>
        )
    }
    return (
        <>
            <div className={(props.current == 1 ? cx("ant-row gutterRow") : ' hidden')}>
                <div className={cx("ant-col ant-col-xs-24 ant-col-sm-24 ant-col-md-24 ant-col-xl-18 gutterCol")}>
                    <h2 className={styles.leftTitle}>Tell us about your Business</h2>
                    <div className={cx("ant-row gutterRow", styles.cardContainer)}>
                        <div className={cx("ant-col ant-col-xs-24 ant-col-sm-24 ant-col-md-24 ant-col-xl-12 mb-3 gutterCol")}>
                            <div className={styles.formLabel}>Display Name  <span className={styles.starText}>*</span></div>
                            <Input placeholder="Enter Display Name" value={formData.shop_title} onChange={handleStorenameChange} />
                        </div>
                    </div>
                    {renderCards()}
                </div>
                <div className={cx("ant-col ant-col-xs-24 ant-col-sm-24 ant-col-md-24 ant-col-xl-6 gutterCol")}>
                    <h2 className={styles.rightTitle}>Complete your Profile!</h2>
                    {/* <div className={styles.rightCardContainer}>
                   <div className={styles.cardTitleMain}>
                <InfoCircleOutlined />
                <h2 className={styles.cardTitle}>Set of Documents</h2>
                </div>
                <div className={cx("mt-2 mb-2")}>
                <Text className={styles.cardContent}>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqu.</Text>
                </div>
                
                <Text className={cx(styles.cardContent)}>Adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqu.</Text>
                </div> */}
                </div>
            </div>
        </>
    )

}
export default AboutBusiness;