import React, { useState, useEffect, useContext, useCallback } from "react";
import PageTitle from "../../Components/PageTitle";

import axios from "axios";
import Swal from "sweetalert2";
import { ConfigContext } from "../../Context/ConfigContext";
import { ContentLoader, NoRecords } from "../../Components/Shimmer";
import { useDropzone } from "react-dropzone";
import Select from "react-select";
import { NavLink, useParams } from "react-router-dom";
import Flatpickr from 'react-flatpickr';
import 'flatpickr/dist/themes/material_blue.css';
import { formatDate } from "../../Components/GlobalFunctions";
import { handleDownloadOptions } from "../../Components/ExportData";


const RequestList = ({ customStyles }) => {
    const { apiURL, apiHeaderJson, apiHeaderFile, user_id } = useContext(ConfigContext);
    const { project_id } = useParams();
    const [rows, setRows] = 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 [errors, setErrors] = useState({});
    const [keyword, setKeyword] = useState("");
    const [reload, setReload] = useState(false)
    const [projectItemsInfo, setProjectItemsInfo] = useState({});
    const [consultantInfo, setConsultantInfo] = useState([]);
    const [attachments, setAttachments] = useState([])
    const [selectOption, setSelectOption] = useState(null);
    const [dateRange, setDateRange] = useState([null, null])

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

    const parseItemLogs = (logsString) => {
        try {
            if (!logsString) return [];
            return JSON.parse(logsString);
        } catch (error) {
            console.error('Error parsing item logs:', error);
            return [];
        }
    };

    const GetInfo = (row) => {
        const headers = apiHeaderJson;
        axios
            .get(`${apiURL}api/requests/GetProjectRequestInfo?project_request_id=${row?.project_request_id}`, {
                headers,
            })
            .then((response) => {
                const { data, success } = response.data;

                if (success) {
                    setProjectItemsInfo(data.info)
                    setConsultantInfo(data.consultants)
                    setAttachments(data.attachments)
                }
            });
    };

    const handleInputChange = (e, setStates) => {
        const { name, value } = e.target;
        setStates(value);
        if (errors[name]) {
            setErrors((prevErrors) => ({
                ...prevErrors,
                [name]: null,
            }));
        }

    };

    const GetList = async () => {
        try {
            const headers = apiHeaderJson;
            const response = await axios.get(`${apiURL}api/requests/GetProjectRequests`, {
                params: { project_id, page, limit },
                headers,
            })

            const { data, success } = response.data;
            if (success === true) {

                setRows(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);
            setLoadingList(false);
        }
    };

    const handleChangeItemInfo = (value, field) => {
        setProjectItemsInfo(prev => ({
            ...prev,
            [field]: value
        }))
    }

    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 handleStatus = async () => {
        const { item_id, pi_item_price, pi_item_qty, project_id, project_item_id } = projectItemsInfo
        const headers = apiHeaderJson;
        const body = {
            project_item_id,
            pi_item_id: item_id,
            pi_item_price,
            pi_item_qty,
            pi_project_id: project_id,
            pi_approved_by: localStorage.getItem('user_id'),
            pi_approved_date: formatDate(),
            pi_status: '1',
        }

        try {
            const response = await axios.patch(`${apiURL}api/project-items/status/${project_item_id}`, body, { headers })

            if (response.status === 200) {
                document.getElementById('btn-close-modal').click();
                Swal.fire({
                    icon: 'success',
                    title: 'Request Approved Successfully',
                    showConfirmButton: false,
                    timer: 1500
                });
                GetList();
                setProjectItemsInfo({});
            }
        } catch (error) {
            Swal.fire({
                icon: 'error',
                title: 'Error',
                showConfirmButton: false,
                timer: 1500
            });
        }

    };


    const handleRejectStatus = async (row) => {
        const { item_id, pi_item_price, pi_item_qty, project_id, project_item_id } = row;
        const headers = apiHeaderJson;
        const body = {
            project_item_id,
            pi_item_id: item_id,
            pi_item_price,
            pi_item_qty,
            pi_project_id: project_id,
            pi_approved_by: localStorage.getItem('user_id'),
            pi_approved_date: formatDate(),
            pi_status: '2',
        }
        try {
            console.log(body);
            const response = await axios.patch(`${apiURL}api/project-items/status/${project_item_id}`, body, { headers })

            if (response.status === 200) {
                Swal.fire({
                    icon: 'success',
                    title: 'Request Rejected Successfully',
                    showConfirmButton: false,
                    timer: 1500
                });

                GetList();
                setProjectItemsInfo({})
            }
        } catch (error) {
            Swal.fire({
                icon: 'error',
                title: 'Error',
                showConfirmButton: false,
                timer: 1500
            });
        }

    };


    const options = [
        { value: '0', label: "Pending" },
        { value: '1', label: 'Approved' },
        { value: '2', label: 'Rejected' }
    ];

    const handleSelectStatus = (selectedOption) => {
        setSelectOption(selectedOption ? selectedOption.value : '');
    };

    const handleInputSearch = () => {
        setPage(1);
        setReload(true);
    };

    const handleClearAll = () => {
        setKeyword('');
        setSelectOption(null);

    };

    const ClearModal = () => {

    }

    const handleDownload = (downloadType) => {
        const endpoint = `api/requests/GetProjectRequests`;
        const params = {
            project_id,
            limit: totalRecords
            , page
        };

        const columns = [
            { header: "Item Name", width: 26 },
            { header: "Submittal Description", width: 26 },
            { header: "Description", width: 30 },
            { header: " Requested By", width: 20 },
            { header: " Status", width: 25 },
        ];

        const mapRow = (data) => ({
            "Item Name": data?.item_name ?? "-",
            "Submittal Description": data?.submittal_description ?? "-",
            "Description": (data?.request_brief_description) ?? "-",
            " Requested By": (data?.profile_name) ?? "-",
            " Status": GetStatus(data?.request_status) ?? "-",
        });

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


    const GetStatus = (status) => {
        if (status == '0') {
            return "Pending"
        } else if (status == '1') {
            return "Approved"
        } else if (status == '2') {
            return "Revise"
        } else if (status == '3') {
            return "Rejected"
        } else if (status == '4') {
            return "In-Clearence"
        }
    }

    const GetBadge = (status) => {
        if (status == '0') {
            return "badge bg-warning-subtle text-warning"
        } else if (status == '1') {
            return "badge bg-success-subtle text-success"
        } else if (status == '2') {
            return "badge bg-info-subtle text-info"
        } else if (status == '3') {
            return "badge bg-danger-subtle text-danger"
        } else if (status == '4') {
            return "badge bg-secondary-subtle text-secondary"
        }

    }

    const GetProgress = (totalQty = 0, items = []) => {
        if (!Array.isArray(items) || totalQty <= 0) return [];

        let itemUsedQty = 0;

        return items.map(item => {
            const receivedQty = Number(item.project_item_received_qty) || 0;
            itemUsedQty += receivedQty;

            const progress = +((itemUsedQty / totalQty) * 100).toFixed(2);

            return {
                ...item,
                progress
            };
        });
    };

    useEffect(() => {
        reload && GetList()
    }, [reload, page])

    return (
        <div className="main-content">
            <div className="page-content">
                {loadingList === false ? (
                    <div className="container-fluid">
                        <br />
                        <PageTitle title={`Request 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'>Request List</h4>
                                        <div className="col-md-3 mx-3">
                                            <div className="row">
                                                <div className="col-md-5"></div>
                                            </div>
                                        </div>

                                        <div className='avatar-xs  flex-shrink-0'>
                                            <NavLink
                                                to={"/Approvals"}
                                                className='avatar-title bg-white rounded-circle fs-4'
                                                style={{
                                                    color: "#184c8f",
                                                }}>
                                                <i className='las la-list'></i>
                                            </NavLink>
                                        </div>
                                    </div>
                                    <div className="card-header pt-0 pb-0" style={{ border: "none" }}>
                                        <div className="row pb-2  py-4" >

                                            <div className="col-md-12">
                                                <div className="dropdown float-end">
                                                    <button type="button" className="btn btn-light btn-label waves-effect waves-light " id="dropdownMenuLink4" data-bs-toggle="dropdown" aria-expanded="true"
                                                    >
                                                        <i className="ri-download-2-line label-icon align-middle fs-16 me-2" />
                                                        Download Report
                                                    </button>
                                                    <ul className="dropdown-menu dropdown-menu-end" aria-labelledby="dropdownMenuLink4">
                                                        <li><a className="dropdown-item" style={{ cursor: "pointer" }} onClick={() => handleDownload('print')}><i className="ri-printer-line me-2 align-middle text-muted" />Print</a>
                                                        </li>
                                                        <li><a className="dropdown-item" style={{ cursor: "pointer" }} onClick={() => handleDownload('pdf')}><i className="ri-file-pdf-line me-2 align-middle text-muted" />PDF</a>
                                                            <li><a className="dropdown-item" style={{ cursor: "pointer" }} onClick={() => handleDownload('excel')}><i className="ri-file-excel-2-line me-2 align-middle text-muted" />Excel</a>
                                                            </li>

                                                        </li>
                                                    </ul>
                                                </div>
                                            </div>

                                        </div>

                                    </div>
                                    <div className="col-md-12">
                                        <div className="card-body pt-0">
                                            <div className="table-responsive">
                                                <table
                                                    className={`table table-bordered table-stripped table-nowrap`}
                                                >
                                                    <thead className="table-light">
                                                        <tr className="text-center">
                                                            <th>ID</th>
                                                            <th>Item Name</th>
                                                            <th>Description</th>
                                                            <th>Unit</th>
                                                            <th>Unit Price</th>
                                                            <th>Qty & Variations</th>
                                                            <th>Progress</th>
                                                            <th>Due Amount</th>
                                                            <th>Remaining Amount</th>
                                                            <th>Total Amount</th>
                                                            <th>Delivery Date</th>
                                                            <th>Requested By</th>
                                                            <th>Status</th>
                                                            <th>Action</th>
                                                        </tr>
                                                    </thead>
                                                    {rows.length !== 0 ? (
                                                        <tbody>
                                                            {rows.map((row, index) => {
                                                                const itemLogs = parseItemLogs(row.items_logs);
                                                                const totalAmount = row.pi_item_qty * row.pi_item_price;
                                                                const receivedQty = itemLogs.reduce((s, l) => s + (Number(l.project_item_received_qty) || 0), 0);
                                                                const dueAmount = receivedQty * row.pi_item_price;
                                                                const remainingAmount = (row.pi_item_qty - receivedQty) * row.pi_item_price;
                                                                const progress = row.pi_item_qty > 0
                                                                    ? ((receivedQty / row.pi_item_qty) * 100).toFixed(2)
                                                                    : "0.00";

                                                                return (
                                                                    <>
                                                                        <tr key={index} className="text-center">
                                                                            <td>{row.project_request_id}</td>
                                                                            <td>{row.item_name || "-"}</td>
                                                                            <td>{row.request_brief_description || "-"}</td>
                                                                            <td>{row.item_unit || "-"}</td>
                                                                            <td>{row.pi_item_price} QAR</td>
                                                                            <td>
                                                                                <div className="d-flex justify-content-center align-items-center gap-2">
                                                                                    {row?.pi_item_qty_old && row?.pi_item_qty_old !== row?.pi_item_qty && (
                                                                                        <>
                                                                                            <span className="badge bg-light text-muted">
                                                                                                {row?.pi_item_qty_old}
                                                                                            </span>
                                                                                            <i className="ri-arrow-right-line text-muted"></i>
                                                                                        </>
                                                                                    )}


                                                                                    <span className="badge bg-primary-subtle text-primary">
                                                                                        {row?.pi_item_qty}
                                                                                    </span>
                                                                                </div>
                                                                            </td>
                                                                            <td>{progress}</td>
                                                                            <td>{dueAmount}</td>
                                                                            <td>{remainingAmount}</td>
                                                                            <td>{totalAmount}</td>
                                                                            <td>{row.pi_item_delivery_date || "-"}</td>
                                                                            <td>{row.profile_name}</td>
                                                                            <td><span className={GetBadge(row.request_status)}>{GetStatus(row.request_status)}</span></td>
                                                                            <td>
                                                                                <button
                                                                                    type="button"
                                                                                    onClick={() => GetInfo(row)}
                                                                                    data-bs-toggle="modal"
                                                                                    data-bs-target="#myModal"
                                                                                    className="btn-icon btn btn-sm btn-outline-primary"
                                                                                >
                                                                                    <i className=" ri-eye-line"></i>
                                                                                </button>
                                                                            </td>
                                                                        </tr >
                                                                        {
                                                                            itemLogs.length !== 0 && (
                                                                                <tr>
                                                                                    <td colSpan="12" className="p-1">
                                                                                        <div
                                                                                            className="d-flex gap-2 py-1"
                                                                                            style={{
                                                                                                overflowX: "auto",
                                                                                                maxWidth: "100%"
                                                                                            }}
                                                                                        >
                                                                                            {GetProgress(row.pi_item_qty, itemLogs).map((log, i) => (
                                                                                                <div
                                                                                                    key={i}
                                                                                                    className="border rounded text-center d-flex flex-column justify-content-center"
                                                                                                    style={{
                                                                                                        minWidth: "80px",
                                                                                                        maxWidth: "80px",
                                                                                                        height: "55px",
                                                                                                        padding: "4px",
                                                                                                        background: "#f8f9fa"
                                                                                                    }}
                                                                                                >
                                                                                                    <div
                                                                                                        className="fw-semibold text-primary"
                                                                                                        style={{ fontSize: "13px", lineHeight: "1" }}
                                                                                                    >
                                                                                                        {log.progress ?? 0}%
                                                                                                    </div>

                                                                                                    <small
                                                                                                        className="text-muted"
                                                                                                        style={{ fontSize: "11px" }}
                                                                                                    >
                                                                                                        {log.project_item_received_datetime
                                                                                                            ? formatDate(log.project_item_received_datetime)
                                                                                                            : '-'}
                                                                                                    </small>
                                                                                                </div>
                                                                                            ))}
                                                                                        </div>
                                                                                    </td>
                                                                                </tr>
                                                                            )
                                                                        }


                                                                    </>
                                                                );
                                                            })}
                                                        </tbody>
                                                    ) : (
                                                        <tbody>
                                                            <tr>
                                                                <td colSpan="16">
                                                                    <NoRecords />
                                                                </td>
                                                            </tr>
                                                        </tbody>
                                                    )}
                                                    <tfoot className="table-light">
                                                        <tr>
                                                            <th colSpan={16}>
                                                                <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>

                        {/* Modal */}
                        <div
                            id="myModal"
                            className="modal fade"
                            tabIndex={-1}
                            aria-labelledby="myModalLabel"
                            aria-hidden="true"
                            style={{ display: "none" }}
                        >
                            <div className="modal-dialog modal-dialog-centered modal-lg">
                                <div className="modal-content">
                                    {/* Modal Header */}
                                    <div
                                        className="modal-header d-flex justify-content-between align-items-center"
                                        style={{ background: "#000000", padding: "15px" }}
                                    >
                                        <div className="w-100">
                                            <div className="row">
                                                <div className="col-md-4">
                                                    <h5 className="mb-0 text-white">Title:{projectItemsInfo?.project_title ?? '-'}</h5>
                                                </div>
                                                <div className="col-md-4">
                                                    <h5 className="mb-0 text-white">Ref.#: {projectItemsInfo?.project_request_id ?? '0'}</h5>
                                                </div>
                                                <div className="col-md-4">
                                                    <h5 className="mb-0 text-white">Rev # : {projectItemsInfo?.request_revision_count ?? '0'}</h5>
                                                </div>
                                            </div>
                                        </div>
                                        <button
                                            type="button"
                                            onClick={() => ClearModal()}
                                            id="close-create-modal"
                                            className="btn-close"
                                            data-bs-dismiss="modal"
                                            aria-label="Close"
                                            style={{ filter: "invert(1)" }} // Keeps close button visible
                                        ></button>
                                    </div>

                                    {/* Modal Body */}
                                    <div className="modal-body">
                                        <div className="row mb-3">
                                            <div className="mb-3 p-3 border rounded bg-white ">
                                                <h6 className="text-primary mb-2">Item Details</h6>
                                                <div className="row">
                                                    <div className="col-md-3">
                                                        <strong>Item Name:</strong>
                                                        {projectItemsInfo?.item_name}
                                                    </div>
                                                    <div className="col-md-9">
                                                        <strong>Type of Submittal:</strong>
                                                        {projectItemsInfo?.submittal_description}
                                                    </div>
                                                    <div className="col-md-12 mt-3">
                                                        <strong>Brief Description:</strong>
                                                        {projectItemsInfo?.request_brief_description}
                                                    </div>
                                                    <div className="col-md-12 mt-3">
                                                        <strong>Consultant Revision:</strong>
                                                        {projectItemsInfo?.request_revision_remark ?? "No Remark Given"}
                                                    </div>
                                                </div>
                                            </div>
                                        </div>


                                        <div className="row mb-3">
                                            <div className="row">
                                                <div className='col-md-6 border rounded'>
                                                    <label className="form-label mt-2 text-primary">Consultants Details</label>
                                                    {consultantInfo.length > 0 ? (
                                                        consultantInfo.map((consultant, idx) => (
                                                            <div
                                                                key={idx}
                                                                className="border rounded p-3 bg-white shadow-sm mb-3"
                                                                style={{ maxWidth: 400 }}
                                                            >
                                                                <div className="d-flex align-items-center mb-2">
                                                                    <i className="bi bi-person-circle fs-3 me-2 text-primary"></i>
                                                                    <div>
                                                                        <h6 className="mb-0">Name: {consultant.profile_name}</h6>
                                                                    </div>
                                                                </div>
                                                                <div className="mb-1">
                                                                    <i className="bi bi-envelope me-2 text-secondary"></i>
                                                                    <span className="text-muted">Email:{consultant.profile_email}</span>
                                                                </div>
                                                                <div className="mb-1">
                                                                    <i className="bi bi-telephone me-2 text-secondary"></i>
                                                                    <span className="text-muted">Contact Number:
                                                                        {consultant.profile_contact_number}
                                                                    </span>
                                                                </div>

                                                            </div>
                                                        ))
                                                    ) : (
                                                        <p className="text-muted">No consultant information available</p>
                                                    )}
                                                </div>
                                                <div className="col-md-6 border rounded">
                                                    <label className="form-label fw-semibold text-primary mt-2">Uploaded Files</label>
                                                    <div className="p-2 border rounded bg-light">
                                                        {attachments.length > 0 ? (
                                                            <div className="d-flex flex-wrap gap-3">
                                                                {attachments.map((file, index) => {
                                                                    const fileUrl = file.attachment_path.replace(/\\/g, '');
                                                                    const lowerUrl = fileUrl.toLowerCase();
                                                                    const isPdf = lowerUrl.endsWith('.pdf');
                                                                    const isImage = /\.(jpg|jpeg|png|gif|bmp|webp)$/i.test(lowerUrl);

                                                                    return (
                                                                        <a
                                                                            key={index}
                                                                            href={fileUrl}
                                                                            target="_blank"
                                                                            rel="noopener noreferrer"
                                                                            className="text-decoration-none"
                                                                            style={{ width: '100px' }}
                                                                        >
                                                                            <div className="p-2 bg-white rounded shadow-sm d-flex flex-column align-items-center hover-effect border">
                                                                                <i
                                                                                    className={`ri-${isPdf
                                                                                        ? 'file-pdf-fill text-danger'
                                                                                        : isImage
                                                                                            ? 'image-fill text-primary'
                                                                                            : 'file-fill text-secondary'
                                                                                        } fs-1 mb-1`}
                                                                                ></i>
                                                                                <small className="text-truncate text-center text-muted" style={{ maxWidth: '80px' }}>
                                                                                    {isPdf ? 'PDF Document' : isImage ? 'Image File' : 'Other File'}
                                                                                </small>
                                                                            </div>
                                                                        </a>
                                                                    );
                                                                })}
                                                            </div>
                                                        ) : (
                                                            <p className="text-muted mb-0">No File Uploaded</p>
                                                        )}
                                                    </div>
                                                </div>
                                            </div>

                                        </div>
                                    </div>

                                </div>


                            </div>


                        </div>

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

export default RequestList