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 { pushNotification } from "../../utils/notification";
import { NOTIFICATION } from "../../constants";
import { useStyles } from "./masterDataStyles";
import Table from "../../components/Table";
import {
  getMasterData,
  setMasterData,
  updateMasterData,
  deleteMasterData,
} from "../../services/masterData.services";

const MasterDataManagement = () => {
  const classes = useStyles();
  const tableRef = useRef(null);
  // State for form fields
  const [type, setType] = useState("");
  const [editId, setEditId] = useState(null);
  const [deleteId, setDeleteId] = useState(null);

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

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

  const handleCloseDialog = () => {
    setOpenDialog(false);
    // Clear form
    setType("");
    setEditId(null);
  };

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

  // Handle delete master data after confirmation
  const handleDelete = async () => {
    try {
      const resp = await deleteMasterData(deleteId);
      pushNotification(
        "Appointment type deleted successfully", 
        NOTIFICATION.SUCCESS
      );
    } catch (error) {
      console.error("Error deleting appointment type:", error);
      pushNotification(
        `Failed to delete appointment type`, 
        NOTIFICATION.ERROR
      );
    }

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

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

    const payload = {
      type,
    };

    let resp;

    if (editId !== null) {
      resp = await updateMasterData(payload, editId);
    } else {
      resp = await setMasterData(payload);
    }

    if (resp?.data?.data) {
      pushNotification(
        "Master Data created successfully!",
        NOTIFICATION.SUCCESS
      );
    } else {
      pushNotification(resp?.data?.message, NOTIFICATION.ERROR);
    }

    // Refresh the table data
    if (tableRef.current) {
      tableRef.current.reFetchData();
    }

    // Close dialog
    handleCloseDialog();
    setEditId(null);
  };

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

      const resp = await getMasterData(params);

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

  const handleEdit = async (row) => {
    setEditId(row.original.id); // Store the ID for update operation
    setType(row.original.type);
    setOpenDialog(true);
  };

  // ...................breadcrumbs array........................
  const breadcrumbs = [
    {
      label: "Dashboard",
      path: "/",
    },
    {
      label: "Master Data Management",
      path: "/masterData",
    },
  ];

  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,
    },
    {
      id: "type", // Add an id to match the accessorKey
      size: 280,
      accessorKey: "type",
      header: "Type",
      Cell: (props) => {
        return (
          <span>
            {props.row.original.type.charAt(0).toUpperCase() + props.row.original.type.slice(1)}
          </span>
        );
      },
      enableColumnFilter: false,
    },
    // Removed the empty object that was causing the error
  ]);

  return (
    <Box>
      <PageHeader
        pageTitle="Master Data 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="Master Data"
            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
          PaperProps={{
            sx: {
              borderRadius: "12px",
              overflow: "hidden",
            },
          }}
        >
          <DialogTitle
            sx={{
              padding: "16px 24px",
              backgroundColor: (theme) => theme.palette.primary.main,
              color: "white",
              fontWeight: "bold",
              position: "relative",
            }}
          >
            {editId !== null
              ? "Edit Appointment Type"
              : "Add New Appointment Type"}
            <IconButton
              onClick={handleCloseDialog}
              sx={{
                position: "absolute",
                right: 8,
                top: 8,
                color: "white",
              }}
            >
              <CloseIcon />
            </IconButton>
          </DialogTitle>

          <Divider />

          <DialogContent>
            <Box component="form" onSubmit={handleSubmit} sx={{ mt: 1 }}>
              <TextField
                label="Appointment Type"
                fullWidth
                margin="normal"
                value={type}
                onChange={(e) => setType(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",
                },
              }}
            >
              {editId !== null
                ? "Update Appointment Type"
                : "Add Appointment Type"}
            </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 appointment type? 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>
  );
};

export default MasterDataManagement;
