import React, { useState, useEffect, useContext } from 'react';

import { useLocation } from 'react-router-dom';

import { Skeleton, Typography, message, Switch, Form, Input, Select, Checkbox } from 'antd';


import AsyncSelect from 'react-select/async';

import { Table, Card, Button, JSONInput, GlobalContext } from './../../../../lib/';

import { ModelsAPI, PagesAPI } from '../../..';

import { UsersAPI } from '../../..';

const { Title } = Typography;

const { Option } = Select;

const UserAdd = ({ model, callback, edit, history, formContent, match, additional_queries, props }) => {

    /**Getting user data */
    const { user = {} } = useContext(GlobalContext);
    let mode = 'Add';

    const [disabled, setDisabled] = useState(true);

    const [selectedOption, setSelectedOption] = useState(null);

    //Need to check this condition
    const [authentication, setAuthentication] = useState(false);

    /**To store user values */
    const [users, setUsers] = useState([]);

    /**Converting to JSON */
    let firmDetails = JSON.parse(user.firm.f_otherdetails1);

    /**Variable for cheaking mandatory condition of mobile*/
    let mobileRequired;

    /**If mode is mobile and fa is 'MND' or 'USR' then  mobile is mandatory */
    if ((firmDetails && firmDetails.FA === 'MND' || firmDetails && firmDetails.FA === 'USR') && (firmDetails.mode === 'mobile')) {

        mobileRequired = true

    } else {

        mobileRequired = false
    }

    if (formContent.id) {
        mode = 'Edit'
    } else if (formContent.copy) {
        mode = 'Copy'
    }

    if (formContent.attributes) {

        if (typeof formContent.attributes === 'string') {

            if (formContent.attributes !== '') {

                formContent.attributes = JSON.parse(formContent.attributes);

            } else {

                formContent.attributes = {};

            }
        }
    } else {
        formContent.attributes = {}
    }

    const [loading, setLoading] = useState(true);

    const [form] = Form.useForm();

    const [body, setBody] = useState(formContent);

    const [isPasswordVisible, setIsPasswordVisible] = useState(false);

    const formData = {
        ...body,
        /**If panel is open then takes password in body */
        password: !isPasswordVisible ? "" : body.password
    }


    let passwordRegex
    let passwordRegexMessage

    if (props && props?.passwordRegex && props?.passwordRegexMessage) {
        passwordRegex = props.passwordRegex
        passwordRegexMessage = props.passwordRegexMessage
    } else if (process.env.REACT_APP_PASSWORD_REGEX && process.env.REACT_APP_PASSWORD_REGEX_MESSAGE) {
        passwordRegex = process.env.REACT_APP_PASSWORD_REGEX
        passwordRegexMessage = process.env.REACT_APP_PASSWORD_REGEX_MESSAGE
    } else {
        passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*(),.?":{}|<>])[A-Za-z\d!@#$%^&*(),.?":{}|<>]{8,}$/
        passwordRegexMessage = "Password must be at least 8 characters long and contain atleast one uppercase letter, one lowercase letter, one digit and one special character"
    }




    useEffect(() => {
        if (formContent.auth_user) {
            setSelectedOption({
                value: formContent.auth_user,
                label: formContent.auth_user, // Add a helper function to capitalize
            });
        }
    }, [formContent.auth_user]);


    useEffect(() => {

        loadUsers()
        setLoading(false);

        if (firmDetails) {

            /**if firmmas.otherdetails - 2FA == MND, then, 2FA option will be enabled by default and read-only  */
            if (firmDetails.FA == 'MND') {

                setAuthentication(true)

                setDisabled(true)

                /**if firmmas.otherdetails - 2FA == OPT, then, 2FA option will be enabled by default and editable */
            } else if (firmDetails.FA == 'USR') {

                setAuthentication(true)

                setDisabled(true)

                /**if firmmas.otherdetails - 2FA == NAP, then, 2FA option will be disabled by default and read-only*/
            } else if (firmDetails.FA == 'NAP') {

                setAuthentication(false)

                setDisabled(true)
            }

        }


    }, []);

    /**
     * Submit values
     */
    const onSubmit = (values) => {

        /**If PanelOpen is open and edit mode then password will be existing password else new password*/
        if (!isPasswordVisible && mode === 'Edit') {
            values.password = body.password;
        }

        values = {
            ...values,
            auth_type: 'LDAP',
            FA: authentication
        }

        setLoading(true);

        let id = formContent.id;
        if (props.ldap && selectedOption && selectedOption.value) {
            values = {
                ...values,
                addAllBranches: props.ldap.addAllBranches,
                auth_user: selectedOption.value,
                auth_type: 'LDAP',
                FA: authentication
            }
        }

        if (values.attributes && typeof values === 'object') {

            values = {
                ...values,
                auth_type: 'LDAP',

                attributes: JSON.stringify(values.attributes)
            }
        }

        if (id) {

            // Update of model
            UsersAPI.updateUser({ id, formBody: values }).then((result) => {

                if (result.success)

                    message.success(result.message);

                else
                    message.error(result.message)

                setLoading(false);

                callback();

            });

        } else {

            // Append the additional queries to the object
            additional_queries.forEach(({ field, value }) => {

                values[field] = value;

            })

            // add new model
            UsersAPI.create(values).then((result) => {

                // callback();
                if (result.success)

                    message.success(result.message);

                else
                    message.error(result.message)

                setLoading(false);

                callback();

            });
        }
    };

    /**
   * Function on handle change
   * @param {*} selected 
   */
    const handleCheackChange = (e) => {

        setIsPasswordVisible(e.target.checked);
    };


    function changeView(result) {

        setAuthentication(result);
    }

    /**
     * Function to add load userrs
     */
    function loadUsers() {

        // UsersAPI.getLdapUsers().then((result) => {

        //     setUsers(result.result);

        // });

    }

    // Transform array into react-select options
    let options = users.map(item => ({
        value: item.name,
        label: item.name// Capitalize the first letter
    }));

    /**
     * Function on handle change
     * @param {*} selected 
     */
    const handleChange = (selected) => {
        setSelectedOption(selected);
    };
    /**
     * 
     * @param {*} inputValue 
     * @param {*} callback 
     */

    const loadOptions = (inputValue, callback) => {
        // Filter options based on input
        const filteredOptions = options.filter(option =>
            option.label.toLowerCase().includes(inputValue.toLowerCase())
        );
        callback(filteredOptions);
    };

    return (
        <section className="collection-add">
            <Title level={4}>{mode} User</Title>

            {loading ? (
                <Skeleton />
            ) : (
                <Form initialValues={formData} form={form} layout="vertical" onFinish={onSubmit}>

                    {/* Caption */}
                    <Form.Item name={"name"} label="Name" required>
                        <Input placeholder="Enter name" />
                    </Form.Item>
                    {/* Caption Ends */}

                    {/* Name */}
                    <Form.Item name={"email"} label="Email" required>
                        <Input placeholder="Enter email" />
                    </Form.Item>
                    {/* Name Ends */}

                    {formContent.id ? (
                        <>
                            <Form.Item>
                                <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                                    <Checkbox onChange={handleCheackChange} />
                                    <span>Select the option if you want to change the password</span>
                                </div>
                            </Form.Item>

                            {isPasswordVisible && (
                                <Form.Item
                                    name="password"
                                    label="Password"
                                    rules={[
                                        { required: true, message: 'Please enter your password' },
                                        { pattern: passwordRegex, message: passwordRegexMessage },
                                    ]}
                                >
                                    <Input.Password placeholder="Enter password" autoComplete="new-password" />
                                </Form.Item>
                            )}
                        </>
                    ) : (
                        <Form.Item
                            name="password"
                            label="Password"
                            rules={[
                                {
                                    required: true,
                                    message: 'Please enter your password',
                                },
                                {
                                    pattern: new RegExp(passwordRegex),
                                    message: passwordRegexMessage,
                                },
                            ]}
                        >
                            <Input.Password visibilityToggle={false} placeholder="Enter password" autoComplete="new-password" />
                        </Form.Item>
                    )}

                    {/* </Form.Item> */}


                    {/* Path */}
                    {/* <Form.Item name="password" label="Password"
                        rules={[
                            {
                                required: true,
                                message: 'Please enter your password',
                            },
                            {
                                pattern: new RegExp(passwordRegex),
                                message: passwordRegexMessage,
                            },
                        ]}>
                        <Input.Password visibilityToggle={false} placeholder="Enter password" autoComplete='new-password' />
                    </Form.Item> */}
                    {/* Path Ends */}


                    {/* Path */}
                    <Form.Item name="user_group" label="User Group" required>
                        <Input placeholder="Enter User Group" />
                    </Form.Item>

                    <Form.Item name="mobile" label="Mobile" required={mobileRequired}>
                        <Input placeholder="Enter Mobile" />
                    </Form.Item>

                    {props.ldap && (
                        <>
                            <Form.Item name="auth_type" label="auth_type">
                                <Input placeholder="Enter auth_type" value={"LDAP"} disabled />


                                {/* <Select

                            placeholder="Auth Type"
                            defaultValue={'LDAP'}
                            // value={formContent && formContent.auth_type?formContent.auth_type:'LDAP'}
                            allowClear
                        // style={{ width: '60%' }}
                        >
                            <Option value={props.user_type}>
                                {props.user_type}
                            </Option>
                        </Select> */}

                                {/* <div style={{ display: 'flex', justifyContent: 'space-between' }}>

                            <div style={{ width: '40%' }}>
 
                            </div>

                            

                        </div> */}
                            </Form.Item>

                            {/* Path */}
                            <Form.Item name="auth_user" label="User Name" required>
                                <Input placeholder="Enter User Name" />
                            </Form.Item>
                        </>
                    )}


                    <Form.Item>

                        <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                            <Switch
                                disabled={disabled}
                                // defaultChecked={view}
                                onChange={changeView}
                                checked={authentication}
                                // disabled={disabled}
                                defaultChecked
                            // checkedChildren={<OrderedListOutlined />}
                            // unCheckedChildren={<PicCenterOutlined />}
                            />
                            <span>Enable Two Factor Authentication</span>

                        </div>
                    </Form.Item>
                    {/* Path Ends */}

                    {/* Path */}
                    {/* <Form.Item name="active" label="Active" required>
                        <Switch />
                    </Form.Item> */}
                    {/* Path Ends */}

                    <Form.Item>
                        <Button loading={loading} htmlType={'submit'} type="primary">
                            Submit
                        </Button>
                    </Form.Item>
                </Form>
            )
            }
        </section >
    );
};

export default UserAdd;
