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

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

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

import { Button } from './../../../../lib';

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

const { Title } = Typography;

const { Option } = Select;



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

    const [roles, setRoles] = useState([]);

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

    const [form] = Form.useForm();

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

    const [selectRoleDescription, setSelectRoleDescription] = useState('') //For storing selected roles description

    let location = useLocation();

    const query = new URLSearchParams(location.search);

    let step = parseInt(query.get('step')) || 0;

    useEffect(() => {

        // loadModelColumns();
        getRoles();
        setLoading(false);

    }, []);


    /**
     * Load the Staffs
     */
    const getRoles = () => {

        RolesAPI.get({ url: 'core-roles' }).then((result) => {
            setRoles(result.result);
        });
    };

    /**
     * Function which is to select role
     */
    const selectedRole = (key, value) => {

        //Matching the selected name to get the descrption of that role
        let data = roles.filter((result) => result.id == value.value)

        //Storing the descrption to the state
        setSelectRoleDescription(data[0].description)
    }

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

        let id = formContent.id;

        if (id) {
            // Update of model
            model.update({ id, values }).then(() => {

                // callback();
                message.success('User Role Updated');
                setLoading(false);
                callback();

            });

        } else {

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

            // add new model
            model.addUserRole({ values }).then(() => {

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

                setLoading(false);

                callback();

            });
        }
    };

    return (
        <section className="collection-add">
            <Title level={4}>{edit ? 'Edit' : 'Add'} User Role</Title>

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

                        {/* Model */}
                        <Form.Item label="Roles" name={'role_id'} required>

                            {/* <ReferenceSelect value={model.id} label={model.name} model={Models} /> */}
                            <Select onSelect={selectedRole} style={{ width: '100%' }}>
                                {roles.map((model, key) => (
                                    <Option key={key} value={model.id}>{model.name}</Option>
                                ))}
                            </Select>

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

                        <Form.Item>
                            <Button loading={loading} htmlType={'submit'} type="primary">
                                Submit
                            </Button>
                        </Form.Item>
                    </Form>
                    {/*If role is added*/}
                    {selectRoleDescription ? (
                        <div className='card'>

                            <p>{selectRoleDescription}</p>

                        </div>
                    ) : null}
                </>
            )}
        </section>
    );
};

export default UserRolesAdd;
