// @ts-nocheck
import React from 'react';

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

import { Space, Popconfirm } from 'antd';

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

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

import GenericList from './../../modules/generic/components/generic-list/generic-list';

import GenericAdd from './../../modules/generic/components/generic-add/generic-add';

import GenericAddModal from './../../modules/generic/components/generic-add-modal/generic-add-modal';

import GenericEdit from './../../modules/generic/components/generic-edit/generic-edit';

import GenericDetail from './../../modules/generic/components/generic-detail/generic-detail';

import { DeleteOutlined } from '@ant-design/icons';

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

class BaseAPI {
    // name;
    // endpoint;
    // pluralName;
    // schema;

    // getEndpoint;

    // getEndpoint;

    endpoint;

    fields;
    // listFields;
    // filterFields;

    // columns = [];

    constructor(fields = []) {
        // this.path = this.path();

        this.endpoint = this.getEndpoint;

        this.name = this.getName;

        this.fields = fields;

        // this.columns = [];
    }

    // get columns() {
    //     return [];
    // }

    filterDate() {
        return false;
    }

    disableAddModal() {
        return false;
    }

    /**
     * Link for redirection
     */
    get link() {
        return this.name.toLowerCase() + '/create';
    }

    /**
     * Get the data from the table
     */
    getData({ path, queries = [] }) {
        // Get the records from firebase
        // return FirebaseUtils.get(path, queries, this);

        return ApiUtils.get({ url: path });

        // return ApiUtils.get(path, queries, this);
    }

    /**
     * Get the data from the table
     */
    get(config = {}) {
        // Get the records from firebase

        return ApiUtils.get({ url: config.url || this.endpoint, config });
    }

    getRelations(id) {
        // Get the records from firebase
        return ApiUtils.get({ url: `modelrelationship/getRelations/${id}` });
    }


    /**
     * Get the data from the table
     */
    getMethod(queries = []) {
        // Get the records from firebase
        // return FirebaseUtils.getRecords(queries, this);
    }

    /**
     *
     * @param {*} values
     * @returns
     */
    getPurchaseDetail = ({ id }) => {

        return ApiUtils.get({ url: this.endpoint + '/' + id + '?includes=purchase_details,purchase_details.item,purchase_details.packing' });
        // return FirebaseUtils.getRecord(id, this);
    };

    /**
     *
     * @param {*} values
     * @returns
     */
    getSaleDetail = ({ id }) => {
        return ApiUtils.get({ url: this.endpoint + '/' + id + '?includes=sale_details' });
        // return FirebaseUtils.getRecord(id, this);
    };


    fillCustomInputData=({ id })=>{
        return ApiUtils.get({ url: `core-scripts/fill-custom-input-data/${id}` });
    }

    /**
     *
     * @param {*} values
     * @returns
     */
    getRecord = ({ id }) => {
        return ApiUtils.get({ url: this.endpoint + '/' + id });
        // return FirebaseUtils.getRecord(id, this);
    };

    /**
     *
     * @param {*} values
     * @param {*} user
     * @returns
     */
    add = ({ values, user }) => {

        let formBody = {
            ...values,
        };

        return ApiUtils.post({ url: this.endpoint, formBody });
    };

    /**
      *
      * @param {*} values
      * @param {*} user
      * @returns
      */
    post = ({ url, formBody, user }) => {

        return ApiUtils.post({ url: url, formBody });
    };


    /**
     * Update of model
     *
     * @param {*} id
     * @param {*} values
     * @param {*} user
     * @returns
     */
    update = ({ id, values, user }) => {

        let formBody = {
            ...values,
        };

        return ApiUtils.put({ url: this.endpoint + '/' + id, formBody });
    };


    /**
     * Delete of model
     *
     * @param {*} id
     * @param {*} values
     * @param {*} user
     * @returns
     */
    delete = ({ id }) => {

        return ApiUtils.delete({ url: this.endpoint + '/' + id });
    };

    columns() {
        return [
            {
                caption: 'Name',
                field: 'name',
                key: 'name',
            },
            {
                caption: 'Weight',
                field: 'weight',
                key: 'weight',
            },
            {
                caption: 'Date',
                field: 'created_at',
                key: 'created_at',
            },
        ];
    }

    /**
     * Get the config of the url
     */
    getConfig = ({ query, config, range, field }) => {

        let baseUrl = this.endpoint;

        let start_time = DateUtils.formatDate(range[0])

        let end_time = DateUtils.formatDate(range[1])

        // baseUrl.search = new URLSearchParams({ url: myUrl });
        // baseUrl.search = new URLSearchParams({ url: myUrl });

        // let query = encodeURIComponent(`${field}>${start_time},${field}<${end_time}`)

        // const queryParams = { param1: 'value1', param2: 'value2' }

        // const queryString = new URLSearchParams(queryParams).toString()

        baseUrl += `?query=` + query;

        return {
            url: baseUrl
        };
    }

    /**
     * Base Column Configuration that would be used 
     * for all tables
     */
    getColumnConfig = ({ options, model, actions = [], callback, edit }) => {

        // console.log(options);

        /**
         * On delete of each record 
         */
        function onDelete(record) {

            model.delete(record).then(() => {

                callback();

            }).catch((error) => {

                setLoading(false);

                console.log(error);

            })
        }

        return [
            ...[
                {
                    title: '#',
                    dataIndex: 'index',
                    render: (value, item, index) => (options.page - 1) * options.size + index + 1,
                },
            ],
            ...model.columns.map((entry) => {
                if (entry.sort) {
                    return {
                        render: (record) => {
                            if (entry.render) {
                                return entry.render(record);
                            } else {
                                return entry.field.split('.').reduce((acc, part) => acc && acc[part], record);
                            }
                        },
                        title: entry.caption,
                        key: entry.field,
                        // sorter: (a, b) => entry.sort(a, b),
                        sortDirections: ['ascend', 'descend', 'ascend'],
                    };
                } else {
                    return {
                        render: (record) => {
                            if (entry.render) {
                                return entry.render(record);
                                // return entry.field.split('.').reduce((acc, part) => acc && acc[part], record);
                            } else {
                                return entry.field.split('.').reduce((acc, part) => acc && acc[part], record);
                            }
                            // return record[entry.field]
                        },
                        title: entry.caption,
                        key: entry.field,
                        // dataIndex: entry.field,
                    };
                }
            }),
            ...[
                {
                    title: '',
                    key: 'action',
                    render: (text, record) => {
                        return (
                            <Space size="middle">


                                {/* Delete Icon */}
                                <Popconfirm title="Are you sure" onConfirm={() => {
                                    onDelete(record);
                                }}>
                                    <Button type="dashed">
                                        <DeleteOutlined />
                                    </Button>
                                </Popconfirm>
                                {/* Delete Icon */}


                                {/* Edit */}
                                {!model.ModalAddComponent ? null : (
                                    <Button type="dashed" onClick={() => edit(record)}>
                                        Edit
                                    </Button>
                                )}
                                {/* Edit Ends */}

                                {/* {!model.hideView && !actions.length ? <Link to={`/${model.name}/${text.id}`}>View</Link> : null} */}

                                {!model.hideView && !actions.length ? <Link to={`/${model.link}/${record.id}`}>View</Link> : null}

                                {/* {actions.map((action) => (
                                    <Link to={action.url(record)}>{action.caption}</Link>
                                ))} */}
                            </Space>
                        );
                    },
                },
            ],
        ]

    }

    AddComponent = GenericAdd;

    ListComponent = GenericList;

    EditComponent = GenericEdit;

    DetailComponent = GenericDetail;

    ModalAddComponent = GenericAddModal;

    Card = ({ record, model }) => {
        return (
            <Link className="booking-card" to={`/${model.link}/${record['id']}`}>
                <div className="listing-card">

                    <Card>

                        Hello
                    </Card>

                    <h2 className="">{record.name}</h2>

                    <h3 className="title">{record.description}</h3>

                    <p className="address">Created by {record.created_by}</p>
                </div>
            </Link>
        );
    };


    // UploadComponent = GenericUpload;

    // ModalAddComponent = GenericAdd;
}

export default BaseAPI;
