import React, {memo, 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';

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

    const queryClient = useQueryClient()

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

    const fieldData = {}
    Object.entries(data)?.forEach(([key, value]) => { // LOOP TO POPULATE FIELDDATA PROPERTIES WITH DATA OF EACH TAB
    fieldData[value?.name?.toLowerCase().replaceAll(" ", "_")] = ''
    })
    backendValues.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
    })

    // console.log('fieldData', fieldData)

    const [fields, setFields] = useState(fieldData)
    
    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
            }
        }
        // console.log('formInfo', reqData)
        submitSettings.mutate(reqData)
      }

      if (isCustom ===  true){
          return  <SiteTemplateSelector  name={name} data={data} isCustom={isCustom} productData={productData} />
      }


      return (
        <div className="page-account-form">
            <div className="p-0" style={{ minHeight: '500px'}}>

                <form id='tab_form'>
                    <div className="form-row">
                        <>
                            {Object.entries(data)?.map(([key, value]) => {
                                let fieldName = value.name.toLowerCase().replaceAll(" ", "_")
                                let fieldValue = 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