import React, { useState, useEffect, useContext } 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 { NavLink, useParams } from "react-router-dom";
import 'flatpickr/dist/themes/material_blue.css';

const ProjectList = () => {

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

  const { project_status } = 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);

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

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

      const result = response.data;

      if (result?.success) {
        setRows(response.data.data)
        setNext(response.data.next);
        setPrev(response.data.prev);
        setPage(response.data.page);
        setTotalRecords(response.data.total_records);
        setTotalPages(response.data.total_pages);

      } else {
        setRows([]);
      }

    } catch (error) {
      console.error("Error fetching project list:", 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));
  };


  /*------------------------------------
    Download Handler
  ------------------------------------*/
  const handleDownload = (type) => {
    Swal.fire({
      title: "Please wait...",
      html: `Preparing ${type} file for download...`,
      allowOutsideClick: false,
      didOpen: () => {
        Swal.showLoading();
      },
    });

    // You can connect your API here later
    setTimeout(() => {
      Swal.fire({
        icon: "success",
        title: `${type} Ready!`,
        timer: 1500,
        showConfirmButton: false
      });
    }, 1500);
  };


  /*------------------------------------
    Status Utils
  ------------------------------------*/
  const getStatus = (status) => {
    if (status === 0) return "Active";
    if (status === 1) return "Completed";
    if (status === 2) return "Cancelled";
    return "Unknown";
  };

  const getBadge = (status) => {
    if (status === 0) return "badge bg-info-subtle text-info";
    if (status === 1) return "badge bg-success-subtle text-success";
    if (status === 2) return "badge bg-warning-subtle text-warning";
    return "badge bg-secondary-subtle text-secondary";
  };


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

        {loadingList === false ? (
          <div className="container-fluid">
            <br />
            <PageTitle title="ProjectList" 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">
                      Project List
                    </h4>

                    <div className="dropdown">
                      <button
                        type="button"
                        className="btn btn-light btn-label waves-effect waves-light"
                        data-bs-toggle="dropdown"
                      >
                        <i className="ri-download-2-line label-icon fs-16 me-2" />
                        Download Report
                      </button>

                      <ul className="dropdown-menu dropdown-menu-end">
                        <li>
                          <a className="dropdown-item" onClick={() => handleDownload("Print")}>
                            <i className="ri-printer-line me-2" /> Print
                          </a>
                        </li>
                        <li>
                          <a className="dropdown-item" onClick={() => handleDownload("PDF")}>
                            <i className="ri-file-pdf-line me-2" /> PDF
                          </a>
                        </li>
                        <li>
                          <a className="dropdown-item" onClick={() => handleDownload("Excel")}>
                            <i className="ri-file-excel-2-line me-2" /> Excel
                          </a>
                        </li>
                      </ul>
                    </div>

                  </div>


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

                      <thead className="table-light">
                        <tr>
                          <th className="text-center">Project Name</th>
                          <th className="text-center">Location</th>
                          <th className="text-center">Consultant Name</th>
                          <th className="text-center">Contractor Name</th>
                          <th className="text-center">Project Status</th>
                          <th className="text-center" width={120}>Item List</th>
                        </tr>
                      </thead>

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

                              <td className="text-center">
                                <NavLink to={`/ProjectProfile/${row.project_id}`}>
                                  {row.project_title}
                                </NavLink>
                              </td>

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

                              <td className="text-center">
                                <div className="tooltip-container">
                                  <div className="ellipsis-text">Addison George, Céline Antoine</div>
                                  <span className="tooltip-content">Addison George, Céline Antoine</span>
                                </div>
                              </td>

                              <td className="text-center">
                                <div className="tooltip-container">
                                  <div className="ellipsis-text">John Doe, Louis Bans</div>
                                  <span className="tooltip-content">John Doe, Louis Bans</span>
                                </div>
                              </td>

                              <td className="text-center">
                                <span className={getBadge(row.project_status)}>
                                  {getStatus(row.project_status)}
                                </span>
                              </td>

                              <td className="d-flex justify-content-around">
                                <NavLink to={`/ItemList/${row.project_id}`}>
                                  <button className="btn-icon btn btn-sm btn-outline-primary">
                                    <i className="ri-list-unordered"></i>
                                  </button>
                                </NavLink>
                              </td>

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

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

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

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

                              <select
                                className="form-select w-auto"
                                onChange={handleChange}
                                value={page}
                              >
                                {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"
                              >
                                Next
                                <i className="ri-arrow-right-line label-icon fs-16 ms-2" />
                              </button>

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

                    </table>
                  </div>

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

      </div>
    </div>
  );
};

export default ProjectList;
