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 { Link } from 'react-router-dom';

const RequestTamplate = () => {

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

    const [templateTitle, setTemplateTitle] = useState("")
    const [templateDescription, setTemplateDescription] = useState("")
    const [requirement_id, setRequirementId] = useState("")

    const [docTitle, setDocTitle] = useState("");
    const [documents, setDocuments] = useState([]);

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

    const addDocument = () => {
        if (!docTitle.trim()) return;

        setDocuments([
            ...documents,
            {
                document_title: docTitle.trim()
            }
        ]);

        setDocTitle("");
    };

    const removeDocument = (index) => {
        setDocuments(documents.filter((_, i) => i !== index));
    };

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

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

            const response = await axios.get(`${apiURL}api/requirements`, {
                params: { limit, page },
                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?requirement_id=${id}`, { headers });

            if (response.data.success) {
                const d = response.data.data[0];
                setRequirementId(d.requirement_id);
                setTemplateTitle(d.requirement_title);
                setTemplateDescription(d.requirement_description);
            }

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

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

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

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

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

        try {
            const headers = apiHeaderJson;

            const body = {
                requirement_title: templateTitle,
                requirement_description: templateDescription
            };

            if (requirement_id) {
                body.requirement_id = requirement_id
            }

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

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

            Swal.fire({
                title: `<strong>${response.data.success ? "Success" : "Failed"}</strong>`,
                text: requirement_id ? "Requirement Updated Successfully" : "New Requirement 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/${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 = () => {
        setTemplateTitle("");
        setTemplateDescription("")
        setDocuments([]);
        setDocTitle("");
        setRequirementId(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" 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</h4>
                                    </div>

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

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

                                            <div className="mt-3">
                                                <label>Template Description:</label>
                                                <textarea
                                                    rows={3}
                                                    name="templateDescription"
                                                    value={templateDescription}
                                                    onChange={(e) => setTemplateDescription(e.target.value)}
                                                    className={`form-control`}
                                                    placeholder="Please Enter Template description"
                                                />
                                            </div>
                                            <div className="d-flex justify-content-between mt-4">

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

                                                <SubmitBtn
                                                    text={requirement_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">Templates 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 Title</th>
                                                        <th>Template Description</th>
                                                        <th className="text-center">Action</th>
                                                    </tr>
                                                </thead>

                                                {rows.length !== 0 ? (
                                                    <tbody>
                                                        {rows.map((row) => (
                                                            <tr key={row.requirement_id}>
                                                                <td>{row.requirement_id}</td>
                                                                <td>{row.requirement_title}</td>
                                                                <td>{row.requirement_description}</td>

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

                                                                    <button
                                                                        onClick={() => handleDelete(row.requirement_id)}
                                                                        className="btn btn-sm btn-outline-danger me-1"
                                                                    >
                                                                        <i className="ri-delete-bin-line"></i>
                                                                    </button>
                                                                    <Link
                                                                        to={`/TemplateItems/${row.requirement_id}`}
                                                                        className='btn btn-outline-secondary btn-sm'
                                                                    >
                                                                        Items
                                                                    </Link>
                                                                </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 RequestTamplate;
