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

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

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

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

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

const { TextArea } = Input;

const { Title } = Typography;

const { Option } = Select;

import './menu-add.scss';


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

    let mode = 'Add';

    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 [pages, setPages] = useState([]);

    const [models, setModels] = useState([]);

    const [menus, setMenus] = useState([])

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

    const { params } = match;

    let location = useLocation();

    const query = new URLSearchParams(location.search);

    console.log(query.get('step'));

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

    console.log(step);

    useEffect(() => {

        // loadModelColumns();
        getPages();

        getModels();

        setLoading(false);

        getMenus();

    }, []);


    /**
     * Load the Staffs
     */
    const getPages = () => {
        PagesAPI.getPages().then((result) => {

            if (Array.isArray(result.result)) {
                setPages(result.result);
            }
        });
    };

    /**
     * Load the Models
     */
    const getModels = () => {
        ModelsAPI.get().then((result) => {
            // console.log(result);

            setModels(result.result);
        });
    };


    /**
  * Load the Models
  */
    const getMenus = () => {
        MenusAPI.get().then((result) => {
            // console.log(result);

            setMenus(result.result);
        });
    };


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

        let id = formContent.id;

        // Add the step to form content
        // values.step = step;

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

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

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

                // callback();
                message.success('Menu Updated');

                setLoading(false);

                callback();

            });

        } else {

            values.step = step;

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

                values[field] = value;

            })

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

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

                setLoading(false);

                callback();

            });
        }
    };

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

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

                    <div className='form-container'>
                        <div className='left-container'>


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

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

                            {/* Description */}
                            <Form.Item name={"description"} label="Description">
                                <TextArea placeholder="Enter Description" />
                            </Form.Item>
                            {/* Description Ends */}

                            {/* Model */}
                            <Form.Item label="Models" name={'model_id'}>

                                {/* <ReferenceSelect value={model.id} label={model.name} model={Models} /> */}
                                <Select showSearch optionFilterProp="children" style={{ width: '100%' }}>
                                    {models.map((model, key) => (
                                        <Option key={key} value={model.id}>{model.name}</Option>
                                    ))}
                                </Select>

                            </Form.Item>
                            {/* Model Ends


                    {/* Pages */}
                            <Form.Item label="Pages" name={'page_id'}>

                                {/* <ReferenceSelect value={pages.id} label={pages.name} model={Pages} /> */}

                                <Select showSearch optionFilterProp="children" style={{ width: '100%' }}>
                                    {pages.map((model, key) => (
                                        <Option key={key} value={model.id}>{model.name}</Option>
                                    ))}
                                </Select>

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



                            {/* Pages */}
                            <Form.Item label="Header" name={'header_id'}>

                                {/* <ReferenceSelect value={pages.id} label={pages.name} model={Pages} /> */}

                                <Select showSearch style={{ width: '100%' }}>
                                    {menus.map((menu, key) => (
                                        <Option key={key} value={menu.id}>{menu.name}</Option>
                                    ))}
                                </Select>

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


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

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

                            {/* Switch */}
                            <Form.Item name="is_visible" label="Visible" required>
                                <Switch defaultChecked={body.is_visible} />
                            </Form.Item>
                            {/* Switch Ends */}

                            {/* Step */}
                            <Form.Item name={"order"} label="Order" required>
                                <InputNumber placeholder="Enter order" />
                            </Form.Item>
                            {/* Step Ends */}

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

                            {/* Step */}
                            <Form.Item name={"step"} label="Step" required>
                                <InputNumber placeholder="Enter step" />
                            </Form.Item>
                            {/* Step Ends */}


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

                        </div>
                        <div className='right-container'>


                            {/* Description */}
                            <Form.Item name={"attributes"} label="Attributes">

                                <JSONInput />

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

                        </div>

                    </div>

                </Form>
            )}
        </section>
    );
};

export default MenuAdd;
