import React, { useContext, useEffect, useState } from 'react'
import { ContentLoader, NoRecords } from '../../Components/Shimmer';
import PageTitle from '../../Components/PageTitle';
import { ConfigContext } from '../../Context/ConfigContext';
import axios from 'axios';
import { NavLink } from 'react-router-dom';
import { handleDownloadOptions } from '../../Components/ExportData';
import Swal from 'sweetalert2';
const InspectionFormList = () => {
    const { apiHeaderJson, apiURL } = useContext(ConfigContext);
    const [inspectionFormData, setInspectionFormData] = useState([]);
    const [loadingList, setLoadingList] = useState(false);
    const [keyword, setKeyword] = useState()
    const [errors, setErrors] = 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 handleInputChange = (e, setStates) => {
        const { name, value } = e.target;
        setStates(value);
        if (errors[name]) {
            setErrors((prevErrors) => ({
                ...prevErrors,
                [name]: null,
            }));
        }

    };

    const getAllInspectionFormList = async () => {
        try {
            setLoadingList(true)
            const headers = apiHeaderJson;
            const response = await axios.get(`${apiURL}api/inspections/GetInspections`, { params: { page, limit }, headers })
            const { success, data } = response.data;
            console.log(data, "GetInspections");
            if (success === true) {
                setInspectionFormData(data)
                setNext(response.data.next);
                setPrev(response.data.prev);
                setPage(response.data.page);
                setTotalRecords(response.data.total_records);
                setTotalPages(response.data.total_pages);
                setLoadingList(false)
            }

        } catch (error) {
            console.log(error);

        }
        finally {
            setLoadingList(false)
        }
    }



    const deleteForm = async (id) => {
        const headers = apiHeaderJson;
        const confirm = await 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!'
        });

        if (confirm.isConfirmed) {
            try {
                const response = await axios.post(
                    `${apiURL}api/inspections/delete?inspection_id=${id}`,
                    // { params: { inspection_id :id} ,headers}
                );

                const { success } = response.data;
                if (success === true) {
                    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,
                    });
                    getAllInspectionFormList()

                }

            } catch (error) {
                console.error(error);
                Swal.fire(
                    'Error!',
                    'Something went wrong while deleting.',
                    'error'
                );
            }
        }
    };


    const updateForm = async (id) => {
        try {
            console.log(id, "iddd");
            const response = await axios.post(`${apiURL}api/inspections/question/update?inspection_question_id=${id}`);


        } catch (error) {
            console.log(error);

        }
    }


    const handleDownload = (downloadType) => {
        const endpoint = `api/inspections/GetInspections`;
        const params = {
            //   headers, 
            //     limit: totalRecords
            //     , page
        };

        const columns = [
            { header: "Inspection Title", width: 30 },
            { header: "Inspection Description", width: 35 },
        ];

        const mapRow = (data) => ({
            "Inspection Title": data?.inspection_title ?? "-",
            "Inspection Description": data?.inspection_description ?? "-",
        });

        handleDownloadOptions(endpoint, params, columns, mapRow, downloadType, apiURL, apiHeaderJson);
    };

    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));
    };

    useEffect(() => {
        getAllInspectionFormList()
    }, [page, limit])
    return (
        <div className="main-content">
            <div className="page-content">
                {
                    loadingList ? <ContentLoader /> :
                        <div className="container-fluid">
                            <br />
                            <PageTitle title={`Form List`} primary={`Home`} />
                            <div className="row">

                                <div className="col-md-12">
                                    <div className='card'>
                                        <div
                                            className='card-header align-items-center d-flex'
                                            style={{
                                                background: "#000000",
                                            }}>
                                            <h4 className='card-title mb-0 flex-grow-1 text-white'>Form List</h4>

                                            <div className='avatar-xs  flex-shrink-0'>
                                                <NavLink
                                                    to={'/InspectionForm'}
                                                    className='avatar-title bg-white rounded-circle fs-4'
                                                    style={{
                                                        color: "#184c8f",
                                                    }}>
                                                    <i className='ri-add-box-line'></i>
                                                </NavLink>
                                            </div>
                                        </div>
                                        <div className='card-body'>
                                            <div className='table-responsive table-card'>
                                                <table className={`table table-bordered table-striped table-hover mb-0`}>
                                                    <thead className='table-light'>
                                                        <tr>
                                                            <th className='text-center' width={380}>Inspection Title</th>
                                                            {/* <th className='text-center' width={180}>Inspection Category </th> */}
                                                            <th className='text-center'>Inspection Description</th>
                                                            <th className='text-center'>Type of Submittal</th>
                                                            <th className='text-center' width={100}>Action</th>
                                                        </tr>
                                                    </thead>
                                                    {inspectionFormData.length !== 0 ? (
                                                        <tbody>
                                                            {inspectionFormData.map((row) => (
                                                                <tr key={row.inspection_id}>

                                                                    <td className='text-center'>{row.inspection_title}</td>
                                                                    {/* <td className='text-center'>{row.category_name}</td> */}
                                                                    <td className='text-center'>{row.inspection_description}</td>
                                                                    <td className='text-center'>{row.type_of_submittal}</td>
                                                                    <td className='d-flex justify-content-around'>
                                                                        <NavLink to={`/InspectionForm/${row.inspection_id}`}>

                                                                            <button
                                                                                type='button'
                                                                                className="btn-icon btn btn-sm btn-outline-primary"
                                                                            >
                                                                                <i className="ri-edit-line"></i>
                                                                            </button>
                                                                        </NavLink>

                                                                        <button
                                                                            onClick={() => deleteForm(row.inspection_id)}
                                                                            type='button'
                                                                            className="btn-icon btn btn-sm btn-outline-danger"
                                                                        >
                                                                            <i className="ri-delete-bin-6-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}
                                                                                        selected={page === 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>
                        </div>

                }
            </div>
        </div>
    )
}

export default InspectionFormList