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

const TemplateItems = () => {

    const { apiURL, apiHeaderJson } = useContext(ConfigContext);
    const { requirement_id } = useParams()

    const [templateItemTitle, setTemplateItemTitle] = useState("")
    const [templateItemDescription, setTemplateItemDescription] = useState("")
    const [templateItemType, setTemplateItemType] = useState("")
    const [requirements_item_id, setReqItemId] = useState(0)

    const [rows, setRows] = useState([]);
    const [loadingList, setLoadingList] = useState(false);

    const [page, setPage] = useState(1);
    const [limit] = useState(10);
    const [totalRecords, setTotalRecords] = useState(0);
    const [totalPages, setTotalPages] = useState(0);
    const [next, setNext] = useState(false);
    const [prev, setPrev] = useState(false);

    const [errors, setErrors] = useState({});

    useEffect(() => {
        loadList();
    }, [page]);

    const loadList = async () => {
        try {
            setLoadingList(true);
            const headers = apiHeaderJson;

            const response = await axios.get(`${apiURL}api/requirements/items`, {
                params: { limit, page, requirement_id },
                headers,
            });

            if (response.data.success) {
                const data = response.data;
                setRows(data.data);
                setNext(data.next);
                setPrev(data.prev);
                setTotalRecords(data.total_records);
                setTotalPages(data.total_pages);
            }

        } catch (error) {
            console.log(error);
        } finally {
            setLoadingList(false);
        }
    };

    const GetInfo = async (id) => {
        try {
            const headers = apiHeaderJson;
            const response = await axios.get(`${apiURL}api/requirements/items?requirements_item_id =${id}`, { headers });

            if (response.data.success) {
                const d = response.data.data[0];
                setTemplateItemTitle(d.requirements_item_title);
                setTemplateItemDescription(d.requirements_item_description);
                setTemplateItemType(d.requirements_item_type);
                setReqItemId(d.requirements_item_id)
            }

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

    const validateForm = () => {
        const err = {};

        if (!templateItemTitle?.trim()) {
            err.templateItemTitle = "Please add Item title";
        }

        setErrors(err);
        return Object.keys(err).length > 0;
    };

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

        try {
            const headers = apiHeaderJson;

            const body = {
                requirements_item_title: templateItemTitle,
                requirements_item_description: templateItemDescription,
                requirements_item_type: templateItemType,
                requirement_id
            };

            if (requirements_item_id) {
                body.requirements_item_id = requirements_item_id
            }

            const url = `${apiURL}api/requirements/items`;

            const response = await axios.post(url, body, { headers });

            Swal.fire({
                title: `<strong>${response.data.success ? "Success" : "Failed"}</strong>`,
                text: requirements_item_id ? "Requirement Item Updated Successfully" : "New Requirement Item Added Successfully",
                icon: response.data.success ? "success" : "error",
                timer: 2000,
                showConfirmButton: false,
            });

            if (response.data.success) {
                resetForm();
                loadList();
            }

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

    const handleDelete = async (id) => {
        try {
            const result = await Swal.fire({
                title: "Are you sure?",
                text: "This action cannot be undone!",
                icon: "warning",
                showCancelButton: true,
                confirmButtonText: "Yes, delete it!",
            });

            if (result.isConfirmed) {
                const headers = apiHeaderJson;
                const response = await axios.delete(`${apiURL}api/requirements/items/${id}`, { headers });

                Swal.fire({
                    title: `<strong>${response.data.success ? "Success" : "Failed"}</strong>`,
                    text: response.data.message,
                    icon: response.data.success ? "success" : "error",
                    timer: 1000,
                    showConfirmButton: false,
                });

                if (response.data.success) loadList();
            }

        } catch (error) {
            Swal.fire("Error", error.message, "error");
        }
    };

    const resetForm = () => {
        setTemplateItemTitle("");
        setTemplateItemDescription("")
        setTemplateItemType("");
        setReqItemId(0)
        setErrors({});
    };

    const handlePrev = () => prev && setPage(page - 1);
    const handleNext = () => next && setPage(page + 1);

    return (
        <div className="main-content">
            <div className="page-content">

                {!loadingList ? (
                    <div className="container-fluid">
                        <PageTitle title="Add Template Item" primary="Home" />

                        <div className="row">
                            <div className="col-md-4">
                                <div className="card">
                                    <div className="card-header" style={{ backgroundColor: "#000000" }}>
                                        <h4 className="card-title flex-grow-1 text-white mb-0">Add Template Item</h4>
                                    </div>

                                    <div className="card-body">
                                        <form onSubmit={handleSubmit}>

                                            <div className="mt-3">
                                                <label>Template Item Title:</label>
                                                <input
                                                    type="text"
                                                    name="templateItemTitle"
                                                    value={templateItemTitle}
                                                    onChange={(e) => setTemplateItemTitle(e.target.value)}
                                                    className={`form-control ${errors.templateItemTitle ? "is-invalid" : ""}`}
                                                    placeholder="Please Enter Template item Title"
                                                />
                                                {errors.templateItemTitle && (
                                                    <small className="text-danger">{errors.templateItemTitle}</small>
                                                )}
                                            </div>

                                            <div className="mt-3">
                                                <label>Template Item Description:</label>
                                                <textarea
                                                    rows={3}
                                                    name="templateItemDescription"
                                                    value={templateItemDescription}
                                                    onChange={(e) => setTemplateItemDescription(e.target.value)}
                                                    className={`form-control`}
                                                    placeholder="Please Enter Template item description"
                                                />
                                            </div>
                                            <div className="mt-3">
                                                <label>Template Item Type:</label>
                                                <input
                                                    type='text'
                                                    name="templateItemType"
                                                    value={templateItemType}
                                                    onChange={(e) => setTemplateItemType(e.target.value)}
                                                    className={`form-control`}
                                                    placeholder="Please Enter Template item type"
                                                />
                                            </div>

                                            <div className="d-flex justify-content-between mt-4">

                                                {requirements_item_id ? (
                                                    <button type="button" onClick={resetForm} className="btn btn-light">
                                                        New
                                                    </button>
                                                ) : <div></div>}

                                                <SubmitBtn
                                                    text={requirements_item_id ? "Update" : "Save"}
                                                    icon="ri-save-line"
                                                    type="primary"
                                                />
                                            </div>

                                        </form>
                                    </div>
                                </div>
                            </div>

                            {/* ---------------------- TABLE ---------------------- */}
                            <div className="col-md-8">
                                <div className="card">
                                    <div className="card-header" style={{ backgroundColor: "#000000" }}>
                                        <h4 className="card-title text-white mb-0">Template Items List</h4>
                                    </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>ID</th>
                                                        <th>Template Item Title</th>
                                                        <th>Template Item Description</th>
                                                        <th>Template Item Type</th>
                                                        <th className="text-center">Action</th>
                                                    </tr>
                                                </thead>

                                                {rows.length !== 0 ? (
                                                    <tbody>
                                                        {rows.map((row) => (
                                                            <tr key={row.requirements_item_id }>
                                                                <td>{row.requirements_item_id }</td>
                                                                <td>{row.requirements_item_title}</td>
                                                                <td>{row.requirements_item_description}</td>
                                                                <td>{row.requirements_item_type}</td>

                                                                <td className="text-center">
                                                                    <button
                                                                        onClick={() => GetInfo(row.requirements_item_id )}
                                                                        className="btn btn-sm btn-outline-primary me-1"
                                                                    >
                                                                        <i className="ri-edit-box-line"></i>
                                                                    </button>

                                                                    <button
                                                                        onClick={() => handleDelete(row.requirements_item_id )}
                                                                        className="btn btn-sm btn-outline-danger"
                                                                    >
                                                                        <i className="ri-delete-bin-line"></i>
                                                                    </button>
                                                                </td>
                                                            </tr>
                                                        ))}
                                                    </tbody>
                                                ) : (
                                                    <tbody>
                                                        <tr>
                                                            <td colSpan="10"><NoRecords /></td>
                                                        </tr>
                                                    </tbody>
                                                )}

                                                <tfoot className="table-light">
                                                    <tr>
                                                        <td colSpan={10}>
                                                            <div className="d-flex justify-content-between align-items-center">

                                                                <button
                                                                    disabled={!prev}
                                                                    onClick={handlePrev}
                                                                    className="btn btn-warning"
                                                                >
                                                                    Previous
                                                                </button>

                                                                <small>
                                                                    Total Records: {totalRecords} |
                                                                    Pages: {totalPages} |
                                                                    Current Page: {page}
                                                                </small>

                                                                <div className="col-md-2">
                                                                    <select className="form-select" onChange={(e) => setPage(Number(e.target.value))}>
                                                                        {Array.from({ length: totalPages }, (_, i) => (
                                                                            <option key={i + 1} value={i + 1}>{i + 1}</option>
                                                                        ))}
                                                                    </select>
                                                                </div>

                                                                <button
                                                                    disabled={!next}
                                                                    onClick={handleNext}
                                                                    className="btn btn-primary"
                                                                >
                                                                    Next
                                                                </button>

                                                            </div>
                                                        </td>
                                                    </tr>
                                                </tfoot>

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

                        </div>
                    </div>
                ) : (
                    <ContentLoader />
                )}
            </div>
        </div>
    );
};

export default TemplateItems;