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'
import TemplateConfigure from './TemplateConfigure';

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)
    // console.log('configData', configData?.data?.subscription_template)

    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="d-flex">
                <ul className="bg-body-secondary flex-column nav" role="tablist" style={{width: '25%', minHeight: '670px', maxHeight: '670px'}}>
                    <>
                        {Object.entries(sortedSettingsConfig).map(([key, value], index) => (
                            <li key={key} className="nav-item">
                            <p className={`text-black nav-link ${(activeTab == value.controls || (index == 0 & !activeTab)) && 'active show bg-primary text-white'}`}
                                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}
                            </p>
                            </li>
                        ))}
                        {configData?.data?.subscription_template &&
                            <li className="mt-auto nav-item">
                                <p className={`text-black nav-link ${(activeTab == 'config_temp') && 'active show bg-primary text-white'}`}
                                    // data-bs-toggle="pill"
                                    // data-bs-target={`#${value.controls}`}
                                    type="button" 
                                    // role="tab"
                                    // aria-controls={value.controls}
                                    // aria-selected="true"
                                    onClick={()=>handleChangeTab('config_temp')}
                                >
                                    Configure Template
                                </p>
                            </li>
                        }
                    </>
                </ul>
                <div className="p-3 tab-content" style={{width: '75%'}}>
                    <>
                        {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 className={`tab-pane fade  ${(activeTab == 'config_temp') && 'active show'}`}
                        >
                            <TemplateConfigure productData={productData} />
                        </div>
                    </>
                </div>
            </div>
            }
        </>
      )
    }
)

export default Settings