import React, { useState, useEffect } from "react";
import {
  Button,
  Dropdown,
  Modal,
  Form,
  Row,
  Col,
  InputGroup,
  FormControl,
} from "react-bootstrap";
import { Table, Pagination, PaginationItem, PaginationLink } from "reactstrap";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import {
  faEdit,
  faTrashAlt,
  faPlus,
  faBars,
  faTimes,
} from "@fortawesome/free-solid-svg-icons";
import "bootstrap/dist/css/bootstrap.min.css";
import "../Dashboard/CSS/CSS/CommonStyle.css";
import { FaSearch, FaTimes } from "react-icons/fa";
import { BsJournals } from "react-icons/bs";
import { toast } from "react-toastify";
import Spinner from '../../UIComponants/Spinner';

function AccessTypeManagement() {
  const [accessTypes, setAccessTypes] = useState([]);
  const [showAddEditModal, setShowAddEditModal] = useState(false);
  const [currentAccessType, setCurrentAccessType] = useState({
    typeId: "",
    typeName: "",
    description: "",
    isActive: false,
  });
  const [currentPage, setCurrentPage] = useState(1);
  const [searchQuery, setSearchQuery] = useState("");
  const [isEditing, setIsEditing] = useState(false);
  const [recordsPerPage, setRecordsPerPage] = useState(10);
  const [visibleColumns, setVisibleColumns] = useState({
    typeId: true,
    typeName: true,
    description: true,
    isActive: true,
    actions: true,
  });
  const [loading, setLoading] = useState(true);


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

  useEffect(() => {
    const fetchAccessTypes = async () => {
      const apiUrl = `${process.env.REACT_APP_API_URL}token/access_type/Accesstype`;
      const token = localStorage.getItem("authToken");

      if (!token) {
        console.error("Authorization token is missing.");
        return;
      }

      try {
        const response = await fetch(apiUrl, {
          method: "GET",
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${token}`,
          },
        });

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }

        const data = await response.json();
        setAccessTypes(data);
      } catch (error) {
        console.error("Error fetching access types:", error);
      }
    };

    fetchAccessTypes();
  }, []);

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

  const handleInputChange = (event) => {
    const { name, value, checked, type } = event.target;
    setCurrentAccessType((prev) => ({
      ...prev,
      [name]: type === "checkbox" ? checked : value,
    }));
  };

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

  const handleSubmit = (event) => {
    try {
      event.preventDefault();
    if (isEditing) {
      setAccessTypes(
        accessTypes.map((type) =>
          type.typeId === currentAccessType.typeId ? currentAccessType : type
        )
      );
      toast.success("AccessType updated successfully!");
    } else {
      const newTypeId = `ID${accessTypes.length + 1}`;
      setAccessTypes([
        ...accessTypes,
        { ...currentAccessType, typeId: newTypeId },
      ]);
      toast.success("AccessType added successfully!");
    }
    setShowAddEditModal(false);
    } catch (error) {
      toast.error("There was an error while submitting the Type.");
      console.error("Error in handleSubmit:", error); // Log the error for debugging
    }
    
  };

  const openModal = (
    type = { typeId: "", typeName: "", description: "", isActive: false }
  ) => {
    setIsEditing(!!type.typeId);
    setCurrentAccessType(type);
    setShowAddEditModal(true);
  };

  const handleClose = () => {
    setShowAddEditModal(false); // Close the modal by setting the state to false
  };

  const slicedAccessTypes = accessTypes
    .filter(
      (item) =>
        item.typeName &&
        item.typeName.toLowerCase().includes(searchQuery.toLowerCase())
    )
    .slice((currentPage - 1) * recordsPerPage, currentPage * recordsPerPage);
  const handleDelete = (typeId) => {
    setAccessTypes(accessTypes.filter((type) => type.typeId !== typeId));
    toast.success("Access Type Deleted ... ");
  };

  const handleRecordsPerPageChange = (number) => {
    setRecordsPerPage(number);
    setCurrentPage(1);
  };

  const totalPages = Math.ceil(accessTypes.length / recordsPerPage);
  const handlePageChange = (pageNumber) => {
    setCurrentPage(pageNumber);
  };

  return (
    <div style={{marginTop:"1rem"}}>
      {loading ? (
        <Spinner/>
      ):(
        <div className="container-fluid mt-5">
      <div className="d-flex justify-content-between align-items-center mb-4">
        <h1 className="title_main">Access Type</h1>
      </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>

        {/*Add Icons */}
        <Col xs={12} md={4} lg={6} className="d-flex justify-content-end">
          <>
            {/* Add Icon */}
            <FontAwesomeIcon
              icon={faPlus}
              onClick={() => openModal(true)}
              style={{
                cursor: "pointer",
                fontSize: "1.5rem",
                color: "#747264",
                marginRight: "20px",
              }}
            />
            <FontAwesomeIcon
              icon={faBars}
              style={{
                cursor: "pointer",
                fontSize: "1.5rem",
                color: "#747264",
              }}
            />
          </>
        </Col>
      </Row>

      <div className="table-responsive">
        <Table striped hover responsive align="middle" className=" table-flush shadow-sm">
          <thead className="custom_header">
            <tr>
              {Object.entries(visibleColumns).map(([key, visible]) =>
                visible ? (
                  <th key={key}>
                    {key.charAt(0).toUpperCase() + key.slice(1)}
                  </th>
                ) : null
              )}
            </tr>
          </thead>
          <tbody className="tbody">
            {slicedAccessTypes.length === 0 ? (
              <tr>
                <td
                  colSpan={
                    Object.keys(visibleColumns).filter(
                      (key) => visibleColumns[key]
                    ).length
                  }
                  className="text-center"
                >
                  No Data Available
                </td>
              </tr>
            ) : (
              slicedAccessTypes.map((type) => (
                <tr key={type.typeId}>
                  {Object.entries(visibleColumns).map(([key, visible]) =>
                    visible ? (
                      <td key={key}>
                        {key === "actions" ? (
                          <div className="">
                            <FontAwesomeIcon
                              icon={faEdit}
                              onClick={() => openModal(type)}
                              className="me-2"
                              style={{
                                cursor: "pointer",
                                fontSize: "1rem",
                                color: "green", // edit icon color
                                marginRight: "15px", // space between icons
                              }}
                            />
                            <FontAwesomeIcon
                              icon={faTrashAlt}
                              onClick={() => handleDelete(type.typeId)}
                              style={{
                                cursor: "pointer",
                                fontSize: "1rem",
                                color: "#dc3545", // delete icon color
                              }}
                            />
                          </div>
                        ) : key === "isActive" ? (
                          <span
                            className="status"
                            style={{
                              color: type.isActive ? "green" : "red", // Dynamic text color
                              backgroundColor: type.isActive
                                ? "#d4f7d4"
                                : "#f7d4d4", // Faint green or red background
                              padding: "4px 8px", // Add some padding for the background effect
                              borderRadius: "4px", // Rounded corners
                              display: "inline-block", // Ensure the background only affects the text
                            }}
                          >
                            {type.isActive ? "Active" : "Inactive"}
                          </span>
                        ) : (
                          type[key]
                        )}
                      </td>
                    ) : null
                  )}
                </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>

      {/* Add/Edit model */}
      <Modal show={showAddEditModal} onHide={() => setShowAddEditModal(false)} >
        <Modal.Header>
          <Modal.Title>
            {isEditing ? "Edit Access Type" : "Add Access Type"}
          </Modal.Title>
          <FontAwesomeIcon
            icon={faTimes}
            size="lg"
            onClick={handleClose}
            style={{
              position: "absolute",
              top: "25px",
              right: "25px",
              cursor: "pointer",
            }}
          />
        </Modal.Header>
        <Modal.Body>
          <Form onSubmit={handleSubmit}>
            <Form.Group controlId="formTypeName">
              <Form.Label>Type Name</Form.Label>
              <Form.Control
                type="text"
                name="typeName"
                value={currentAccessType.typeName}
                onChange={handleInputChange}
                required
                className="custom-hover-border"
              />
            </Form.Group>
            <Form.Group controlId="formDescription">
              <Form.Label>Description</Form.Label>
              <Form.Control
                type="text"
                name="description"
                value={currentAccessType.description}
                onChange={handleInputChange}
                className="custom-hover-border"
              />
            </Form.Group>
            <Form.Group controlId="formActive">
              <Form.Check
                type="checkbox"
                label="Active?"
                name="isActive"
                checked={currentAccessType.isActive}
                onChange={handleInputChange}
                className="custom-checkbox"
              />
            </Form.Group>
            <Modal.Footer>
              <Button
                variant="primary"
                className="custom_button px-4"
                onClick={() => setShowAddEditModal(false)}
              >
                Close
              </Button>
              <Button
                variant="primary"
                className="custom_button px-4"
                type="submit"
              >
                {isEditing ? "Update" : "Add"}
              </Button>
            </Modal.Footer>
          </Form>
        </Modal.Body>
      </Modal>
    </div>
      )}
    </div>
    
  );
}

export default AccessTypeManagement;
