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 DocumentRequest = () => {

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

    const [projectRow, setProjectRow] = useState([]);
    const [profileRow, setProfileRow] = useState([]);
    const [reqRow, setReqRow] = useState([]);
    const [selectedProject, setSelectedProject] = useState(null);
    const [selectedProfile, setSelectedProfile] = useState(null);
    const [selectedRequirement, setSelectedRequirement] = useState(null);
    const [selectedType, setSelectedType] = useState(null);
    const [reqRemark, setReqRemark] = useState("");
    const [errors, setErrors] = useState({});
    const [showModal, setShowModal] = useState(false);
    const [selectedRequestId, setSelectedRequestId] = useState(null);
    const [approvalRemark, setApprovalRemark] = useState("");
    const [allProfiles, setAllProfiles] = 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 profileTypeOptions = [
        { value: "consultant", label: "Consultant", filter_value: 2 },
        { value: "contractor", label: "Contractor", filter_value: 1 },
        { value: "client", label: "Client", filter_value: 3 },
    ]

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

        if (!selectedRequirement) {
            err.selectedRequirement = "Please select template";
        }
        if (!selectedType) {
            err.selectedType = "Please select profile type";
        }
        if (!selectedProfile) {
            err.selectedProfile = "Please select profile";
        }

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

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

            if (response.data.success) {
                const options = response.data.data.map((item) => ({
                    value: item.requirement_id,
                    label: item.requirement_title
                }));
                setReqRow(options)
            }

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

    const GetProjects = async () => {
        try {
            const response = await axios.get(`${apiURL}api/projects`);
            const { success, data } = response.data;

            if (success) {
                setProjectRow(
                    data.map((row) => ({
                        value: row.project_id,
                        label: row.project_title,
                    }))
                );
            }
        } catch (error) {
            console.log(error);
        }
    };

    const GetAllProfiles = async () => {
        try {
            const response = await axios.get(`${apiURL}api/profiles`);
            const { success, data } = response.data;

            if (success) {
                setAllProfiles(
                    data.map(row => ({
                        value: row.profile_id,
                        label: `${row.profile_name} -- ${row.pc_category_title}`
                    }))
                );
            }
        } catch (err) {
            console.log(err);
        }
    };

    const GetProfiles = async () => {
        try {
            const response = await axios.get(`${apiURL}api/profiles`, { params: { profile_type: getProfileFilter() } });
            const { data, success } = response.data;
            if (success === true) {
                setProfileRow(
                    data.map((row) => ({
                        value: row.profile_id,
                        label: `${row.profile_name} -- ${row.pc_category_title}`,
                    }))
                );
            }
        } catch (error) {
            console.log(error);
        }
    };

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

            const response = await axios.get(`${apiURL}api/requirements/requests`, {
                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 handleSubmit = async (e) => {
        e.preventDefault();
        if (validateForm()) return;

        try {
            const headers = apiHeaderJson;

            const body = {
                requirement_id: selectedRequirement,
                profile_type: selectedType,
                profile_id: selectedProfile,
                project_id: selectedProject,
                requirements_request_status: 1,
                requirements_request_remark: reqRemark
            };

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

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

            Swal.fire({
                title: `<strong>${response.data.success ? "Success" : "Failed"}</strong>`,
                text: "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/requests/${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 openApproveModal = (id) => {
        setSelectedRequestId(id);
        setApprovalRemark("");
        setShowModal(true);
    };

    const closeApproveModal = () => {
        setShowModal(false);
        setSelectedRequestId(null);
        setApprovalRemark("");
    };

    const approveRequest = async () => {
        if (!approvalRemark.trim()) {
            Swal.fire("Remark Required", "Please enter approval remark.", "warning");
            return;
        }

        try {
            const headers = apiHeaderJson;

            const response = await axios.post(
                `${apiURL}api/requirements/requests/${selectedRequestId}`,
                {
                    requirements_request_status: 2,
                    requirements_request_remark: approvalRemark
                },
                { headers }
            );

            Swal.fire({
                title: response.data.success ? "Success" : "Failed",
                text: response.data.message,
                icon: response.data.success ? "success" : "error",
                timer: 1500,
                showConfirmButton: false,
            });

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

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

    const resetForm = () => {
        setSelectedRequirement(null)
        setSelectedProfile(null)
        setSelectedType(null)
        setSelectedProject(null)
        setReqRemark("")
        setErrors({});
    };

    const copyRequestLink = async (token) => {
        const link = `${window.location.origin}/RequestForm/${token}`;

        try {
            await navigator.clipboard.writeText(link);

            Swal.fire({
                icon: "success",
                title: "Copied!",
                text: "Request link copied to clipboard.",
                timer: 1500,
                showConfirmButton: false,
            });
        } catch (err) {
            Swal.fire("Error", "Unable to copy link.", "error");
        }
    };

    const shareRequestLink = async (token) => {
        const link = `${window.location.origin}/RequestForm/${token}`;

        if (navigator.share) {
            try {
                await navigator.share({
                    title: "Document Request",
                    text: "Please complete the document request.",
                    url: link,
                });
            } catch (err) {
                console.log(err);
            }
        } else {
            copyRequestLink(token);
        }
    };

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

    const getRequirementTitle = (id) => {
        return reqRow.find(x => x.value === id)?.label || "-";
    };

    const getProfileTitle = (id) => {
        return allProfiles.find(x => x.value === id)?.label || "-";
    };

    const getProfileFilter = () => {
        return (
            profileTypeOptions.find(x => x.value === selectedType)?.filter_value ?? null
        );
    };

    const getProjectTitle = (id) => {
        return projectRow.find(x => x.value === id)?.label || "-";
    };

    useEffect(() => {
        GetProjects();
        GetRequirements();
        GetAllProfiles();
    }, []);

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

    useEffect(() => {
        if (selectedType) {
            GetProfiles();
        } else {
            setProfileRow([]);
            setSelectedProfile(null);
        }
    }, [selectedType]);

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

                    {!loadingList ? (
                        <div className="container-fluid">
                            <PageTitle title="Add Request" 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 Request</h4>
                                        </div>

                                        <div className="card-body">
                                            <form onSubmit={handleSubmit}>
                                                <div className="mb-3">
                                                    <label>Tamplete :</label>
                                                    <Select
                                                        options={reqRow}
                                                        placeholder="Select Tamplete"
                                                        value={
                                                            selectedRequirement
                                                                ? reqRow.find(
                                                                    (option) => option.value === selectedRequirement
                                                                )
                                                                : null
                                                        }
                                                        onChange={(option) =>
                                                            setSelectedRequirement(option ? option.value : null)
                                                        }
                                                    />
                                                    {errors.selectedRequirement && (
                                                        <small className="text-danger">{errors.selectedRequirement}</small>
                                                    )}
                                                </div>
                                                <div className="mb-3">
                                                    <label>Profile Type :</label>
                                                    <Select
                                                        options={profileTypeOptions}
                                                        placeholder="Select Profile Type"
                                                        value={
                                                            selectedType
                                                                ? profileTypeOptions.find(
                                                                    (option) => option.value === selectedType
                                                                )
                                                                : null
                                                        }
                                                        onChange={(option) =>
                                                            setSelectedType(option ? option.value : null)
                                                        }
                                                    />
                                                    {errors.selectedType && (
                                                        <small className="text-danger">{errors.selectedType}</small>
                                                    )}
                                                </div>
                                                <div className="mb-3">
                                                    <label>Profile :</label>
                                                    <Select
                                                        options={profileRow}
                                                        placeholder="Select Profile"
                                                        value={
                                                            selectedProfile
                                                                ? profileRow.find(
                                                                    (option) => option.value === selectedProfile
                                                                )
                                                                : null
                                                        }
                                                        onChange={(option) =>
                                                            setSelectedProfile(option ? option.value : null)
                                                        }
                                                    />
                                                    {errors.selectedProfile && (
                                                        <small className="text-danger">{errors.selectedProfile}</small>
                                                    )}
                                                </div>
                                                <div className="mb-3">
                                                    <label>Project (optional) :</label>
                                                    <Select
                                                        options={projectRow}
                                                        placeholder="Select Project"
                                                        value={
                                                            selectedProject
                                                                ? projectRow.find(
                                                                    (option) => option.value === selectedProject
                                                                )
                                                                : null
                                                        }
                                                        onChange={(option) =>
                                                            setSelectedProject(option ? option.value : null)
                                                        }
                                                    />
                                                </div>

                                                <div>
                                                    <label>Remark (optional) :</label>
                                                    <textarea
                                                        rows={3}
                                                        name="reqRemark"
                                                        value={reqRemark}
                                                        onChange={(e) => setReqRemark(e.target.value)}
                                                        className={`form-control`}
                                                        placeholder="Please Enter request remark"
                                                    />
                                                </div>

                                                <div className="d-flex justify-content-between mt-4">
                                                    <SubmitBtn
                                                        text={"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">Requests List</h4>
                                        </div>

                                        <div className="card-body">
                                            <div className='table-responsive table-card'>
                                                <table className="table table-bordered table-striped table-hover table-nowrap mb-0">
                                                    <thead className="table-light">
                                                        <tr>
                                                            <th>ID</th>
                                                            <th>Requirement</th>
                                                            <th>Profile Type</th>
                                                            <th>Profile</th>
                                                            <th>Project</th>
                                                            <th>Status</th>
                                                            <th className="text-center">Action</th>
                                                        </tr>
                                                    </thead>

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

                                                                    <td>
                                                                        <span className="badge bg-info text-capitalize">
                                                                            {row.profile_type}
                                                                        </span>
                                                                    </td>

                                                                    <td>{getProfileTitle(row.profile_id)}</td>

                                                                    <td>{getProjectTitle(row.project_id)}</td>
                                                                    <td>{
                                                                        row.requirements_request_status === 1 ?
                                                                            <span className='badge bg-warning'>Pending</span> :
                                                                            <span className='badge bg-success'>Aproved</span>
                                                                    }
                                                                    </td>

                                                                    <td className="text-center">

                                                                        {row.requirements_request_status === 1 && (
                                                                            <>


                                                                                <button
                                                                                    className="btn btn-sm btn-success me-2"
                                                                                    onClick={() => openApproveModal(row.requirements_request_id)}
                                                                                    title="Approve"
                                                                                >
                                                                                    <i className="ri-check-line"></i>
                                                                                </button>


                                                                                <button
                                                                                    className="btn btn-sm btn-info me-2"
                                                                                    title="Copy Link"
                                                                                    onClick={() => copyRequestLink(row.unique_access_token)}
                                                                                >
                                                                                    <i className="ri-file-copy-line"></i>
                                                                                </button>

                                                                                <button
                                                                                    className="btn btn-sm btn-primary me-2"
                                                                                    title="Share Link"
                                                                                    onClick={() => shareRequestLink(row.unique_access_token)}
                                                                                >
                                                                                    <i className="ri-share-forward-line"></i>
                                                                                </button>


                                                                                <button
                                                                                    onClick={() => handleDelete(row.requirements_request_id)}
                                                                                    className="btn btn-sm btn-danger me-2"
                                                                                    title="Delete"
                                                                                >
                                                                                    <i className="ri-delete-bin-line"></i>
                                                                                </button>
                                                                            </>
                                                                        )}
                                                                        <Link
                                                                            className='btn btn-sm btn-secondary'
                                                                            to={`/RequestItems/${row.requirements_request_id}`}
                                                                        >
                                                                            <i className="ri-file-line"></i>
                                                                        </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>
            {showModal && (
                <>
                    <div
                        className="modal fade show"
                        style={{ display: "block", background: "rgba(0,0,0,.5)" }}
                    >
                        <div className="modal-dialog modal-dialog-centered">
                            <div className="modal-content">

                                <div className="modal-header">
                                    <h5 className="modal-title">
                                        Approve Request
                                    </h5>

                                    <button
                                        type="button"
                                        className="btn-close"
                                        onClick={closeApproveModal}
                                    ></button>
                                </div>

                                <div className="modal-body">

                                    <label className="form-label">
                                        Approval Remark
                                    </label>

                                    <textarea
                                        rows={4}
                                        className="form-control"
                                        placeholder="Enter approval remark..."
                                        value={approvalRemark}
                                        onChange={(e) =>
                                            setApprovalRemark(e.target.value)
                                        }
                                    />

                                </div>

                                <div className="modal-footer">

                                    <button
                                        className="btn btn-secondary"
                                        onClick={closeApproveModal}
                                    >
                                        Cancel
                                    </button>

                                    <button
                                        className="btn btn-success"
                                        onClick={approveRequest}
                                    >
                                        <i className="ri-check-line me-1"></i>
                                        Approve
                                    </button>

                                </div>

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

                    <div className="modal-backdrop fade show"></div>
                </>
            )}
        </>
    )
}

export default DocumentRequest