import React, { useState, useEffect, useContext } from "react";
import PageTitle from "../../Components/PageTitle";
import axios from "axios";
import { ConfigContext } from "../../Context/ConfigContext";
import { ContentLoader, NoRecords } from "../../Components/Shimmer";
import { NavLink, useParams } from "react-router-dom";

const ItemList = () => {
  const { apiURL, apiHeaderJson } = 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(true);

  useEffect(() => {
    if (project_id) {
      GetList();
    }
  }, [project_id, page]);

  /*------------------------------------
    Get Item List
  ------------------------------------*/
  const GetList = async () => {
    setLoadingList(true);
    try {
      const response = await axios.get(
        `${apiURL}api/clients/Get-Request-Items`,
        {
          params: { pi_project_id: project_id },
          headers: apiHeaderJson,
        }
      );

      const result = response.data;

      if (result?.success) {
        setRows(result.data);
        setTotalRecords(result.data.length);

        const pages = Math.ceil(result.data.length / limit);
        setTotalPages(pages);

        setNext(page < pages);
        setPrev(page > 1);
      } else {
        setRows([]);
      }
    } catch (error) {
      console.error("Error fetching items:", error);
      setRows([]);
    } finally {
      setLoadingList(false);
    }
  };

  /*------------------------------------
    Pagination
  ------------------------------------*/
  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));
  };

  return (
    <div className="main-content">
      <div className="page-content">
        {loadingList === false ? (
          <div className="container-fluid">
            <br />
            <PageTitle title="Items List" primary="Home" />

            <div className="row">
              <div className="col-md-12">
                <div className="card">

                  {/* HEADER */}
                  <div
                    className="card-header align-items-center d-flex"
                    style={{ background: "#000000" }}
                  >
                    <h4 className="card-title mb-0 flex-grow-1 text-white">
                      Requested Items
                    </h4>

                    <div className="avatar-xs flex-shrink-0">
                      <NavLink
                        to={"/ProjectList"}
                        className="avatar-title bg-white rounded-circle fs-4"
                        style={{ color: "#000308" }}
                      >
                        <i className="ri-list-unordered"></i>
                      </NavLink>
                    </div>
                  </div>

                  {/* TABLE */}
                  <div className="col-md-12">
                    <div className="card-body p-0">
                      <table className="table table-bordered table-stripped">

                        <thead className="table-light">
                          <tr>
                            <th className="text-center">Item ID</th>
                            <th className="text-center">Quantity</th>
                            <th className="text-center">Received Quantity</th>
                            <th className="text-center">Price</th>
                            <th className="text-center">Created Date</th>
                          </tr>
                        </thead>

                        {rows.length !== 0 ? (
                          <tbody>
                            {rows.map((row) => (
                              <tr key={row.project_item_id}>

                                <td className="text-center">
                                  {row.pi_item_id}
                                </td>

                                <td className="text-center">
                                  {row.pi_item_qty}
                                </td>

                                <td className="text-center">
                                  {row.pi_item_received_qty}
                                </td>

                                <td className="text-center">
                                  {row.pi_item_price}
                                </td>

                                <td className="text-center">
                                  {row.created_date}
                                </td>

                              </tr>
                            ))}
                          </tbody>
                        ) : (
                          <tbody>
                            <tr>
                              <td colSpan="5">
                                <NoRecords />
                              </td>
                            </tr>
                          </tbody>
                        )}

                        {/* PAGINATION */}
                        <tfoot className="table-light">
                          <tr>
                            <th colSpan={5}>
                              <div className="d-flex justify-content-between align-items-center">

                                <button
                                  disabled={!prev}
                                  onClick={handlePrev}
                                  className="btn btn-warning btn-label waves-effect waves-light"
                                >
                                  <i className="ri-arrow-left-line label-icon fs-16 me-2" />
                                  Previous
                                </button>

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

                                <select
                                  className="form-select w-auto"
                                  value={page}
                                  onChange={handleChange}
                                >
                                  {Array.from({ length: totalPages }, (_, i) => (
                                    <option key={i + 1} value={i + 1}>
                                      {i + 1}
                                    </option>
                                  ))}
                                </select>

                                <button
                                  disabled={!next}
                                  onClick={handleNext}
                                  className="btn btn-primary btn-label waves-effect waves-light"
                                >
                                  Next
                                  <i className="ri-arrow-right-line label-icon fs-16 ms-2" />
                                </button>

                              </div>
                            </th>
                          </tr>
                        </tfoot>

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

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

export default ItemList;
