import React, { Component } from 'react';
import PageTitle from "../../Components/PageTitle";
import { SubmitBtn } from "../../Components/InputElements";
import axios from 'axios';
import Swal from 'sweetalert2';
import withRouter from '../../Utils/withRouter';
import { ConfigContext } from '../../Context/ConfigContext'
import { ContentLoader, NoRecords } from "../../Components/Shimmer";

class Users extends Component {
    static contextType = ConfigContext;
    constructor(props) {
        super(props);
        this.state = {
            user_id: 0,
            user_name: '',
            login_id: '',
            login_password: '',
            rows: [],
            next: false,
            prev: false,
            page: 1,
            limit: 10,
            total_records: 0,
            total_pages: 0,
            loadingList: false,
            postLoading: false,
            errors: {},
        };
    }
    componentDidMount() {
        this.setState({ loadingList: true }, (prevState) => {
            this.GetList();
        })
    }
    handleInputChange = (e) => {
        const errors = { ...this.state.errors };
        delete errors[e.target.name];

        this.setState({
            [e.target.name]: e.target.value,
            errors: errors,
        });
    };

    GetInfo = () => {
        const { apiURL, apiHeaderJson } = this.context;
        const headers = apiHeaderJson;
        axios.get(`${apiURL}CompanyMasters/GetCompanyUserInfo`, {
            params: {
                user_id: this.state.user_id,
            }, headers
        }).then((response) => {
            const { data, success } = response.data;
            if (success === true) {
                this.resetForm();
                this.setState(
                    {
                        login_id: data[0].login_id,
                        login_password: data[0].login_password,
                        user_id: data[0].user_id,
                        user_name: data[0].user_name,
                    }
                )
            }
        });
    }
    GetList = () => {
        const { apiURL, apiHeaderJson } = this.context;
        const headers = apiHeaderJson;
        axios.get(`${apiURL}CompanyMasters/GetCompanyUsers`, { params: { limit: this.state.limit, page: this.state.page }, headers }).then((response) => {

            var data = response.data;
            if (response.data.success === true) {
                this.setState({
                    rows: data.data,
                    next: data.next,
                    prev: data.prev,
                    page: data.page,
                    total_records: data.total_records,
                    total_pages: data.total_pages,
                    loadingList: false
                });
            } else {
                this.setState({ loadingList: false });
            }
        });
    }

    validateForm = () => {
        const errors = {};
        const loginIdRegex = /^[a-zA-Z0-9_]{3,20}$/;
        const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@])[a-zA-Z\d@]{8,}$/;
      
        if (this.state.login_id.trim() === '') {
          errors.login_id = 'Login ID is required';
        } else if (!loginIdRegex.test(this.state.login_id.trim())) {
          errors.login_id = 'Login ID must be 3 to 20 characters long and can only contain letters, numbers, and underscores';
        }
      
        if (this.state.login_password.trim() === '') {
          errors.login_password = 'Login Password is required';
        } else if (!passwordRegex.test(this.state.login_password.trim())) {
          errors.login_password = 'Password must be at least 8 characters long and contain at least one lowercase letter, one uppercase letter, one number, and one special character (@)';
        }
      
        if (this.state.user_name.trim() === '') {
          errors.user_name = 'User Name is required';
        }
      
        this.setState({ errors });
        return Object.keys(errors).length === 0;
      };      

    handleSubmit = (e) => {
        e.preventDefault();
        if (!this.validateForm()) {
            return;
        }
        const { apiURL, apiHeaderJson } = this.context;
        const headers = apiHeaderJson;
        var formData = {
            user_name: this.state.user_name,
            login_id: this.state.login_id,
            login_password: this.state.login_password,
        }
        if (this.state.user_id !== 0) {
            formData.user_id = this.state.user_id;
        }

        axios.post(`${apiURL}CompanyMasters/CreateCompanyUser`, formData, { headers }).then((response) => {
            const { success } = response.data;
            if (success === true) {
                this.resetForm();
                this.setState({ loadingList: true }, (prevState) => {
                    this.GetList();
                })
                Swal.fire({
                    title: `<strong>${response.data.success === true ? 'Success' : 'Failed'}</strong>`,
                    text: response.data.message,
                    icon: response.data.success === true ? 'success' : 'error',
                    timer: 2000,
                    timerProgressBar: true,
                    showConfirmButton: false,
                })
            } else {
                Swal.fire({
                    title: `<strong>${response.data.success === true ? 'Success' : 'Failed'}</strong>`,
                    text: response.data.message,
                    icon: response.data.success === true ? 'success' : 'error',
                    timer: 2000,
                    timerProgressBar: true,
                    showConfirmButton: false,
                })
                this.setState({ loadingList: true }, (prevState) => {
                    this.GetList();
                })
            }

        })
    };
    resetForm = () => {
        this.setState({
            errors: {},
            user_id: 0,
            login_id: '',
            login_password: '',
            user_name: '',
        })

    }

    handleDelete = (id) => {
        const { apiURL, apiHeaderJson } = this.context;
        const headers = apiHeaderJson;
        Swal.fire(
            {
                title: 'Are you sure?',
                text: "You won't be able to revert this!",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Yes, delete it!'
            }
        ).then((result) => {
            if (result.isConfirmed) {
                this.setState({ status: true });
                const formData = {
                    user_id: id
                };
                axios
                    .post(`${apiURL}CompanyMasters/DeleteCompanyUser`, formData, { headers })
                    .then((response) => {

                        Swal.fire({
                            title: `<strong>${response.data.success === true ? 'Success' : 'Failed'}</strong>`,
                            text: response.data.message,
                            icon: response.data.success === true ? 'success' : 'error',
                            timer: 1000,
                            timerProgressBar: true,
                            showConfirmButton: false,
                        })
                        this.setState({ status: false });
                        if (response.data.success === true) {
                            this.setState({ loadingList: true }, (prevState) => {
                                this.GetList();
                            })
                        }
                    })
                    .catch((error) => {

                        Swal.fire({
                            title: <strong>Error</strong>,
                            html: error,
                            icon: 'error'
                        })
                    });
            }
        });
    }

    handlePrev = (ev) => {

        if (this.state.prev === true) {
            this.setState((prevState) => {
                return { page: prevState.page - 1 };
            }, () => {
                this.GetList();
            });
        }
    }
    handleNext = () => {

        if (this.state.next === true) {
            this.setState((prevState) => {
                return { page: prevState.page + 1 };
            }, () => {
                this.GetList();
            });
        }
    }
    handleChange = (e) => {

        this.setState((prevState) => {
            return { page: parseInt(e.target.value, 10) };
        }, () => {
            this.GetList();
        });
    }

    render() {
        const { errors, loadingList } = this.state;
        return (
            <div className="main-content">
                <div className="page-content">
                    {loadingList === false ? (
                        <div className="container-fluid">
                            <br />
                            <PageTitle title={`Users Management`} primary={`Home`} />
                            <div className="row">
                                <div className="col-md-5">
                                    <div className="card">
                                        <div className="card-header align-items-center d-flex">
                                            <h4 className="card-title mb-0 flex-grow-1">Users Management</h4>
                                        </div>
                                        <div className="card-body">
                                            <div className="row gy-4">
                                                <div className="col-md-12">
                                                    <form onSubmit={this.handleSubmit} className="row">
                                                        <div className="col-md-12">
                                                            <label for="user_name">User name</label>
                                                            <input
                                                                type="text"
                                                                name="user_name"
                                                                id='user_name'
                                                                value={this.state.user_name}
                                                                onChange={this.handleInputChange}
                                                                className={`form-control ${errors.user_name ? 'is-invalid' : ''}`}
                                                                placeholder="Enter user name"
                                                            />
                                                            {errors.user_name && <div className="text-danger">{errors.user_name}</div>}
                                                        </div>

                                                        <div className="col-md-12" style={{ marginTop: "10px" }}>
                                                            <label for="login_id">Login id</label>
                                                            <input
                                                                type="text"
                                                                name="login_id"
                                                                id="login_id"
                                                                value={this.state.login_id}
                                                                onChange={this.handleInputChange}
                                                                className={`form-control ${errors.login_id ? 'is-invalid' : ''}`}
                                                                placeholder="Enter login id"
                                                            />
                                                            {errors.login_id && <div className="text-danger">{errors.login_id}</div>}
                                                        </div>
                                                        <div className="col-md-12" style={{ marginTop: "10px" }}>
                                                            <label for="login_password">Login password</label>
                                                            <input
                                                                type="text"
                                                                name="login_password"
                                                                id="login_password"
                                                                value={this.state.login_password}
                                                                onChange={this.handleInputChange}
                                                                className={`form-control ${errors.login_password ? 'is-invalid' : ''}`}
                                                                placeholder="login password"
                                                            />
                                                            {errors.login_password && <div className="text-danger">{errors.login_password}</div>}
                                                        </div>
                                                        <div className="col-md-12" style={{ marginTop: "30px" }}>
                                                            <SubmitBtn text={this.state.user_id !== 0 ? 'Update' : 'Save'} type="primary" icon="ri-save-line" />
                                                            {this.state.user_id !== 0 &&
                                                                <button
                                                                    style={{ float: 'right' }}
                                                                    type="button"
                                                                    className="btn btn-light right btn-label"
                                                                    onClick={() => this.resetForm()}
                                                                >
                                                                    <i className=" ri-arrow-right-line label-icon align-middle fs-16 ms-2" /> New
                                                                </button>
                                                            }
                                                        </div>
                                                    </form>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div className="col-md-7">
                                    <div className='card'>
                                        <div className="col-md-12">
                                            <table className={`table table-bordered table-stripped`}>
                                                <thead className='table-light'>
                                                    <tr>
                                                        <th>User name</th>
                                                        <th>User login id</th>
                                                        <th>User login password</th>
                                                        <th className='text-center' width={120}>Action</th>
                                                    </tr>
                                                </thead>
                                                {this.state.rows.length !== 0 ? (
                                                    <tbody>
                                                        {this.state.rows.map((row) => (
                                                            <tr key={row.user_id}>
                                                                <td>{row.user_name}</td>
                                                                <td>{row.login_id}</td>
                                                                <td>{row.login_password}</td>
                                                                <td className='d-flex justify-content-around'>
                                                                    <button
                                                                        type='button'
                                                                        onClick={() => this.setState({ user_id: row.user_id }, () => this.GetInfo())}
                                                                        className="btn-icon btn btn-sm btn-outline-primary"
                                                                    >
                                                                        <i className="ri-edit-box-line"></i>
                                                                    </button>
                                                                    <button
                                                                        onClick={() => this.handleDelete(row.user_id)}
                                                                        className="btn-icon btn btn-sm btn-outline-danger"
                                                                    >
                                                                        <i className="ri-delete-bin-line"></i>
                                                                    </button>
                                                                </td>
                                                            </tr>
                                                        ))}
                                                    </tbody>
                                                ) : (
                                                    <tbody>
                                                        <tr>
                                                            <td colSpan="4">
                                                                <NoRecords />
                                                            </td>
                                                        </tr>
                                                    </tbody>
                                                )}
                                                <tfoot className='table-light'>
                                                    <tr>
                                                        <th colSpan={6} >
                                                            <div className="d-flex justify-content-between" >
                                                                <button disabled={this.state.prev === false && this.state.loadingList === false ? true : false} type="button" onClick={() => this.handlePrev()} className={`btn btn-warning btn-label waves-effect waves-light`}><i className="ri-arrow-left-line label-icon align-middle fs-16 me-2" /> Previous</button>
                                                                <div className='col-md-4' style={{ display: 'flex', alignItems: 'center' }}>
                                                                    {
                                                                        <small>Total Records: {this.state.total_records} | Total Pages: {this.state.total_pages} | Current Page: {this.state.page}</small>
                                                                    }
                                                                </div>
                                                                <div className='col-md-2'>
                                                                    <select className="form-select" onChange={(e) => this.handleChange(e)}>
                                                                        {Array.from({ length: this.state.total_pages }, (_, i) => (
                                                                            <option selected={this.state.page === i + 1} key={i} value={i + 1}>Page {i + 1}</option>
                                                                        ))}
                                                                    </select>
                                                                </div>
                                                                <button disabled={this.state.next === false && this.state.loadingList === false ? true : false} type="button" onClick={() => this.handleNext()} className={`btn btn-primary btn-label waves-effect right waves-light`}><i className="ri-arrow-right-line label-icon align-middle fs-16 ms-2" /> Next</button>
                                                            </div>
                                                        </th>
                                                    </tr>

                                                </tfoot>

                                            </table>
                                        </div>
                                    </div>

                                </div>
                            </div>
                        </div>) :
                        <ContentLoader />
                    }
                </div>
            </div>
        )
    };
}
export default withRouter(Users);