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 MasterDataManagement = () => {
  // State for form fields
  const [appointmentType, setAppointmentType] = useState("");
  const queryParams = new URLSearchParams(location.search);

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

  // State for staff 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",
  });

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

  const handleCloseDialog = () => {
    setOpenDialog(false);
    // Clear form
    setAppointmentType("");
  };

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

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

    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: "Master Data Management",
      path: "/masterData",
    },
  ];

  return (
    <Container maxWidth="lg" sx={{ py: 4 }}>
      <PageHeader pageTitle="Master Data Management" hideAddButton />

      <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" }}>
            Master Appointment Type List
          </Typography>

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

        {/* Search Box */}
        <Box sx={{ px: 3, pb: 2 }}>
          <TextField
            placeholder="Search Appointment Type 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" }}>
                  Appointment Type
                </TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {staffList.length > 0 ? (
                staffList
                  .filter((staff) =>
                    `${staff.appointmentType}`
                      .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.appointmentType}</TableCell>
                    </TableRow>
                  ))
              ) : (
                <TableRow>
                  <TableCell
                    colSpan={2}
                    align="center"
                    sx={{ py: 5, color: "#666" }}
                  >
                    No Appointment Type 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 Appointment Type
            </Typography>
          </Box>
          <IconButton onClick={handleCloseDialog} size="small">
            <CloseIcon />
          </IconButton>
        </DialogTitle>

        <Divider />

        <DialogContent>
          <Box component="form" onSubmit={handleSubmit} sx={{ mt: 1 }}>
            <TextField
              label="Appointment Type"
              fullWidth
              margin="normal"
              value={appointmentType}
              onChange={(e) => setAppointmentType(e.target.value)}
              placeholder="Appointment Type"
              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 Appointment Type
          </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 MasterDataManagement;
