import React, { memo, useMemo, useState } from 'react'
import GeneralTab from './GeneralTab'
import { getSettingsData, getMyProductConfig } from '../../../services/services';
import queryKeys from '../../../services/queryKeys';
import { useSelector } from 'react-redux';
import { useQuery } from '@tanstack/react-query';
import sortObjectByListOrder from '../../../helpers/sortObjectByListOrder'

const Settings = memo(({productData}) => {

    const { userDetails: { uid }} = useSelector((state) => state?.userDetails); // GETS USER UID

    const {data:configData, isFetching:configIsFetching, configIsError, error:configError} = useQuery({
        queryKey: queryKeys.myProductConfig,
        queryFn: () => {
            let reqData = {
                token: localStorage.getItem('token'), // USER TOKEN
                uid: localStorage.getItem('uid'), // USER UID
                product_id: productData?.product_id
            }
           return getMyProductConfig(reqData)
        },
        staleTime: 0,
    })
    const settingsConfig = configData?.data?.settings_items
    // console.log('CONFIG DATA...', settingsConfig)


    const [fieldsChanged, setFieldsChanged] = useState(false)

    // const [activeTab, setActiveTab] = useState(Object.entries(settingsConfig)[0][1]?.controls)
     const [activeTab, setActiveTab] = useState(null)

    const handleChangeTab = (value) => {
        // if(fieldsChanged){
        //     const proceed = confirm('Continue without saving changes')
        //     if(proceed){
        //         setActiveTab(value)
        //         setFieldsChanged(false)
        //     }
        // }else{
        //     setActiveTab(value)
        // }
        setActiveTab(value)
    }


    const {data, isFetching, isError, error} = useQuery({
        queryKey: queryKeys.settingsData,
        queryFn: () => {
            let reqData = {
                token: localStorage.getItem('token'), // USER TOKEN
                uid: localStorage.getItem('uid'), // USER UID
                product_id: productData?.product_id
            }
           return getSettingsData(reqData)
        },
        staleTime: 0,
        enabled: settingsConfig ? true : false
    })

    const settingsData = {data: data?.data?.settings, isFetching, isError, error}
    // console.log('data', settingsData)

    const sortedSettingsConfig = sortObjectByListOrder(settingsConfig ? settingsConfig : {}) // SORTED SETTINGSCONFIG

      return (
        <>
        {configIsFetching ? 
            <>
                <div className="row">
                    <div className="col-12">
                        <p className='text-mute'>Loading...</p>
                    </div>
                </div>
            </>
            : configIsError ?
            <div className="row">
                <div className="col-12">
                    <p className='text-danger'>{configError.message}</p>
                </div>
            </div>
            :
            <div className="tab tab-vertical">
                <ul className="nav nav-tabs" role="tablist">
                    <>
                        {Object.entries(sortedSettingsConfig).map(([key, value], index) => (
                            <li key={key} className="nav-item">
                            <a className={`nav-link ${(activeTab == value.controls || (index == 0 & !activeTab)) && 'active show'}`}
                                id={key} 
                                // data-bs-toggle="pill"
                                // data-bs-target={`#${value.controls}`}
                                type="button" 
                                // role="tab"
                                // aria-controls={value.controls}
                                // aria-selected="true"
                                onClick={()=>handleChangeTab(value.controls)}
                            >
                                {value.title}
                            </a>
                            </li>
                        ))}
                    </>
                </ul>
                <div className="tab-content">
                    <>
                        {Object.entries(sortedSettingsConfig).map(([key, value], index) => (
                            <div key={key} className={`tab-pane fade  ${(activeTab == value.controls || (index == 0 & !activeTab)) && 'active show'}`}
                                // id={value.controls} role="tabpanel"
                                // aria-labelledby={key}
                            >
                                <GeneralTab tabKey={key} name={value.title} data={value.data} isCustom={value.custom} productData={productData} backendValues={settingsData} setFieldsChanged={setFieldsChanged} />
                            </div>
                        ))}
                    </>
                </div>
            </div>
            }
        </>
      )
    }
)

export default Settings