import React, { useState, useEffect } from "react";
import {
  Box,
  Button,
  TextField,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  IconButton,
  Menu,
  MenuItem,
  Checkbox,
  FormControlLabel,
  Pagination,
  Modal,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  FormGroup,
  Switch,
  Tooltip,
  Typography,
  InputAdornment,
  Select,
  FormControl,
  InputLabel,
  CircularProgress,
} from "@mui/material";
import {
  Add,
  Search,
  Settings,
  Edit,
  Delete,
  Download,
  Upload,
  Close,
  Visibility,
  VisibilityOff,
  Check,
} from "@mui/icons-material";
import { toast } from "react-toastify";
import * as XLSX from "xlsx";
import { getAllUsers, createUser, updateUser, deleteUser } from "../../ApiServices/Usermaintenanceapi";

function UserMaintenanceView() {
  // State management
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState("");
  const [currentPage, setCurrentPage] = useState(1);
  const [recordsPerPage, setRecordsPerPage] = useState(10);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isImportModalOpen, setIsImportModalOpen] = useState(false);
  const [isEditing, setIsEditing] = useState(false);
  const [anchorEl, setAnchorEl] = useState(null);
  const [columnMenuAnchor, setColumnMenuAnchor] = useState(null);

  // User data state
  const [userData, setUserData] = useState({
    userId: "",
    username: "",
    fullName: "",
    email: "",
    mob_no: "",
    active: true,
    usrGrpId: "",
  });

  // Column visibility configuration
  const [visibleColumns, setVisibleColumns] = useState({
    userId: true,
    username: true,
    fullName: true,
    email: true,
    mob_no: true,
    active: true,
    usrGrpId: true,
    actions: true,
  });

  // Fetch users on component mount
  useEffect(() => {
    const fetchUsers = async () => {
      try {
        setLoading(true);
        const response = await getAllUsers();
        setUsers(response.data || []);
      } catch (error) {
        console.error("Error fetching users:", error);
        toast.error("Failed to fetch users");
      } finally {
        setLoading(false);
      }
    };

    fetchUsers();
  }, []);

  // Filter users based on search query
  const filteredUsers = users.filter((user) =>
    user.username.toLowerCase().includes(searchQuery.toLowerCase())
  );

  // Pagination logic
  const totalPages = Math.ceil(filteredUsers.length / recordsPerPage);
  const paginatedUsers = filteredUsers.slice(
    (currentPage - 1) * recordsPerPage,
    currentPage * recordsPerPage
  );

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

  // Modal handlers
  const handleOpenModal = (user = null) => {
    if (user) {
      setUserData(user);
      setIsEditing(true);
    } else {
      setUserData({
        userId: "",
        username: "",
        fullName: "",
        email: "",
        mob_no: "",
        active: true,
        usrGrpId: "",
      });
      setIsEditing(false);
    }
    setIsModalOpen(true);
  };

  const handleCloseModal = () => {
    setIsModalOpen(false);
  };

  // Form input handler
  const handleInputChange = (e) => {
    const { name, value, type, checked } = e.target;
    setUserData((prev) => ({
      ...prev,
      [name]: type === "checkbox" ? checked : value,
    }));
  };

  // Form submission handler
  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      if (isEditing) {
        await updateUser(userData);
        toast.success("User updated successfully");
      } else {
        await createUser(userData);
        toast.success("User added successfully");
      }
      // Refresh user list
      const response = await getAllUsers();
      setUsers(response.data || []);
      handleCloseModal();
    } catch (error) {
      console.error("Error saving user:", error);
      toast.error("There was an error while submitting the USER.");
    }
  };

  // Delete user handler
  const handleDelete = async (userId) => {
    try {
      await deleteUser(userId);
      setUsers(users.filter((user) => user.userId !== userId));
      toast.success("User deleted successfully");
    } catch (error) {
      console.error("Error deleting user:", error);
      toast.error("Failed to delete user");
    }
  };

  // Excel export handler
  const exportToExcel = () => {
    const worksheet = XLSX.utils.json_to_sheet(users);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, "UserDetails");
    XLSX.writeFile(workbook, "UserMaintenance.xlsx");
  };

  // Excel import handlers
  const handleFileChange = (e) => {
    // Implement your file import logic here
  };

  const handleImport = () => {
    // Implement your import logic here
    toast.success("File imported successfully");
    setIsImportModalOpen(false);
  };

  if (loading) {
    return (
      <Box display="flex" justifyContent="center" alignItems="center" minHeight="80vh">
        <CircularProgress />
      </Box>
    );
  }

  return (
    <Box sx={{ p: 3, marginTop: "7rem" }}>
      {/* Header and Search */}
      <Box sx={{ display: "flex", justifyContent: "space-between", mb: 3 }}>
        <Typography variant="h4">User Maintenance</Typography>
        
        <Box sx={{ display: "flex", gap: 2 }}>
          <TextField
            size="small"
            placeholder="Search"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            InputProps={{
              startAdornment: (
                <InputAdornment position="start">
                  <Search />
                </InputAdornment>
              ),
            }}
          />

          <Tooltip title="Download template">
            <IconButton onClick={exportToExcel}>
              <Download />
            </IconButton>
          </Tooltip>

          <Tooltip title="Import users">
            <IconButton onClick={() => setIsImportModalOpen(true)}>
              <Upload />
            </IconButton>
          </Tooltip>

          <Button
            variant="contained"
            startIcon={<Add />}
            onClick={() => handleOpenModal()}
          >
            Add User
          </Button>
        </Box>
      </Box>

      {/* Table */}
      <TableContainer component={Paper}>
        <Table>
          <TableHead>
            <TableRow>
              {Object.entries(visibleColumns).map(
                ([key, visible]) =>
                  visible && (
                    <TableCell key={key}>
                      {key.charAt(0).toUpperCase() + key.slice(1).replace(/_/g, " ")}
                    </TableCell>
                  )
              )}
            </TableRow>
          </TableHead>
          <TableBody>
            {paginatedUsers.length === 0 ? (
              <TableRow>
                <TableCell colSpan={Object.keys(visibleColumns).length} align="center">
                  No users found
                </TableCell>
              </TableRow>
            ) : (
              paginatedUsers.map((user) => (
                <TableRow key={user.userId}>
                  {Object.entries(visibleColumns).map(([key, visible]) => {
                    if (!visible) return null;

                    if (key === "actions") {
                      return (
                        <TableCell key={key}>
                          <Tooltip title="Edit">
                            <IconButton onClick={() => handleOpenModal(user)}>
                              <Edit color="primary" />
                            </IconButton>
                          </Tooltip>
                          <Tooltip title="Delete">
                            <IconButton onClick={() => handleDelete(user.userId)}>
                              <Delete color="error" />
                            </IconButton>
                          </Tooltip>
                        </TableCell>
                      );
                    } else if (key === "active") {
                      return (
                        <TableCell key={key}>
                          <Switch
                            checked={user.active}
                            readOnly
                            color="primary"
                          />
                        </TableCell>
                      );
                    } else {
                      return <TableCell key={key}>{user[key]}</TableCell>;
                    }
                  })}
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </TableContainer>

      {/* Pagination and Column Controls */}
      <Box sx={{ display: "flex", justifyContent: "space-between", mt: 2 }}>
        <Box>
          <Button
            onClick={(e) => setColumnMenuAnchor(e.currentTarget)}
            startIcon={<Settings />}
          >
            Manage Columns
          </Button>
          <Menu
            anchorEl={columnMenuAnchor}
            open={Boolean(columnMenuAnchor)}
            onClose={() => setColumnMenuAnchor(null)}
          >
            {Object.keys(visibleColumns).map((column) => (
              <MenuItem key={column}>
                <FormControlLabel
                  control={
                    <Checkbox
                      checked={visibleColumns[column]}
                      onChange={() => toggleColumn(column)}
                    />
                  }
                  label={column.charAt(0).toUpperCase() + column.slice(1).replace(/_/g, " ")}
                />
              </MenuItem>
            ))}
          </Menu>
        </Box>

        <Box sx={{ display: "flex", alignItems: "center", gap: 2 }}>
          <FormControl size="small" sx={{ minWidth: 120 }}>
            <InputLabel>Rows per page</InputLabel>
            <Select
              value={recordsPerPage}
              label="Rows per page"
              onChange={(e) => {
                setRecordsPerPage(e.target.value);
                setCurrentPage(1);
              }}
            >
              {[5, 10, 25, 50].map((option) => (
                <MenuItem key={option} value={option}>
                  {option}
                </MenuItem>
              ))}
            </Select>
          </FormControl>

          <Pagination
            count={totalPages}
            page={currentPage}
            onChange={(e, page) => setCurrentPage(page)}
            color="primary"
          />
        </Box>
      </Box>

      {/* Add/Edit User Modal */}
      <Dialog open={isModalOpen} onClose={handleCloseModal} fullWidth maxWidth="sm">
        <DialogTitle>
          {isEditing ? "Edit User" : "Add New User"}
          <IconButton
            onClick={handleCloseModal}
            sx={{
              position: "absolute",
              right: 8,
              top: 8,
            }}
          >
            <Close />
          </IconButton>
        </DialogTitle>
        <DialogContent>
          <form onSubmit={handleSubmit}>
            <TextField
              margin="normal"
              fullWidth
              label="Username"
              name="username"
              value={userData.username}
              onChange={handleInputChange}
              required
            />
            <TextField
              margin="normal"
              fullWidth
              label="Full Name"
              name="fullName"
              value={userData.fullName}
              onChange={handleInputChange}
              required
            />
            <TextField
              margin="normal"
              fullWidth
              label="Email"
              name="email"
              type="email"
              value={userData.email}
              onChange={handleInputChange}
              required
            />
            <TextField
              margin="normal"
              fullWidth
              label="Mobile Number"
              name="mob_no"
              value={userData.mob_no}
              onChange={handleInputChange}
            />
            <TextField
              margin="normal"
              fullWidth
              label="User Group"
              name="usrGrpId"
              value={userData.usrGrpId}
              onChange={handleInputChange}
            />
            <FormGroup>
              <FormControlLabel
                control={
                  <Switch
                    name="active"
                    checked={userData.active}
                    onChange={handleInputChange}
                  />
                }
                label="Active"
              />
            </FormGroup>
          </form>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCloseModal}>Cancel</Button>
          <Button onClick={handleSubmit} variant="contained">
            {isEditing ? "Save Changes" : "Add User"}
          </Button>
        </DialogActions>
      </Dialog>

      {/* Import Modal */}
      <Dialog open={isImportModalOpen} onClose={() => setIsImportModalOpen(false)}>
        <DialogTitle>
          Import Users
          <IconButton
            onClick={() => setIsImportModalOpen(false)}
            sx={{
              position: "absolute",
              right: 8,
              top: 8,
            }}
          >
            <Close />
          </IconButton>
        </DialogTitle>
        <DialogContent>
          <input
            type="file"
            accept=".xlsx, .xls, .csv"
            onChange={handleFileChange}
          />
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setIsImportModalOpen(false)}>Cancel</Button>
          <Button onClick={handleImport} variant="contained">
            Import
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
}

export default UserMaintenanceView;