
import React, { useState, useEffect, useContext } from 'react';
import PageTitle from "../../Components/PageTitle";
import { SubmitBtn } from "../../Components/InputElements";
import Select from 'react-select';
import axios from 'axios';
import Swal from 'sweetalert2';
import withRouter from '../../Utils/withRouter';
import { ConfigContext } from '../../Context/ConfigContext';
import { ContentLoader, NoRecords } from "../../Components/Shimmer";

const Modilds = () => {
    const { apiURL, apiHeaderJson } = useContext(ConfigContext)
    const [company_module_id, setcompany_module_id] = useState(0)
    const [company_id, setcompany_id] = useState(0)
    const [module, setModule] = useState(0);
    const [moduleStatus, setModuleStatus] = useState('1');
    const [rows, setRows] = useState([]);
    const [companies, setCompanies] = useState([]);
    const [next, setNext] = useState(false);
    const [prev, setPrev] = useState(false);
    const [page, setPage] = useState(1);
    const [limit] = useState(10);
    const [totalRecords, setTotalRecords] = useState(0);
    const [totalPages, setTotalPages] = useState(0);
    const [loadingList, setLoadingList] = useState(false);
    const [postLoading, setPostLoading] = useState(false);
    const [errors, setErrors] = useState({});

    useEffect(() => {
        setLoadingList(true);
        GetList();
        GetCompaniesList();
    }, [page]);


    const handleInputChange = (e) => {
        const { name, value } = e.target;
        setErrors((prevErrors) => {
            const updatedErrors = { ...prevErrors };
            delete updatedErrors[name];
            return updatedErrors;
        });

        switch (name) {
            case 'company_id':
                setcompany_id(value);
                break;
            case 'module':
                setModule(value);
                break;
            default:
                break;
        }
    };


    const handleSelectChange = (name, selectedOption) => {
        setErrors((prevErrors) => ({
            ...prevErrors,
            [name]: '',
        }));

        if (name === 'company_id') setcompany_id(selectedOption.value);
        if (name === 'module') setModule(selectedOption.value);
    };

    const handleRadioChange = (name, value) => {
        setErrors((prevErrors) => ({
            ...prevErrors,
            [name]: '',
        }));

        if (name === 'module_status') setModuleStatus(value);
    };

    const GetInfo = () => {
        const headers = apiHeaderJson;
        axios
            .get(`${apiURL}CompanyMasters/GetCompanyModildInfo`, {
                params: { company_module_id: company_module_id },
                headers,
            })
            .then((response) => {
                const { data, success } = response.data;
                if (success) {
                    resetForm();
                    setcompany_module_id(data[0].company_module_id);
                    setModule(data[0].module);
                    setcompany_id(data[0].company_id);
                    setModuleStatus(data[0].module_status);
                }
            });
    };

    const GetList = () => {
        const headers = apiHeaderJson;
        axios
            .get(`${apiURL}CompanyMasters/GetCompanyModilds`, {
                params: { limit, page },
                headers,
            })
            .then((response) => {
                const data = response.data;
                if (data.success) {
                    setRows(data.data);
                    setNext(data.next);
                    setPrev(data.prev);
                    setPage(data.page);
                    setTotalRecords(data.total_records);
                    setTotalPages(data.total_pages);
                }
                setLoadingList(false);
            });
    };

    const GetCompaniesList = () => {
        const headers = apiHeaderJson;
        axios
            .get(`${apiURL}CompanyMasters/GetCompaniesList`, { headers })
            .then((response) => {
                const data = response.data;
                if (data.success) {
                    setCompanies(
                        data.data.map((row) => ({
                            value: row.company_id,
                            label: row.company_name,
                        }))
                    );
                }
            });
    };

    const validateForm = () => {
        const errors = {};
        if (company_id === 0) errors.company_id = 'Company is required';
        if (module === 0) errors.module = 'Module is required';
        setErrors(errors);
        return Object.keys(errors).length === 0;
    };

    const handleSubmit = (e) => {
        e.preventDefault();
        if (!validateForm()) return;

        const headers = apiHeaderJson;
        const formData = {
            module,
            module_status: moduleStatus,
            company_id: company_id,
        };
        if (company_module_id !== 0) formData.company_module_id = company_module_id;

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

                if (success) {
                    resetForm();
                    setLoadingList(true);
                    GetList();
                } else {
                    setLoadingList(true);
                    GetList();
                }
            });
    };

    const resetForm = () => {
        setErrors({});
        setcompany_module_id(0);
        setModuleStatus('1');
        setModule(0);
        setcompany_id(0);
    };

    const handleDelete = (id) => {
        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) {
                axios
                    .post(`${apiURL}CompanyMasters/DeleteCompanyModilds`, { company_module_id: id }, { headers })
                    .then((response) => {
                        Swal.fire({
                            title: `<strong>${response.data.success ? 'Success' : 'Failed'}</strong>`,
                            text: response.data.message,
                            icon: response.data.success ? 'success' : 'error',
                            timer: 1000,
                            timerProgressBar: true,
                            showConfirmButton: false,
                        });

                        if (response.data.success) {
                            setLoadingList(true);
                            GetList();
                        }
                    })
                    .catch((error) => {
                        Swal.fire({
                            title: <strong>Error</strong>,
                            html: error,
                            icon: 'error',
                        });
                    });
            }
        });
    };

    const handlePrev = () => {
        if (prev) {
            setPage((prevPage) => prevPage - 1);
        }
    };

    const handleNext = () => {
        if (next) {
            setPage((prevPage) => prevPage + 1);
        }
    };

    const handleChange = (e) => {
        setPage(parseInt(e.target.value, 10));
    };

    const options = [
        { value: 'leaves', label: 'Leaves' },
        { value: 'attendance', label: 'Attendance' },
        { value: 'salary_details', label: 'Salary details' },
        { value: 'documents', label: 'Documents' },
        { value: 'payslip', label: 'Payslip' },
    ];

    return (
        <div className="main-content">
            <div className="page-content">
                {loadingList === false ? (
                    <div className="container-fluid">
                        <br />
                        <PageTitle title={`Module 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">Module Management</h4>
                                    </div>
                                    <div className="card-body">
                                        <div className="row gy-4">
                                            <div className="col-md-12">
                                                <form onSubmit={handleSubmit} className="row">
                                                    <div className="col-md-12">
                                                        <label for="company_name">Select company</label>
                                                        <Select
                                                            options={companies}
                                                            value={companies ? companies.find(option => option.value === companies) : null}
                                                            onChange={(selectedOption) => handleSelectChange('company_id', selectedOption)}
                                                            name='company_id'
                                                            placeholder={`Select company`}
                                                        />
                                                        {errors.company_id && <div className="text-danger">{errors.company_id}</div>}
                                                    </div>

                                                    <div className="col-md-12" style={{ marginTop: "10px" }}>
                                                        <label for="module">Select module</label>
                                                        <Select
                                                            options={options}
                                                            value={options ? options.find(option => option.value === module) : null}
                                                            onChange={(selectedOption) => handleSelectChange('module', selectedOption)}
                                                            name='module'
                                                            placeholder={`Select module`}
                                                        />
                                                        {errors.module && <div className="text-danger">{errors.module}</div>}
                                                    </div>
                                                    <div className="col-md-6 mt-3">
                                                        <div>
                                                            <label htmlFor="module_status0" className="form-label">Hide module:</label>
                                                        </div>
                                                        <div className="form-check form-check-inline mt-2" >
                                                            <input
                                                                type="radio"
                                                                id="module_status0"
                                                                name="module_status"
                                                                value="0"
                                                                // checked={module_status == '0'}
                                                                onChange={() => handleRadioChange('module_status', '0')}
                                                                className={`form-check-input`}
                                                            />
                                                            <label htmlFor="module_status0" className="form-check-label">Yes</label>
                                                        </div>
                                                        <div className="form-check form-check-inline">
                                                            <input
                                                                type="radio"
                                                                id="module_status1"
                                                                name="module_status"
                                                                value="0"
                                                                // checked={module_status == '1'}
                                                                onChange={() => handleRadioChange('module_status', '1')}
                                                                className={`form-check-input`}
                                                            />
                                                            <label htmlFor="module_status1" className="form-check-label">No</label>
                                                        </div>
                                                    </div>
                                                    <div className="col-md-12" style={{ marginTop: "30px" }}>
                                                        {
                                                            // <SubmitBtn text={company_module_id !== 0 ? 'Update' : 'Save'} type="primary" icon="ri-save-line" />

                                                            company_module_id !== 0 ?
                                                                <SubmitBtn icon={`ri-save-line`} text={`Update`} type={`primary`} /> :
                                                                <SubmitBtn text={`Save`} type={`primary`} icon={`ri-save-line`} />
                                                        }
                                                        {
                                                            company_module_id ? <button style={{ float: 'right' }} type="button" className={`btn btn-light right btn-label`} onClick={resetForm} ><i className={` ri-arrow-right-line label-icon align-middle fs-16 ms-2`} />New</button> : <div></div>

                                                        }
                                                    </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>Company name</th>
                                                    <th>Modilds</th>
                                                    <th>Hide modilds status</th>
                                                    <th className='text-center' width={120}>Action</th>
                                                </tr>
                                            </thead>
                                            {rows.length !== 0 ? (
                                                <tbody>
                                                    {rows.map((row) => (
                                                        <tr key={row.company_module_id}>
                                                            <td>{row.company_name}</td>
                                                            <td>{row.module}</td>
                                                            <td>{row.module_status_label}</td>
                                                            <td className='d-flex justify-content-around'>
                                                                <button
                                                                    type='button'
                                                                    onClick={() => GetInfo(row.company_module_id)}
                                                                    className="btn-icon btn btn-sm btn-outline-primary"
                                                                >
                                                                    <i className="ri-edit-box-line"></i>
                                                                </button>
                                                                <button
                                                                    onClick={() => handleDelete(row.company_module_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={prev === false && loadingList === false ? true : false} type="button" onClick={() => 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: {totalRecords} | Total Pages: {totalPages} | Current Page: {page}</small>
                                                                }
                                                            </div>
                                                            <div className='col-md-2'>
                                                                <select className="form-select" onChange={(e) => handleChange(e)}>
                                                                    {Array.from({ length: totalPages }, (_, i) => (
                                                                        <option key={i + 1} value={i + 1}>
                                                                            {i + 1}
                                                                        </option>
                                                                    ))}
                                                                </select>
                                                            </div>
                                                            <button disabled={next === false && loadingList === false ? true : false} type="button" onClick={() => 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(Modilds);