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

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

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

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

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

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

const { Title } = Typography;

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

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

    /**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);

    useEffect(() => {


        setLoading(false);

    }, []);


    /**
     * Submit values
     */
    const onSubmit = (values) => {
        // console.log(values);
        setLoading(true);

        let id = formContent.id;

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

            values = {
                ...values,
                attributes: JSON.stringify(values.attributes)
            }
        }

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

                if (result.success && result.result)

                    message.success('User Updated');

                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(() => {

                // callback();
                message.success('User Added');

                setLoading(false);

                callback();

            });
        }
    };

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

            {loading ? (
                <Skeleton />
            ) : (
                <Form initialValues={{ ...body }} 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 */}

                    {/* Path */}
                    <Form.Item name="password" label="Password" required>
                        <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>
                    {/* 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;
