import AddIcon from "@mui/icons-material/Add";
import EditIcon from "@mui/icons-material/Edit";
import DeleteIcon from "@mui/icons-material/Delete";
import CloseIcon from "@mui/icons-material/Close";
import PersonAddIcon from "@mui/icons-material/PersonAdd";
import {
  Box,
  Button,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  Divider,
  IconButton,
  TextField,
  Typography,
} from "@mui/material";
import React, { useMemo, useRef, useState } from "react";
import CustomBreadcrumbs from "../../components/CustomBreadcrumbs";
import PageHeader from "../../components/PageHeader";
import { createAdmin, getAdmins, updateAdmin, deleteAdmin } from "../../services/auth.services";
import { pushNotification } from "../../utils/notification";
import { NOTIFICATION } from "../../constants";
import { useStyles } from "./staffStyles";
import Table from "../../components/Table";

const StaffManagement = () => {
  const classes = useStyles();
  const ref = useRef(null);
  const tableRef = useRef(null);
  
  // State for form fields
  const [firstName, setFirstName] = useState("");
  const [lastName, setLastName] = useState("");
  const [email, setEmail] = useState("");
  const [emailError, setEmailError] = useState("");
  const [isEditMode, setIsEditMode] = useState(false);
  const [editId, setEditId] = useState(null);

  // State for dialog
  const [openDialog, setOpenDialog] = useState(false);
  
  // State for delete confirmation dialog
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [deleteId, setDeleteId] = useState(null);

  // Email validation function
  const validateEmail = (email) => {
    const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return regex.test(email);
  };

  // Handle dialog open/close
  const handleOpenDialog = () => {
    setOpenDialog(true);
  };

  const handleCloseDialog = () => {
    setOpenDialog(false);
    // Clear form
    setFirstName("");
    setLastName("");
    setEmail("");
    setEmailError("");
    setIsEditMode(false);
    setEditId(null);
  };

  // Handle form submission
  const handleSubmit = async (e) => {
    e.preventDefault();

    // For edit mode, only username is required
    if (!isEditMode) {
      // Validate email
      if (!validateEmail(email)) {
        setEmailError("Please enter a valid email address");
        return;
      }
    }

    let response;
    
    if (isEditMode) {
      // In edit mode, only update the username
      const payload = {
        username: `${firstName} ${lastName}`,
      };
      
      response = await updateAdmin(payload, editId);
    } else {
      // In create mode, include both username and email
      const payload = {
        username: `${firstName} ${lastName}`,
        email,
      };
      
      response = await createAdmin(payload);
    }

    if (response?.data?.data) {
      pushNotification(
        `Admin ${isEditMode ? 'updated' : 'created'} successfully!`, 
        NOTIFICATION.SUCCESS
      );
      
      // Refresh the table
      if (tableRef.current) {
        tableRef.current.reFetchData();
      }
    } else {
      pushNotification(response?.data?.message, NOTIFICATION.ERROR);
    }

    // Close dialog
    handleCloseDialog();
  };

  const getData = async (filters) => {
    try {
      // Remove the type parameter since it's not defined
      let params = {
        ...filters,
      };

      const resp = await getAdmins(params);

      return {
        data: resp?.data?.data?.data,
        rowCount: resp?.data?.total || 0,
      };
    } catch (error) {
      console.error("Error fetching admins:", error);
      return {
        data: [],
        rowCount: 0,
      };
    }
  };

  const handleEdit = (row) => {
    setIsEditMode(true);
    setEditId(row.original.id);
    
    // Split the username into first and last name
    const nameParts = row.original.username.split(' ');
    setFirstName(nameParts[0] || '');
    setLastName(nameParts.slice(1).join(' ') || '');
    
    // Set email but make it read-only in the form
    setEmail(row.original.email);
    
    setOpenDialog(true);
  }

  // Open delete confirmation dialog
  const openDeleteConfirmation = (id) => {
    setDeleteId(id);
    setDeleteDialogOpen(true);
  };

  // Handle delete after confirmation
  const handleDelete = async () => {
    try {
      const resp = await deleteAdmin(deleteId);
      pushNotification(
        "Admin deleted successfully", 
        NOTIFICATION.SUCCESS
      );
    } catch (error) {
      console.error("Error deleting admin:", error);
      pushNotification(
        "Failed to delete admin", 
        NOTIFICATION.ERROR
      );
    }

    // Close the dialog and refresh the table
    setDeleteDialogOpen(false);
    setDeleteId(null);
    
    if (tableRef.current) {
      tableRef.current.reFetchData();
    }
  };

  // ...................breadcrumbs array........................
  const breadcrumbs = [
    {
      label: "Dashboard",
      path: "/",
    },
    {
      label: "Staff Management",
      path: "/staff",
    },
  ];

  const columns = useMemo(() => [
    {
      size: 100,
      header: "Sr. No.",
      Cell: (props) => {
        const tableState = props?.table?.getState();
        const serialNumber = (
          props?.row?.index +
          1 +
          tableState?.pagination?.pageIndex * tableState?.pagination?.pageSize
        )
          ?.toString()
          ?.padStart(1, "0");
        return <span>{serialNumber}</span>;
      },
      enableSorting: false,
    },
    {
      size: 280,
      accessorKey: "username",
      header: "User Name",
      enableColumnFilter: false,
    },
    {
      size: 220,
      accessorKey: "email",
      header: "User Email Address",
      enableColumnFilter: false,
    },
  ]);

  return (
    <Box>
      <PageHeader
        pageTitle="Staff Management"
        // hideAddButton
        addButtonIcon={<AddIcon />}
        onAddButtonClick={handleOpenDialog}
      />
      <CustomBreadcrumbs breadcrumbs={breadcrumbs} />
      <Box className={classes.tableMainDiv}>
        <Box>
          <Table
            hideTopToolbar
            columns={columns}
            getData={getData}
            options={{
              enableRowSelection: false,
              showTopBar: false,
              showFilters: true,
            }}
            searchText="Staff"
            showSearchBox={true}
            showAction={true}
            ref={tableRef}
            actions={[
              {
                onClick: (row) => handleEdit(row),
                text: "Edit",
                icon: <EditIcon alt="Edit" />,
              },
              {
                onClick: (row) => openDeleteConfirmation(row.original.id),
                text: "Delete",
                icon: <DeleteIcon alt="Delete" />,
              },
            ]}
          />
        </Box>
      </Box>
      <Box className={classes.tableMainDiv}>
        <Dialog
          open={openDialog}
          onClose={handleCloseDialog}
          maxWidth="sm"
          fullWidth
        >
          <DialogTitle
            sx={{
              display: "flex",
              alignItems: "center",
              justifyContent: "space-between",
              pb: 1,
            }}
          >
            <Box sx={{ display: "flex", alignItems: "center" }}>
              <PersonAddIcon sx={{ mr: 1, color: "#0a2d6b" }} />
              <Typography
                variant="h6"
                component="span"
                sx={{ fontWeight: "bold", color: "#0a2d6b" }}
              >
                {isEditMode ? "Edit Staff" : "Add New Staff"}
              </Typography>
            </Box>
            <IconButton onClick={handleCloseDialog} size="small">
              <CloseIcon />
            </IconButton>
          </DialogTitle>

          <Divider />

          <DialogContent>
            <Box component="form" onSubmit={handleSubmit} sx={{ mt: 1 }}>
              <TextField
                label="First Name"
                fullWidth
                margin="normal"
                value={firstName}
                onChange={(e) => setFirstName(e.target.value)}
                placeholder="First Name"
                required
                InputLabelProps={{
                  shrink: true,
                }}
              />

              <TextField
                label="Last Name"
                fullWidth
                margin="normal"
                value={lastName}
                onChange={(e) => setLastName(e.target.value)}
                placeholder="Last Name"
                required
                InputLabelProps={{
                  shrink: true,
                }}
              />

              {!isEditMode ? (
                <TextField
                  label="Email Address"
                  fullWidth
                  margin="normal"
                  type="email"
                  value={email}
                  onChange={(e) => {
                    setEmail(e.target.value);
                    setEmailError("");
                  }}
                  placeholder="Email Address"
                  error={!!emailError}
                  helperText={emailError}
                  required
                  InputLabelProps={{
                    shrink: true,
                  }}
                />
              ) : (
                <TextField
                  label="Email Address"
                  fullWidth
                  margin="normal"
                  type="email"
                  value={email}
                  disabled
                  InputLabelProps={{
                    shrink: true,
                  }}
                />
              )}
            </Box>
          </DialogContent>

          <DialogActions sx={{ px: 3, pb: 3 }}>
            <Button
              variant="contained"
              color="error"
              fullWidth
              onClick={handleSubmit}
              sx={{
                py: 1.5,
                backgroundColor: "#ff3366",
                "&:hover": {
                  backgroundColor: "#e61653",
                },
              }}
            >
              {isEditMode ? "Update Admin" : "Add Admin"}
            </Button>
          </DialogActions>
        </Dialog>

        {/* Delete Confirmation Dialog */}
        <Dialog
          open={deleteDialogOpen}
          onClose={() => setDeleteDialogOpen(false)}
          maxWidth="xs"
          fullWidth
          PaperProps={{
            sx: {
              borderRadius: "12px",
              overflow: "hidden",
            },
          }}
        >
          <DialogTitle
            sx={{
              padding: "16px 24px",
              backgroundColor: (theme) => theme.palette.error.main,
              color: "white",
              fontWeight: "bold",
              position: "relative",
            }}
          >
            Confirm Deletion
            <IconButton
              aria-label="close"
              onClick={() => setDeleteDialogOpen(false)}
              sx={{
                position: "absolute",
                right: 8,
                top: 8,
                color: "white",
              }}
            >
              <CloseIcon />
            </IconButton>
          </DialogTitle>

          <DialogContent sx={{ padding: "24px 24px 16px", mt: 1 }}>
            <Typography variant="body1">
              Are you sure you want to delete this admin? This action cannot be undone.
            </Typography>
          </DialogContent>

          <DialogActions
            sx={{
              padding: "16px 24px",
              borderTop: "1px solid",
              borderColor: (theme) => theme.palette.grey[200],
              justifyContent: "space-between",
            }}
          >
            <Button
              onClick={() => setDeleteDialogOpen(false)}
              sx={{
                color: (theme) => theme.palette.grey[700],
                fontWeight: "medium",
              }}
            >
              Cancel
            </Button>
            <Button
              onClick={handleDelete}
              variant="contained"
              color="error"
              sx={{
                borderRadius: "8px",
                px: 3,
              }}
            >
              Delete
            </Button>
          </DialogActions>
        </Dialog>
      </Box>
    </Box>
    // <Container maxWidth="lg" sx={{ py: 4 }}>
    //   {/* <Typography
    //     variant="h4"
    //     component="h1"
    //     gutterBottom
    //     sx={{ fontWeight: 'bold', mb: 4, color: '#0a2d6b' }}
    //   >
    //     Staff Management
    //   </Typography> */}

    //   <PageHeader
    //     pageTitle="Staff Management"
    //     hideAddButton
    //     // addButtonTitle="Add Staff"
    //     // onAddButtonClick={toggle}
    //     // addButtonIcon={<img src={AddIcon} />}
    //     // addButtonDisabled={false}
    //     // permissionName={'CREATE_USERS'}
    //     // infiniteDropdown
    //   />

    //   <CustomBreadcrumbs breadcrumbs={breadcrumbs} />

    //   <Paper elevation={3} sx={{ p: 0, mb: 4, overflow: 'hidden' }}>
    //     {/* Staff List Header with Add Button */}
    //     <Box
    //       sx={{
    //         display: 'flex',
    //         justifyContent: 'space-between',
    //         alignItems: 'center',
    //         p: 3,
    //       }}
    //     >
    //       <Typography variant="h6" component="h2" sx={{ fontWeight: 'bold' }}>
    //         Staff List
    //       </Typography>

    //       <Button
    //         variant="contained"
    //         color="error"
    //         startIcon={<AddIcon />}
    //         onClick={handleOpenDialog}
    //         sx={{
    //           borderRadius: 50,
    //           textTransform: 'none',
    //           backgroundColor: '#ff3366',
    //           '&:hover': {
    //             backgroundColor: '#e61653',
    //           },
    //         }}
    //       >
    //         Add Admin
    //       </Button>
    //     </Box>

    //     {/* Search Box */}
    //     <Box sx={{ px: 3, pb: 2 }}>
    //       <TextField
    //         placeholder="Search user here"
    //         fullWidth
    //         size="small"
    //         value={searchQuery}
    //         onChange={(e) => setSearchQuery(e.target.value)}
    //         InputProps={{
    //           startAdornment: (
    //             <InputAdornment position="start">
    //               <SearchIcon color="action" />
    //             </InputAdornment>
    //           ),
    //         }}
    //         sx={{
    //           backgroundColor: '#fff',
    //           '& .MuiOutlinedInput-root': {
    //             borderRadius: 2,
    //           },
    //         }}
    //       />
    //     </Box>

    //     {/* Staff List Table */}
    //     <TableContainer>
    //       <Table>
    //         <TableHead>
    //           <TableRow sx={{ backgroundColor: '#f5f5f5' }}>
    //             <TableCell sx={{ fontWeight: 'bold' }}>Sr. No.</TableCell>
    //             <TableCell sx={{ fontWeight: 'bold' }}>User Name</TableCell>
    //             <TableCell sx={{ fontWeight: 'bold' }}>
    //               User Email Address
    //             </TableCell>
    //           </TableRow>
    //         </TableHead>
    //         <TableBody>
    //           {staffList.length > 0 ? (
    //             staffList
    //               .filter(
    //                 (staff) =>
    //                   `${staff.firstName} ${staff.lastName}`
    //                     .toLowerCase()
    //                     .includes(searchQuery.toLowerCase()) ||
    //                   staff.email
    //                     .toLowerCase()
    //                     .includes(searchQuery.toLowerCase())
    //               )
    //               .slice((page - 1) * rowsPerPage, page * rowsPerPage)
    //               .map((staff, index) => (
    //                 <TableRow key={staff.id}>
    //                   <TableCell>
    //                     {(page - 1) * rowsPerPage + index + 1}
    //                   </TableCell>
    //                   <TableCell>{`${staff.firstName} ${staff.lastName}`}</TableCell>
    //                   <TableCell>{staff.email}</TableCell>
    //                 </TableRow>
    //               ))
    //           ) : (
    //             <TableRow>
    //               <TableCell
    //                 colSpan={3}
    //                 align="center"
    //                 sx={{ py: 5, color: '#666' }}
    //               >
    //                 No staff members added yet
    //               </TableCell>
    //             </TableRow>
    //           )}
    //         </TableBody>
    //       </Table>
    //     </TableContainer>

    //     {/* Pagination */}
    //     {staffList.length > 0 && (
    //       <Box
    //         sx={{
    //           display: 'flex',
    //           justifyContent: 'center',
    //           p: 2,
    //           borderTop: '1px solid #eee',
    //         }}
    //       >
    //         <Button
    //           onClick={() => setPage((prev) => Math.max(prev - 1, 1))}
    //           disabled={page === 1}
    //           startIcon={<ArrowBackIosNewIcon fontSize="small" />}
    //           sx={{ mx: 1, color: '#666' }}
    //         >
    //           Previous
    //         </Button>

    //         <Button
    //           variant="contained"
    //           disableElevation
    //           sx={{
    //             mx: 1,
    //             minWidth: '36px',
    //             backgroundColor: '#f0f0f0',
    //             color: '#333',
    //             '&:hover': {
    //               backgroundColor: '#e0e0e0',
    //             },
    //           }}
    //         >
    //           {page}
    //         </Button>

    //         <Button
    //           onClick={() => setPage((prev) => prev + 1)}
    //           disabled={page * rowsPerPage >= staffList.length}
    //           endIcon={<ArrowForwardIosIcon fontSize="small" />}
    //           sx={{ mx: 1, color: '#666' }}
    //         >
    //           Next
    //         </Button>
    //       </Box>
    //     )}
    //   </Paper>

    //   {/* Add Staff Dialog */}

    //   {/* Notification */}
    //   <Snackbar
    //     open={notification.open}
    //     autoHideDuration={4000}
    //     onClose={handleCloseNotification}
    //     anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}
    //   >
    //     <Alert
    //       onClose={handleCloseNotification}
    //       severity={notification.severity}
    //       sx={{ width: '100%' }}
    //     >
    //       {notification.message}
    //     </Alert>
    //   </Snackbar>
    // </Container>
  );
};

export default StaffManagement;
