import React, { useState, useEffect } from "react";
import {
  Button,
  Container,
  Checkbox,
  Modal,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  TextField,
  FormControlLabel,
  Typography,
  Pagination,
  IconButton,
  InputAdornment,
  Menu,
  MenuItem,
  Box,
  Divider
} from "@mui/material";
import {
  Edit as EditIcon,
  Delete as DeleteIcon,
  Add as AddIcon,
  Menu as MenuIcon,
  Close as CloseIcon,
  Search as SearchIcon,
  Check as CheckIcon,
  Book as BookIcon
} from "@mui/icons-material";
import { toast } from "react-toastify";
import { CircularProgress } from "@mui/material";

const api =process.env.REACT_APP_API_BASE_URL;

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);
  const [anchorEl, setAnchorEl] = useState(null);
  const [columnsAnchorEl, setColumnsAnchorEl] = useState(null);

  const openColumnsMenu = (event) => {
    setColumnsAnchorEl(event.currentTarget);
  };

  const closeColumnsMenu = () => {
    setColumnsAnchorEl(null);
  };

  const openRecordsMenu = (event) => {
    setAnchorEl(event.currentTarget);
  };

  const closeRecordsMenu = () => {
    setAnchorEl(null);
  };

  useEffect(() => {
    const fetchAccessTypes = async () => {
      const token = localStorage.getItem("token");
      const apiUrl = `${api}/token/access_type/Accesstype`;
      
      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);
        setLoading(false);
      } catch (error) {
        console.error("Error fetching access types:", error);
        toast.error("Failed to fetch access types");
        setLoading(false);
      }
    };

    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 handleSubmit = async (event) => {
    event.preventDefault();
    const token = localStorage.getItem("token");
    const apiUrl = isEditing 
      ? `${api}/access_type/Accesstype/${currentAccessType.id}`
      : `${api}/access_type/Accesstype`;

    try {
      const method = isEditing ? "PUT" : "POST";
      const response = await fetch(apiUrl, {
        method,
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify(currentAccessType),
      });

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

      const data = await response.json();
      
      if (isEditing) {
        setAccessTypes(accessTypes.map(type => 
          type.id === currentAccessType.id ? data : type
        ));
        toast.success("Access type updated successfully!");
      } else {
        setAccessTypes([...accessTypes, data]);
        toast.success("Access type added successfully!");
      }
      
      setShowAddEditModal(false);
    } catch (error) {
      console.error("Error submitting access type:", error);
      toast.error("Failed to submit access type");
    }
  };

  const handleDelete = async (id) => {
    const token = localStorage.getItem("token");
    const apiUrl = `${api}/access_type/Accesstype/${id}`;
    
    try {
      const response = await fetch(apiUrl, {
        method: "DELETE",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
        },
      });

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

      setAccessTypes(accessTypes.filter(type => type.id !== id));
      toast.success("Access type deleted successfully!");
    } catch (error) {
      console.error("Error deleting access type:", error);
      toast.error("Failed to delete access type");
    }
  };

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

  const handleClose = () => {
    setShowAddEditModal(false);
  };

  const filteredAccessTypes = accessTypes.filter(item =>
    item.typeName && item.typeName.toLowerCase().includes(searchQuery.toLowerCase())
  );

  const slicedAccessTypes = filteredAccessTypes.slice(
    (currentPage - 1) * recordsPerPage,
    currentPage * recordsPerPage
  );

  const totalPages = Math.ceil(filteredAccessTypes.length / recordsPerPage);

  const handlePageChange = (event, value) => {
    setCurrentPage(value);
  };

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

  return (
    <Container maxWidth="xl" sx={{ mt: 4 }}>
      {loading ? (
    <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '200px' }}>
  <CircularProgress />
</Box>  
    ) : (
        <>
          <Box sx={{ display: "flex", justifyContent: "space-between", alignItems: "center", mb: 3 }}>
            <Typography variant="h4" component="h1" sx={{ fontWeight: 'bold' }}>
              Access Type
            </Typography>
          </Box>

          <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
            <TextField
              placeholder="Search"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              InputProps={{
                startAdornment: (
                  <InputAdornment position="start">
                    <SearchIcon />
                  </InputAdornment>
                ),
                sx: {
                  borderRadius: '10px',
                  boxShadow: '0px 4px 12px rgba(0, 0, 0, 0.1)',
                  width: '100%',
                  maxWidth: '528px',
                }
              }}
              sx={{ flexGrow: 1, maxWidth: '528px' }}
            />

            <Box>
              <IconButton onClick={() => openModal()} sx={{ mr: 2, color: 'primary.main' }}>
                <AddIcon />
              </IconButton>
              <IconButton onClick={openColumnsMenu} sx={{ color: 'primary.main' }}>
                <MenuIcon />
              </IconButton>
            </Box>
          </Box>

          <TableContainer component={Paper} sx={{ boxShadow: '0px 4px 12px rgba(0, 0, 0, 0.1)', mb: 3 }}>
            <Table>
              <TableHead sx={{ backgroundColor: '#f8f9fa' }}>
                <TableRow>
                  {Object.entries(visibleColumns).map(([key, visible]) =>
                    visible && (
                      <TableCell key={key} sx={{ fontWeight: 'bold' }}>
                        {key.charAt(0).toUpperCase() + key.slice(1)}
                      </TableCell>
                    )
                  )}
                </TableRow>
              </TableHead>
              <TableBody>
                {slicedAccessTypes.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={Object.keys(visibleColumns).filter(key => visibleColumns[key]).length} align="center">
                      No Data Available
                    </TableCell>
                  </TableRow>
                ) : (
                  slicedAccessTypes.map((type) => (
                    <TableRow key={type.id}>
                      {Object.entries(visibleColumns).map(([key, visible]) =>
                        visible && (
                          <TableCell key={key}>
                            {key === "actions" ? (
                              <Box>
                                <IconButton onClick={() => openModal(type)} sx={{ color: 'success.main', mr: 1 }}>
                                  <EditIcon />
                                </IconButton>
                                <IconButton onClick={() => handleDelete(type.id)} sx={{ color: 'error.main' }}>
                                  <DeleteIcon />
                                </IconButton>
                              </Box>
                            ) : key === "isActive" ? (
                              <Typography
                                variant="body2"
                                sx={{
                                  color: type.isActive ? 'success.main' : 'error.main',
                                  backgroundColor: type.isActive ? 'rgba(0, 200, 83, 0.1)' : 'rgba(255, 0, 0, 0.1)',
                                  px: 1,
                                  py: 0.5,
                                  borderRadius: 1,
                                  display: 'inline-block'
                                }}
                              >
                                {type.isActive ? "Active" : "Inactive"}
                              </Typography>
                            ) : (
                              type[key]
                            )}
                          </TableCell>
                        )
                      )}
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </TableContainer>

          <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mt: 2 }}>
            <Box>
              <Button
                variant="outlined"
                onClick={openColumnsMenu}
                startIcon={<MenuIcon />}
                sx={{ mr: 2 }}
              >
                Manage Columns
              </Button>
              
              <Menu
                anchorEl={columnsAnchorEl}
                open={Boolean(columnsAnchorEl)}
                onClose={closeColumnsMenu}
              >
                {Object.keys(visibleColumns).map((column) => (
                  <MenuItem key={column} onClick={() => toggleColumn(column)}>
                    <Checkbox checked={visibleColumns[column]} />
                    <Typography>
                      {column.charAt(0).toUpperCase() + column.slice(1)}
                    </Typography>
                  </MenuItem>
                ))}
              </Menu>

              <Button
                variant="outlined"
                onClick={openRecordsMenu}
                startIcon={<BookIcon />}
              >
                Records
              </Button>
              
              <Menu
                anchorEl={anchorEl}
                open={Boolean(anchorEl)}
                onClose={closeRecordsMenu}
              >
                {[5, 10, 20, 50].map((number) => (
                  <MenuItem 
                    key={number} 
                    onClick={() => handleRecordsPerPageChange(number)}
                    selected={recordsPerPage === number}
                  >
                    {number}
                    {recordsPerPage === number && <CheckIcon sx={{ ml: 1 }} />}
                  </MenuItem>
                ))}
              </Menu>
            </Box>

            <Pagination
              count={totalPages}
              page={currentPage}
              onChange={handlePageChange}
              color="primary"
              shape="rounded"
            />
          </Box>

          {/* Add/Edit Modal */}
          <Modal
            open={showAddEditModal}
            onClose={handleClose}
            aria-labelledby="modal-modal-title"
            aria-describedby="modal-modal-description"
          >
            <Box sx={{
              position: 'absolute',
              top: '50%',
              left: '50%',
              transform: 'translate(-50%, -50%)',
              width: 400,
              bgcolor: 'background.paper',
              boxShadow: 24,
              p: 4,
              borderRadius: 1
            }}>
              <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
                <Typography id="modal-modal-title" variant="h6" component="h2">
                  {isEditing ? "Edit Access Type" : "Add Access Type"}
                </Typography>
                <IconButton onClick={handleClose}>
                  <CloseIcon />
                </IconButton>
              </Box>
              
              <Divider sx={{ mb: 3 }} />
              
              <form onSubmit={handleSubmit}>
                <TextField
                  fullWidth
                  label="Type Name"
                  name="typeName"
                  value={currentAccessType.typeName}
                  onChange={handleInputChange}
                  required
                  sx={{ mb: 2 }}
                />
                
                <TextField
                  fullWidth
                  label="Description"
                  name="description"
                  value={currentAccessType.description}
                  onChange={handleInputChange}
                  sx={{ mb: 2 }}
                />
                
                <FormControlLabel
                  control={
                    <Checkbox
                      name="isActive"
                      checked={currentAccessType.isActive}
                      onChange={handleInputChange}
                    />
                  }
                  label="Active?"
                  sx={{ mb: 3 }}
                />
                
                <Box sx={{ display: 'flex', justifyContent: 'flex-end', gap: 2 }}>
                  <Button variant="outlined" onClick={handleClose}>
                    Close
                  </Button>
                  <Button variant="contained" type="submit">
                    {isEditing ? "Update" : "Add"}
                  </Button>
                </Box>
              </form>
            </Box>
          </Modal>
        </>
      )}
    </Container>
  );
}

export default AccessTypeManagement;