import React, { useState } from "react";
import GlobalModel from "../../common/GlobalModel";
import ManageBranch from "./ManageBranch";
import { useBranches, useDeleteBranch } from "../../../hooks/useServiceProject";
import { ITEMS_PER_PAGE } from "../../../utils/constants";
import { useDebounce } from "../../../utils/appUtils";
import { useParams } from "react-router-dom";
import Pagination from "../../common/Pagination";
import ConfirmModal from "../../common/ConfirmModal";
import { SpinnerLoader } from "../../common/Loader";
import ViewBranchDetails from "./ViewBranchDetails";

const ServiceBranch = () => {
  const { projectId } = useParams();
  const [IsDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
  const [showInactive, setShowInactive] = useState(false);
  const [manageState, setManageState] = useState({
    IsOpen: false,
    branchId: null,
  });
  const { mutate: DeleteBranch, isPending } = useDeleteBranch();
  const [deletingId, setDeletingId] = useState(null);
  const [ViewRequest, setViewRequest] = useState({ requestId: null, view: false });

  const [search, setSearch] = useState("");
  const [currentPage, setCurrentPage] = useState(1);
  const debouncedSearch = useDebounce(search, 500);

  const { data, isLoading, isError, error } = useBranches(
    projectId,
    !showInactive,
    ITEMS_PER_PAGE - 12,
    currentPage,
    debouncedSearch
  );

  const paginate = (page) => {
    if (page >= 1 && page <= (data?.totalPages ?? 1)) {
      setCurrentPage(page);
    }
  };

  const columns = [
    {
      key: "branchName",
      label: "Name",
      align: "text-start",
      getValue: (e) => e?.branchName || "N/A",
    },
  ];

  const handleDelete = (id) => {
    setDeletingId(id);
    DeleteBranch(
      { id, isActive: showInactive },
      {
        onSettled: () => {
          setDeletingId(null);
          setIsDeleteModalOpen(false);
        },
      }
    );
  };
  return (
    <>
      {IsDeleteModalOpen && (
        <ConfirmModal
          isOpen={IsDeleteModalOpen}
          type={!showInactive ? "delete" : "undo"}
          header={!showInactive ? "Delete Branch" : "Restore Branch"}
          message={
            !showInactive
              ? "Are you sure you want delete?"
              : "Are you sure you want restore?"
          }
          onSubmit={handleDelete}
          onClose={() => setIsDeleteModalOpen(false)}
          loading={isPending}
          paramData={deletingId}
        />
      )}
      <div className="card h-100 table-responsive px-sm-4">
        <div className="card-datatable" id="payment-request-table">
          {/* Header Section */}
          <div className="row align-items-center justify-content-between mt-3 mx-1">
            <div className="col-md-4 col-sm-12 ms-n3 text-start ">
              <h5 className="mb-0">
                <i className="bx bx-buildings text-primary"></i>
                <span className="ms-2 fw-bold">Branches</span>
              </h5>
            </div>

            {/* Flex container for toggle + button */}
            <div className="col-md-8 col-sm-12   text-end">
              <div className="d-flex justify-content-end  gap-2">
                <div className="form-check form-switch d-inline-flex align-items-center">
                  <input
                    type="checkbox"
                    className="form-check-input mt-1"
                    id="inactiveEmployeesCheckbox"
                    checked={showInactive}
                    onChange={() => setShowInactive(!showInactive)}
                  />
                  <label
                    htmlFor="inactiveEmployeesCheckbox"
                    className="ms-2 text-xs"
                  >
                    {!showInactive ? "Show Deleted" : "Hide Deleted"}
                  </label>
                </div>
                <div className="d-flex justify-content-end">
                  <button
                    className="btn btn-sm btn-primary"
                    type="button"
                    onClick={() =>
                      setManageState({
                        IsOpen: true,
                        branchId: null,
                      })
                    }
                  >
                    <i className="bx bx-sm bx-plus-circle me-2"></i>
                    Add Branch
                  </button>
                </div>
              </div>
            </div>
          </div>

          <div className="mx-2 mt-3">
            <table className="table border-top text-nowrap align-middle  table-borderless">
              <thead>
                <tr>
                  {columns.map((col) => (
                    <th key={col.key} className={col.align}>
                      {col.label}
                    </th>
                  ))}
                  <th className="text-center">Action</th>
                </tr>
              </thead>

              <tbody>
                {isLoading && (
                  <tr>
                    <td
                      colSpan={columns.length + 1}
                      className="text-center py-5"
                      style={{
                        height: "200px",
                        verticalAlign: "middle",
                      }}
                    >
                      <div className="d-flex justify-content-center align-items-center w-100 h-100">
                        <SpinnerLoader />
                      </div>
                    </td>
                  </tr>
                )}

                {isError && (
                  <tr>
                    <td
                      colSpan={columns.length + 1}
                      className="text-center text-danger py-5"
                    >
                      {error?.message || "Error loading branches"}
                    </td>
                  </tr>
                )}

                {!isLoading &&
                  !isError &&
                  data?.data?.length > 0 &&
                  data.data.map((branch) => (
                    <tr
                      key={branch.id}
                      style={{ height: "35px", cursor: showInactive ? "default" : "pointer" }}
                      onClick={(e) => {
                        if (!showInactive && !e.target.closest(".dropdown") && !e.target.closest(".bx-show")) {
                          setViewRequest({ branchId: branch.id, view: true });
                        }
                      }}
                    >

                      {columns.map((col) => (
                        <td key={col.key} className={`${col.align} py-3`}>
                          {col.getValue(branch)}
                        </td>
                      ))}
                      <td className="text-center">
                        <div className="d-flex justify-content-center align-items-center gap-2">
                          {/* View Icon */}
                          {/* <i
                            className="bx bx-show text-primary cursor-pointer"
                            onClick={() =>
                              setViewRequest({ branchId: branch.id, view: true })
                            }
                          ></i> */}

                          <div className="dropdown z-2">
                            <button
                              type="button"
                              className="btn btn-xs btn-icon btn-text-secondary rounded-pill dropdown-toggle hide-arrow p-0 m-0"
                              data-bs-toggle="dropdown"
                            >
                              <i className="bx bx-dots-vertical-rounded text-muted p-0"></i>
                            </button>
                            <ul className="dropdown-menu dropdown-menu-end w-auto">
                              {!showInactive ? (
                                <>
                                  <li
                                    onClick={() =>
                                      setManageState({
                                        IsOpen: true,
                                        branchId: branch.id,
                                      })
                                    }
                                  >
                                    <a className="dropdown-item px-2 cursor-pointer py-1">
                                      <i className="bx bx-edit text-primary bx-xs me-2"></i>
                                      Modify
                                    </a>
                                  </li>
                                  <li
                                    onClick={() => {
                                      setIsDeleteModalOpen(true);
                                      setDeletingId(branch.id);
                                    }}
                                  >
                                    <a className="dropdown-item px-2 cursor-pointer py-1">
                                      <i className="bx bx-trash text-danger bx-xs me-2"></i>
                                      Delete
                                    </a>
                                  </li>
                                  <li
                                    onClick={() =>
                                      setViewRequest({ branchId: branch.id, view: true })
                                    }
                                  >
                                    <a className="dropdown-item px-2 cursor-pointer py-1">
                                      <i className="bx bx-show text-primary cursor-pointer me-2"></i>
                                      View
                                    </a>
                                  </li>
                                </>
                              ) : (
                                <li
                                  onClick={() => {
                                    setIsDeleteModalOpen(true);
                                    setDeletingId(branch.id);
                                  }}
                                >
                                  <a className="dropdown-item px-2 cursor-pointer py-1">
                                    <i className="bx bx-undo text-danger me-2"></i>
                                    Restore
                                  </a>
                                </li>
                              )}
                            </ul>
                          </div>
                        </div>
                      </td>
                    </tr>
                  ))}

                {!isLoading &&
                  !isError &&
                  (!data?.data || data.data.length === 0) && (
                    <tr>
                      <td colSpan={columns.length + 1}>
                        <div
                          className="d-flex justify-content-center align-items-center"
                          style={{ height: "150px" }}
                        >
                          No Branch Found
                        </div>
                      </td>
                    </tr>
                  )}

              </tbody>
            </table>

            {data?.data?.length > 0 && (
              <Pagination
                currentPage={currentPage}
                totalPages={data.totalPages}
                onPageChange={paginate}
              />
            )}
          </div>

          {manageState.IsOpen && (
            <GlobalModel
              isOpen
              size="md"
              closeModal={() =>
                setManageState({ IsOpen: false, branchId: null })
              }
            >
              <ManageBranch
                key={manageState.branchId ?? "new"}
                BranchToEdit={manageState.branchId}
                closeModal={() =>
                  setManageState({ IsOpen: false, branchId: null })
                }
              />
            </GlobalModel>
          )}
          {ViewRequest.view && (
            <GlobalModel
              isOpen
              size="md"
              modalType="top"
              closeModal={() => setViewRequest({ branchId: null, view: false })}
            >
              <ViewBranchDetails BranchToEdit={ViewRequest.branchId} />
            </GlobalModel>

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

export default ServiceBranch;
