import React, {memo, useEffect, useMemo, useState} from 'react'
import {useMutation, useQueryClient} from "@tanstack/react-query";
import {pageSettings} from "../../../services/services";
import SiteTemplateSelector from './SiteTemplateSelector';
import NoYesBooleanDropdown from './NoYesBooleanDropdown';
import {IoMdArrowDropdown} from 'react-icons/io';
import queryKeys from '../../../services/queryKeys';
import sortObjectByListOrder from '../../../helpers/sortObjectByListOrder';
import URLConfiguration from "./URLConfiguration";
import ColorStyleConfigure from "./ColorStyleConfigure";

const GeneralTab = memo(({
                             name = 'Full Name',
                             data,
                             tabKey,
                             isCustom,
                             productData,
                             backendValues,
                             setFieldsChanged
                         }) => {

        const queryClient = useQueryClient()

        const [reqStatus, setReqStatus] = useState({error: null, message: ''})


        // const computeFieldData = useMemo(()=>{
        //     const fieldData = {}
        //     Object.entries(data)?.forEach(([key, value]) => { // LOOP TO POPULATE FIELDDATA PROPERTIES WITH DATA OF EACH TAB
        //     fieldData[value?.name?.toLowerCase().replaceAll(" ", "_")] = ''
        //     })
        //     backendValues?.data?.forEach(item => { //LOOPING THROUGH USER ALREADY ADDED DATA FROM BACKEND IF ANY AND UPDATING THE FIELDDATA OBJECT
        //     fieldData[item?.setting_key?.toLowerCase().replaceAll(" ", "_")] = item?.setting_value
        //     })
        //     return fieldData
        // },[backendValues.data])


        const [fields, setFields] = useState({})

        const sortedData = sortObjectByListOrder(data ? data : {}) // SORTED SETTINGSCONFIG

        useEffect(() => {
            const fieldData = {}
            Object.entries(sortedData)?.forEach(([key, value]) => { // LOOP TO POPULATE FIELDDATA PROPERTIES WITH DATA OF EACH TAB
                fieldData[value?.name?.toLowerCase().replaceAll(" ", "_")] = ''
            })
            backendValues?.data?.forEach(item => { //LOOPING THROUGH USER ALREADY ADDED DATA FROM BACKEND IF ANY AND UPDATING THE FIELDDATA OBJECT
                fieldData[item?.setting_key?.toLowerCase().replaceAll(" ", "_")] = item?.setting_value
            })
            setFields(fieldData)
        }, [backendValues.data])

        const handleChange = ({target: {name, value}}) => {
            setFields(prev => ({...prev, [name]: value}))
            setFieldsChanged(true)
        }

        const submitSettings = useMutation({
            mutationFn: (fields) => {
                return pageSettings(fields)
            },
            onSuccess: (res) => {
                if (res?.data?.resultCode != '0') {
                    return setReqStatus({error: true, message: 'Unable to complete, try again later'})
                }
                setFieldsChanged(false)
                setReqStatus({error: false, message: 'Completed successfully'})
            },
            onError: (err) => {
                setReqStatus({error: true, message: 'Unable to complete, try again later'})
            },
            onSettled: () => {
                queryClient.refetchQueries({  // refetches productProvision API call
                    queryKey: [...queryKeys.settingsData],
                })
                setTimeout(() => {
                    setReqStatus({error: null, message: ''})
                }, 3000)
            },
        })

        const handleSubmit = () => {
            const reqData = {
                token: localStorage.getItem('token'), // USER TOKEN
                uid: localStorage.getItem('uid'), // USER UID
                product_id: productData?.product_id,
                settings: {
                    ...fields
                }
            }
            submitSettings.mutate(reqData)
        }
        console.log(tabKey);
        return (
            <>
                {backendValues?.isFetching || !backendValues?.data ?
                    <>
                        <div className="row">
                            <div className="col-12">
                                <p className='text-mute'>Loading...</p>
                            </div>
                        </div>
                    </>
                    : backendValues?.isError ?
                        <div className="row">
                            <div className="col-12">
                                <p className='text-danger'>{backendValues?.error.message}</p>
                            </div>
                        </div>
                        :
                        <>
                            {isCustom === true ?
                                <>
                                    {(tabKey === 'template_tab') && <SiteTemplateSelector name={name} data={sortedData} isCustom={isCustom} productData={productData}/>}
                                    {(tabKey === 'url_config_tab') && <URLConfiguration name={name} data={sortedData} isCustom={isCustom} productData={productData}/>}
                                    {(tabKey === 'color_scheme_tab') && <ColorStyleConfigure name={name} data={sortedData} isCustom={isCustom} productData={productData}/>}
                                </>
                                :
                                <div className="page-account-form">
                                    <div className="p-0" style={{minHeight: '500px'}}>

                                        <form id='tab_form'>
                                            <div className="form-row">
                                                <>
                                                    {Object.entries(sortedData)?.map(([key, value]) => {
                                                            let fieldName = key; // value.key.toLowerCase().replaceAll(" ", "_")
                                                            let fieldValue = fields[key]; //fields[value.name.toLowerCase().replaceAll(" ", "_")]
                                                            return (
                                                                <div key={key} className="form-group col-md-12">
                                                                    <label htmlFor="name1">{value.name}</label>
                                                                    {value.controls === 'TEXT' ?
                                                                        <input name={fieldName} type="text"
                                                                               className="form-control" id={key}
                                                                               value={fieldValue} onChange={handleChange}/>
                                                                        : value.controls === 'TEXTAREA' ?
                                                                            <textarea name={fieldName} rows={5}
                                                                                      style={{resize: 'none'}} type="text"
                                                                                      className="form-control" id={key}
                                                                                      value={fieldValue}
                                                                                      onChange={handleChange}/>
                                                                            : value.controls === 'SELECT_NO_YES' ?
                                                                                // <NoYesBooleanDropdown name={fieldName} value={fieldValue} onChange={handleChange}  />
                                                                                <div className='position-relative'>
                                                                                    <select onChange={handleChange}
                                                                                            name={fieldName} value={fieldValue}
                                                                                            className="form-control">
                                                                                        <option value=''>Select</option>
                                                                                        <option value='0'>No</option>
                                                                                        <option value='1'>Yes</option>
                                                                                    </select>
                                                                                    <IoMdArrowDropdown
                                                                                        className='position-absolute w-auto'
                                                                                        style={{
                                                                                            top: '50%',
                                                                                            right: '2px',
                                                                                            transform: 'translateY(-50%)'
                                                                                        }}/>
                                                                                </div>
                                                                                :
                                                                                null
                                                                    }
                                                                </div>
                                                            )
                                                        }
                                                    )}
                                                </>
                                                {reqStatus.message &&
                                                    <>
                                                        <div className="col-12">
                                                            <p className={reqStatus.error ? 'text-danger' : 'text-success'}>{reqStatus.message}</p>
                                                        </div>
                                                    </>
                                                }
                                                <div className="form-group col-md-12" style={{textAlign: 'right'}}>
                                                    <button onClick={handleSubmit} type="button" className="btn btn-primary"
                                                            disabled={submitSettings.isPending}>{submitSettings.isPending ? 'Loading...' : 'Update'}</button>
                                                </div>
                                            </div>
                                        </form>
                                    </div>
                                </div>
                            }
                        </>
                }
            </>
        )
    }
)


export default GeneralTab