import AddIcon from '@mui/icons-material/Add';
import ArrowBackIosNewIcon from '@mui/icons-material/ArrowBackIosNew';
import ArrowForwardIosIcon from '@mui/icons-material/ArrowForwardIos';
import CloseIcon from '@mui/icons-material/Close';
import PersonAddIcon from '@mui/icons-material/PersonAdd';
import SearchIcon from '@mui/icons-material/Search';
import {
  Alert,
  Box,
  Button,
  Container,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  Divider,
  IconButton,
  InputAdornment,
  Paper,
  Snackbar,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TextField,
  Typography,
} from '@mui/material';
import React, { useState } from 'react';
import CustomBreadcrumbs from '../../components/CustomBreadcrumbs';
import PageHeader from '../../components/PageHeader';

const StaffManagement = () => {
  // State for form fields
  const [firstName, setFirstName] = useState('');
  const [lastName, setLastName] = useState('');
  const [email, setEmail] = useState('');
  const [emailError, setEmailError] = useState('');
  const queryParams = new URLSearchParams(location.search);

  // State for staff list
  const [staffList, setStaffList] = useState([]);

  // State for dialog
  const [openDialog, setOpenDialog] = useState(false);

  // State for search
  const [searchQuery, setSearchQuery] = useState('');

  // State for pagination
  const [page, setPage] = useState(1);
  const rowsPerPage = 10;

  // State for notification
  const [notification, setNotification] = useState({
    open: false,
    message: '',
    severity: 'success',
  });

  // 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('');
  };

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

    // Validate email
    if (!validateEmail(email)) {
      setEmailError('Please enter a valid email address');
      return;
    }

    // Add new staff member
    const newStaff = {
      id: staffList.length + 1,
      firstName,
      lastName,
      email,
    };

    setStaffList([...staffList, newStaff]);

    // Close dialog
    handleCloseDialog();

    // Show success notification
    setNotification({
      open: true,
      message: 'Staff member added successfully!',
      severity: 'success',
    });
  };

  // Handle notification close
  const handleCloseNotification = () => {
    setNotification({
      ...notification,
      open: false,
    });
  };

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

  return (
    <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 */}
      <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' }}
            >
              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,
              }}
            />

            <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,
              }}
            />
          </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',
              },
            }}
          >
            Add Admin
          </Button>
        </DialogActions>
      </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;
