import React, { useState, useEffect, useRef } from "react";
import { Box, Button, Typography } from "@mui/material";
import { DataGrid, GridToolbarContainer } from "@mui/x-data-grid";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faEllipsisV } from "@fortawesome/free-solid-svg-icons";
import "./UserGroupMaintance.css";

const api = process.env.REACT_APP_API_BASE_URL;

function CustomToolbar({ apiRef, handleModal }) {
  const handleGoToPage1 = () => {
    if (apiRef.current) {
      apiRef.current.setPage(1);
    }
  };

  return (
    <GridToolbarContainer className="grid-toolbar">
      <Button 
        variant="contained" 
        className="toolbar-button"
        onClick={handleGoToPage1}
      >
        Go to page 1
      </Button>
      <Button 
        variant="contained" 
        className="toolbar-button add-button"
        onClick={handleModal}
      >
        Add User Group
      </Button>
    </GridToolbarContainer>
  );
}

function UserMaintance() {
  const [userGroups, setUserGroups] = useState([]);
  const [selectedUserGroup, setSelectedUserGroup] = useState(null);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const apiRef = useRef(null);

  useEffect(() => {
    const fetchData = async () => {
      const token = localStorage.getItem("token");
      try {
        const response = await fetch(`${api}/api/getAllUsrGrp`, {
          headers: { authorization: `bearer ${token}` },
        });
        const data = await response.json();
        const userGroupsWithIds = data.map((group, index) => ({
          ...group,
          id: index + 1,
        }));
        setUserGroups(userGroupsWithIds);
      } catch (error) {
        console.error("Error fetching data:", error);
      }
    };

    fetchData();
  }, []);

  const handleThreeDotsClick = (usrGrp) => {
    setSelectedUserGroup(usrGrp === selectedUserGroup ? null : usrGrp);
  };

  const handleDelete = async (usrGrp) => {
    try {
      const response = await fetch(`${api}/api/delete_usrgrp/${usrGrp}`, {
        method: "DELETE",
      });
      if (response.ok) {
        setUserGroups(userGroups.filter((group) => group.usrGrp !== usrGrp));
        console.log("User group deleted successfully:", usrGrp);
      } else {
        console.error("Failed to delete user group:", response.statusText);
      }
    } catch (error) {
      console.error("Error deleting user group:", error);
    }
  };

  const handleModal = () => {
    setIsModalOpen(true);
  };

  const columns = [
    {
      field: "usrGrp",
      headerName: "User Group ID",
      width: 150,
      headerClassName: "custom-header",
      cellClassName: "custom-cell",
    },
    {
      field: "groupName",
      headerName: "Group Name",
      width: 150,
      headerClassName: "custom-header",
      cellClassName: "custom-cell",
    },
    {
      field: "groupDesc",
      headerName: "Group Description",
      width: 150,
      headerClassName: "custom-header",
      cellClassName: "custom-cell",
    },
    {
      field: "createby",
      headerName: "Create By",
      width: 100,
      headerClassName: "custom-header",
      cellClassName: "custom-cell",
    },
    {
      field: "createdate",
      headerName: "Create Date",
      width: 100,
      headerClassName: "custom-header",
      cellClassName: "custom-cell",
    },
    {
      field: "updatedate",
      headerName: "Update Date",
      width: 100,
      headerClassName: "custom-header",
      cellClassName: "custom-cell",
    },
    {
      field: "updateby",
      headerName: "Update By",
      width: 100,
      headerClassName: "custom-header",
      cellClassName: "custom-cell",
    },
    {
      field: "status",
      headerName: "Status",
      width: 100,
      headerClassName: "custom-header",
      cellClassName: "custom-cell",
    },
    {
      field: "grouplevel",
      headerName: "Group Level",
      width: 100,
      headerClassName: "custom-header",
      cellClassName: "custom-cell",
    },
    {
      field: "actions",
      headerName: "Actions",
      width: 150,
      renderCell: ({ row }) => (
        <div style={{ position: 'relative' }}>
          <div
            className="three-dots"
            onClick={() => handleThreeDotsClick(row.usrGrp)}
          >
            <FontAwesomeIcon icon={faEllipsisV} />
          </div>
          {selectedUserGroup === row.usrGrp && (
            <div className="popover">
              <button onClick={() => handleDelete(row.usrGrp)}>Delete</button>
            </div>
          )}
        </div>
      ),
    },
  ];

  return (
    <div className="user-group-maintenance-container">
      <Typography variant="h4" className="main-title" gutterBottom>
        User Group Maintenance
      </Typography>

      <Box className="data-grid-container" sx={{ height: 500, width: '100%' }}>
        <DataGrid
          rows={userGroups}
          columns={columns}
          components={{
            Toolbar: () => (
              <CustomToolbar
                apiRef={apiRef}
                handleModal={handleModal}
              />
            ),
          }}
          pageSize={10}
          rowsPerPageOptions={[10]}
          onGridReady={(gridApi) => {
            apiRef.current = gridApi;
          }}
        />
      </Box>

      {isModalOpen && (
        <div className="modal-overlay">
          <div className="modal-content">
            <Typography variant="h5" className="modal-title">
              Add New User Group
            </Typography>
            {/* Modal form content here */}
            <div className="modal-actions">
              <Button 
                variant="contained" 
                onClick={() => setIsModalOpen(false)}
                className="toolbar-button"
              >
                Close
              </Button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

export default UserMaintance;