import React, { useState, useEffect } from "react";
import Spinner from "../../UIComponants/Spinner";
import "../Dashboard/CSS/CSS/MenuMaitenance.css";
import { Table, Pagination, PaginationItem, PaginationLink } from "reactstrap";
import { BsJournals } from "react-icons/bs";
import {
  Button,
  Dropdown,
  Modal,
  Form,
  Row,
  Col,
  InputGroup,
  FormControl,
  OverlayTrigger,
  Tooltip,
} from "react-bootstrap";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { FaSearch } from "react-icons/fa";
import { faEdit, faTrashAlt } from "@fortawesome/free-solid-svg-icons";
import { addSubmenuItem } from "../../APIServices/MenuMaintenanceAPI";
import { toast } from "react-toastify";
const SubMenuMaintenance = ({ selectedMainMenuId }) => {
  const [recordsPerPage, setRecordsPerPage] = useState(10);
  const [currentPage, setCurrentPage] = useState(1);
  const [subMenu, setSubMenu] = useState([]);
  const [modalAdd, setModalAdd] = useState(false);
  const [modalDelete, setModalDelete] = useState(false);
  const [modalEdit, setModalEdit] = useState(false);
  const [loading, setLoading] = useState(false);
  const [rowSelected, setRowSelected] = useState({});

  const [entryForm, setEntryForm] = useState({
    menuId: selectedMainMenuId,
    menuItemDesc: "",
    itemSeq: "",
    moduleName: "",
    status: "Enable",
    main_menu_action_name: "",
  });
  const [data, setData] = useState([]);

  const [visibleColumns, setVisibleColumns] = useState({
    menu_id: true,
    menuItemDesc: true,
    itemSeq: true,
    moduleName: true,
    main_menu_action_name: true,
    status: true,
  });

  const [isSubMenu, setIsSubMenu] = useState(false);
  const [searchQuery, setSearchQuery] = useState("");
  const [menuItems, setMenuItems] = useState([]);
  const [slicedSubMenus, setSlicedSubMenus] = useState([]);
  const [currentMenuItem, setCurrentMenuItem] = useState({});
  const [subMenuItems, setSubMenuItems] = useState([]);

  useEffect(() => {
    // Simulate loading data
    setTimeout(() => {
      setLoading(false);
    }, 3000); // Simulated 3 seconds loading
  }, []);

  useEffect(() => {
    if (selectedMainMenuId) {
      setEntryForm((prev) => ({ ...prev, menuId: selectedMainMenuId }));
    }
  }, [selectedMainMenuId]);

  useEffect(() => {
    const filteredSubMenus = subMenu
      .filter(
        (submenu) =>
          submenu.menuItemDesc &&
          submenu.menuItemDesc.toLowerCase().includes(searchQuery.toLowerCase())
      )
      .slice((currentPage - 1) * recordsPerPage, currentPage * recordsPerPage);

    setSlicedSubMenus(filteredSubMenus);
  }, [subMenu, searchQuery, currentPage, recordsPerPage]);

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setEntryForm((prev) => ({ ...prev, [name]: value }));
  };

  const handleRowChange = (e) => {
    const { name, value } = e.target;
    setRowSelected((prev) => ({ ...prev, [name]: value }));
  };

  const handleSearch = (query) => {
    setSearchQuery(query);
  };

  // const goToAdd = () => {
  //   setEntryForm((prev) => ({
  //     ...prev,
  //     menuId: selectedMainMenuId, // Set the main menu ID
  //   }));
  //   setModalAdd(true);
  // };

  const goToAdd = () => {
    console.log("selectedMainMenuId:", selectedMainMenuId); // Debugging line
    if (!selectedMainMenuId) {
      toast.error("Please select a main menu item first.");
      return;
    }
    setEntryForm((prev) => ({
      ...prev,
      menuId: selectedMainMenuId,
    }));
    setModalAdd(true);
  };
  
  
  const onSubmit = async (event) => {
    event.preventDefault();

    // Include menuId in the form data
    const formData = {
      menuItemDesc: entryForm.menuItemDesc,
    };

    try {
      // Pass menuId as a string
      const data = await addSubmenuItem(
        selectedMainMenuId.toString(),
        formData
      );
      toast.success("Submenu item added successfully!");
      console.log("Submenu item added successfully:", data);
      // Handle successful submission, e.g., close modal, refresh data, etc.
      setModalAdd(false);
    } catch (error) {
      console.error("Error adding submenu item:", error);
      toast.error(
        "Unexpected error: " +
          (error.message || "Server error occurred. Please try again.")
      );
      // Handle error, e.g., show a message to the user
    }
  };

  const goToEdit = (user) => {
    setRowSelected(user);
    setEntryForm({
      menuId: user.menuId,
      menuItemDesc: user.menuItemDesc,
    });
    setModalEdit(true);
  };

  const onUpdate = (e) => {
    e.preventDefault();

    // Prepare the updated entry from the form
    const updatedEntry = {
      menuId: entryForm.menuId,
      menuItemDesc: entryForm.menuItemDesc,
      // Add other fields as needed
    };

    // Find the index of the subMenu to update
    const index = slicedSubMenus.findIndex(
      (subMenu) => subMenu.menuId === updatedEntry.menuId
    );

    if (index !== -1) {
      // Update the subMenu in the state
      const updatedSubMenus = [...slicedSubMenus];
      updatedSubMenus[index] = updatedEntry;

      // Update the state with the new subMenus list
      setSlicedSubMenus(updatedSubMenus);

      // Close the modal after updating
      setModalEdit(false);
    }
  };

  const onDelete = (user) => {
    setRowSelected(user);
    setModalDelete(true);
  };

  const confirmDelete = () => {
    // Logic to delete
    console.log("Deleted:", rowSelected);
    setModalDelete(false);
  };

  // pagination
  const toggleColumn = (column) => {
    setVisibleColumns((prev) => ({
      ...prev,
      [column]: !prev[column],
    }));
  };

  const totalPages = Math.ceil(subMenu.length / recordsPerPage);
  const handlePageChange = (pageNumber) => {
    setCurrentPage(pageNumber);
  };
  const handleRecordsPerPageChange = (number) => {
    setRecordsPerPage(number);
  };
  return (
    <div style={{ marginTop: "11rem" }}>
      {loading ? (
        <Spinner />
      ) : (
        <div className="submenu-maintenance">
          {/* Header */}
          <div className="row mt-3">
            <div className="col-md-8">
              <h3 className=" d-inline title_main">Sub-Menu Maintenance</h3>
              <span className="badge bg-primary ms-3">Sub Menu</span>
            </div>
          </div>

          <Row className="align-items-center my-3">
            {/* Left: Search Bar */}
            <Col
              xs={12}
              md={8}
              lg={6}
              className="d-flex justify-content-center my-3"
            >
              <InputGroup
                className="search-bar"
                style={{
                  borderRadius: "10px",
                  overflow: "hidden",
                  boxShadow: "0px 4px 12px rgba(0, 0, 0, 0.1)",
                  width: "100%",
                  maxWidth: "528px", // Set max-width to limit overall width
                  paddingRight: "-15px", // Increase padding on the right side
                }}
              >
                <InputGroup.Text
                  style={{
                    backgroundColor: "#0E6591",
                    color: "#fff",
                    padding: "10px 15px",
                  }}
                >
                  <FaSearch />
                </InputGroup.Text>
                <FormControl
                  placeholder="Search"
                  value={searchQuery}
                  onChange={(e) => handleSearch(e.target.value)}
                  style={{
                    padding: "10px",
                    border: "none",
                    paddingRight: "5px", // More space on the right side of input field
                  }}
                />
              </InputGroup>
            </Col>
            <Col xs={12} md={4} lg={6} className="d-flex justify-content-end">
              <div className="col-md-4 text-end">
                <button className="btn btn-primary" onClick={goToAdd}>
                  <i className="bi bi-plus"></i> ADD
                </button>
              </div>
            </Col>
          </Row>

          <div className="table-responsive">
            <Table
              striped
              responsive
              hover
              align="middle"
              className="table-flush shadow-sm"
            >
              <thead className="custom_header">
                <tr>
                  <th>No</th>
                  {Object.entries(visibleColumns).map(
                    ([key, visible]) =>
                      visible && (
                        <th key={key}>
                          {key.charAt(0).toUpperCase() + key.slice(1)}
                        </th>
                      )
                  )}
                  <th>Actions</th>
                </tr>
              </thead>
              <tbody className="tbody">
                {slicedSubMenus.length === 0 ? (
                  <tr>
                    <td
                      colSpan={
                        1 + // For the "No" column
                        Object.keys(visibleColumns).filter(
                          (key) => visibleColumns[key]
                        ).length +
                        (isSubMenu ? 1 : 2)
                      }
                      className="text-center"
                    >
                      No menu items found. Please add new items.
                    </td>
                  </tr>
                ) : (
                  slicedSubMenus.map((subMenu, index) => (
                    <tr key={index}>
                      <td>{index + 1}</td>
                      {Object.keys(visibleColumns).map(
                        (key) =>
                          visibleColumns[key] && (
                            <td key={key}>
                              {key === "status" ? (
                                <span
                                  className="status"
                                  style={{
                                    color: subMenu.status ? "green" : "red",
                                    backgroundColor: subMenu.status
                                      ? "#d4f7d4"
                                      : "#f7d4d4",
                                    padding: "4px 8px",
                                    borderRadius: "4px",
                                    display: "inline-block",
                                  }}
                                >
                                  {subMenu.status ? "Enabled" : "Disabled"}
                                </span>
                              ) : (
                                subMenu[key]
                              )}
                            </td>
                          )
                      )}
                      <td className="text-center">
                        <FontAwesomeIcon
                          icon={faEdit}
                          onClick={() => goToEdit(subMenu)}
                          style={{
                            cursor: "pointer",
                            fontSize: "1rem",
                            color: "green",
                            marginRight: "15px",
                          }}
                        />
                        <FontAwesomeIcon
                          icon={faTrashAlt}
                          onClick={() => onDelete(subMenu)}
                          style={{
                            cursor: "pointer",
                            fontSize: "1rem",
                            color: "#dc3545",
                          }}
                        />
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </Table>
          </div>

          {/* Manage Columns & Records Per Page */}
          <Row className="mt-4">
            <Col md={6} className="d-flex justify-content-start">
              <Dropdown>
                <Dropdown.Toggle
                  variant="outline-primary"
                  className="custom_manage_column_button"
                >
                  Manage Columns
                </Dropdown.Toggle>
                <Dropdown.Menu>
                  {Object.keys(visibleColumns).map((column) => (
                    <Dropdown.Item
                      key={column}
                      onClick={() => toggleColumn(column)}
                    >
                      <Form.Check
                        type="checkbox"
                        label={
                          column.charAt(0).toUpperCase() +
                          column.slice(1).toLowerCase()
                        }
                        checked={visibleColumns[column]}
                        readOnly
                        className="custom-checkbox"
                      />
                    </Dropdown.Item>
                  ))}
                </Dropdown.Menu>
              </Dropdown>
            </Col>

            <Col md={6} className="d-flex justify-content-end">
              <Dropdown>
                <Dropdown.Toggle
                  variant="outline-primary"
                  className="custom_manage_column_button px-4 py-2 border-2 rounded-3 shadow-sm"
                  id="dropdown-custom-components"
                >
                  <BsJournals />
                </Dropdown.Toggle>
                <Dropdown.Menu
                  className="border-0 rounded-3 shadow-lg"
                  align="end"
                >
                  {[1, 5, 10, 20, 50].map((number) => (
                    <Dropdown.Item
                      key={number}
                      onClick={() => handleRecordsPerPageChange(number)}
                      className="text-dark d-flex justify-content-between align-items-center"
                    >
                      <span>{number}</span>
                      <i
                        className="fa fa-check-circle"
                        style={{
                          display:
                            recordsPerPage === number ? "inline" : "none",
                        }}
                      />
                    </Dropdown.Item>
                  ))}
                </Dropdown.Menu>
              </Dropdown>
            </Col>
          </Row>

          <Pagination className="pagination">
            <PaginationItem disabled={currentPage === 1}>
              <PaginationLink
                previous
                onClick={() => handlePageChange(currentPage - 1)}
              />
            </PaginationItem>
            {[...Array(totalPages)].map((_, index) => (
              <PaginationItem key={index} active={index + 1 === currentPage}>
                <PaginationLink
                  onClick={() => handlePageChange(index + 1)}
                  style={{ color: "#0b6592" }}
                >
                  {index + 1}
                </PaginationLink>
              </PaginationItem>
            ))}
            <PaginationItem disabled={currentPage === totalPages}>
              <PaginationLink
                next
                onClick={() => handlePageChange(currentPage + 1)}
              />
            </PaginationItem>
          </Pagination>

          {/* Modals */}
          {modalAdd && (
            <div className="modal fade show d-block" tabIndex="-1">
              <div className="modal-dialog">
                <div className="modal-content">
                  <div className="modal-header">
                    <h5 className="modal-title">Add Sub-Menu</h5>
                    <button
                      type="button"
                      className="btn-close"
                      onClick={() => setModalAdd(false)}
                    ></button>
                  </div>
                  <div className="modal-body">
                    <form onSubmit={onSubmit}>
                      <input
                        type="text"
                        className="form-control mb-2"
                        name="menuId"
                        placeholder="Menu ID"
                        value={entryForm.menuId || selectedMainMenuId}
                        onChange={handleInputChange}
                        readOnly
                      />

                      <input
                        type="text"
                        className="form-control mb-2"
                        name="menuItemDesc"
                        placeholder="Menu Item Name"
                        value={entryForm.menuItemDesc}
                        onChange={handleInputChange}
                      />
                      <button type="submit" className="btn btn-primary">
                        Add
                      </button>
                    </form>
                  </div>
                </div>
              </div>
            </div>
          )}

          {modalEdit && (
            <div className="modal fade show d-block" tabIndex="-1">
              <div className="modal-dialog">
                <div className="modal-content">
                  <div className="modal-header">
                    <h5 className="modal-title">Edit Sub-Menu</h5>
                    <button
                      type="button"
                      className="btn-close"
                      onClick={() => setModalEdit(false)}
                    ></button>
                  </div>
                  <div className="modal-body">
                    <form onSubmit={onUpdate}>
                      <input
                        type="text"
                        className="form-control mb-2"
                        name="menuId"
                        placeholder="Menu ID"
                        value={entryForm.menuId}
                        onChange={handleInputChange}
                      />
                      <input
                        type="text"
                        className="form-control mb-2"
                        name="menuItemDesc"
                        placeholder="Menu Item Name"
                        value={entryForm.menuItemDesc}
                        onChange={handleInputChange}
                      />
                      <button type="submit" className="btn btn-primary">
                        Update
                      </button>
                    </form>
                  </div>
                </div>
              </div>
            </div>
          )}
        </div>
      )}
    </div>
  );
};

export default SubMenuMaintenance;
