import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import {
  Box,
  Typography,
  Button,
  IconButton,
  Drawer,
  TextField,
  useMediaQuery,
  useTheme,
  FormControlLabel,
  Snackbar,
  Alert,
  Checkbox,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
} from "@mui/material";
import { Close as CloseIcon, Visibility } from "@mui/icons-material";
import Dialog from "@mui/material/Dialog";
import DialogTitle from "@mui/material/DialogTitle";
import DialogContent from "@mui/material/DialogContent";
import DialogActions from "@mui/material/DialogActions";
import { GridColDef } from "@mui/x-data-grid";
import Switch from "@mui/material/Switch";
import ConfirmDialog from "../../components/ConfirmDialog";
import { Edit, Delete } from "@mui/icons-material";
import { useQuery, useMutation } from "@apollo/client";
import { TEXT, ERROR_MESSAGES } from "../../const";
import Datagrids from "../../components/Datagrid";
import { GET_ALL_USERSDETAILS } from "../../graphql/query";
import {
  CREATE_CUSTOMER,
  UPDATE_CUSTOMER,
  UPDATE_CUSTOMER_STATUS,
  DELETE_CUSTOMER_BY_ID,
} from "../../graphql/mutation";
import themestyle from "../../theme";

interface Customer {
  _id: string;
  id?: string;
  clerkId: string;
  customerNo: string;
  email: string;
  fullName: string;
  password: string;
  createdAt: string;
  updatedAt: string;
  active_status: boolean;
  username?: string;
  userType?: string;
  approval?: boolean;
  companyName?: string;
  phoneNumber?: string;
  address?: string;
  city?: string;
  state?: string;
  country?: string;
  pincode?: string;
  gstnumber?: string;
}

interface CustomerInput {
  email: string;
  password?: string;
  userType: "CUSTOMER" | "ADMIN" ;
}

interface StatusSwitchProps {
  id: string;
  status: boolean;
  fullName: string;
  showSnackbar: (message: string, severity: "error" | "success") => void;
}

const AdminUserManagement: React.FC = () => {
  const navigate = useNavigate();

  const [createCustomer] = useMutation(CREATE_CUSTOMER);
  const [updateCustomer] = useMutation(UPDATE_CUSTOMER);
  const [deleteCustomer] = useMutation(DELETE_CUSTOMER_BY_ID);
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down("sm"));
  const isTablet = useMediaQuery(theme.breakpoints.between("sm", "md"));
  const [isSendEmail, setIsSendEmail] = useState(false);
  const [confirmDialog, setConfirmDialog] = useState<{
    open: boolean;
    title: string;
    message: string;
    confirmText: string;
    onConfirm: () => void;
  }>({
    open: false,
    title: "",
    message: "",
    confirmText: "",
    onConfirm: () => {},
  });
  const [drawerOpen, setDrawerOpen] = useState(false);
  const [modalOpen, setModalOpen] = useState(false);
  const [isEditMode, setIsEditMode] = useState(false);
  const [form, setForm] = useState<{ id?: string | null; email: string; password: string; userType: "CUSTOMER"|"ADMIN" }>({ id: null, email: "", password: "", userType: "CUSTOMER" });
  const [emailError, setEmailError] = useState<string>("");
  const [passwordError, setPasswordError] = useState<string>("");
  const [isEdit, setIsEdit] = useState(false);
  const [isView, setIsView] = useState(false);
  const [editingCustomerId, setEditingCustomerId] = useState<string | null>(
    null
  );
  const [newCustomer, setNewCustomer] = useState<CustomerInput>({
    email: "",
    password: "",
    userType: "CUSTOMER",
  });
  const [searchQuery, setSearchQuery] = useState<string>("");
  const [customers, setCustomers] = useState<Customer[]>([]);
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [touched, setTouched] = useState<Record<string, boolean>>({});
  const [snackbar, setSnackbar] = useState<{
    open: boolean;
    message: string;
    severity: "error" | "success";
  }>({
    open: false,
    message: "",
    severity: "success",
  });
  const [totalPages, setTotalPages] = useState(0);
  const startIndex = 1;
  const [paginationModel, setPaginationModel] = React.useState({
    pageSize: 5,
    page: 0,
  });
  const { loading, error, data, refetch } = useQuery(GET_ALL_USERSDETAILS, {
    fetchPolicy: "network-only",
    variables: {
      page: paginationModel.page + 1,
      perPage: paginationModel.pageSize,
      searchQuery: searchQuery || "",
    },
    onCompleted: (data) => {
      if (data?.getAllUserDetails) {
        const { items, totalPages, totalCount } = data.getAllUserDetails;
        const responseDataWithIndex = items.map((item: any, index: number) => ({
          ...item,
          _id: String(item.id ?? index + 1),
          id: String(item.id ?? index + 1),
          active_status: Boolean(item.approval),
          serial_no:
            index + 1 + paginationModel.page * paginationModel.pageSize,
        }));
        setCustomers(responseDataWithIndex);
        setTotalPages(totalCount);
      }
    },
    onError: (error) => {
      console.error("Error fetching customers:", error);
    },
  });


  useEffect(() => {
    if (data?.getAllUserDetails) {
      const { items, totalPages, totalCount } = data.getAllUserDetails;
      const responseDataWithIndex = items.map((item: any, index: number) => ({
        ...item,
        _id: String(item.id ?? index + 1),
        id: String(item.id ?? index + 1),
        active_status: Boolean(item.approval),
        serial_no: index + 1 + paginationModel.page * paginationModel.pageSize,
      }));
      setCustomers(responseDataWithIndex);
      setTotalPages(totalCount);
    }
  }, [data, error, loading]);

  const handlePaginationChange = (newModel: any) => {
    setPaginationModel({
      page: newModel.page,
      pageSize: newModel.pageSize,
    });
    refetch({
      page: newModel.page + 1,
      perPage: newModel.pageSize,
      searchQuery: searchQuery || "",
    });
  };

  const handleSearchQueryChange = (newQuery: string) => {
    setSearchQuery(newQuery);
    setPaginationModel((prev) => ({ ...prev, page: 0 }));
    refetch({
      page: 1,
      perPage: paginationModel.pageSize,
      searchQuery: newQuery,
    });
  };

  useEffect(() => {
    if (!drawerOpen) {
      resetForm();
      setErrors({});
    }
  }, [drawerOpen]);

  const validateField = (name: string, value: string) => {
    const newErrors = { ...errors };

    // switch (name) {
    //   case 'email':
    //     if (!value) {
    //       newErrors.email = ERROR_MESSAGES.EMAIL_REQUIRED;
    //     } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) {
    //       newErrors.email = ERROR_MESSAGES.EMAIL_ERROR;
    //     } else {
    //       delete newErrors.email;
    //     }
    //     break;

    //   case 'fullName':
    //     if (!value) {
    //       newErrors.fullName = ERROR_MESSAGES.FULLNAME_REQUIRED;
    //     } else if (/\s/.test(value)) {
    //       newErrors.fullName = ERROR_MESSAGES.SPACE_ERROR;
    //     } else if (!/^[A-Za-z]+$/.test(value)) {
    //       newErrors.fullName = ERROR_MESSAGES.NAME_ERROR;
    //     } else {
    //       delete newErrors.fullName;
    //     }
    //     break;
    //   case 'password':
    //     if (!value) {
    //       newErrors.password = ERROR_MESSAGES.PASSWORD_REQ;
    //     } else if (value.length < 8) {
    //       newErrors.password = ERROR_MESSAGES.PSWD_LENGTH;
    //     } else if (!/[A-Z]/.test(value)) {
    //       newErrors.password = ERROR_MESSAGES.PSWD_UPPERCASE;
    //     } else if (!/[a-z]/.test(value)) {
    //       newErrors.password = ERROR_MESSAGES.PSWD_SMALLCASE;
    //     } else if (!/[0-9]/.test(value)) {
    //       newErrors.password = ERROR_MESSAGES.PSWD_NUMBER;
    //     } else if (!/[!@#$%^&*(),.?":{}|<>]/.test(value)) {
    //       newErrors.password = ERROR_MESSAGES.PSWD_SPECIAL;
    //     } else {
    //       delete newErrors.password;
    //     }
    //     break;
    //   case 'phoneNumber':
    //     if (value) {
    //       if (!TEXT.PHONE_REGEX.test(value)) {
    //         newErrors.phoneNumber = ERROR_MESSAGES.INCLUDE_COUNTRY_CODE;
    //       } else {
    //         const cleaned = value.replace(/[^\d+]/g, '');
    //         const match = cleaned.match(/^\+(\d{1,3})/);
    //         if (match) {
    //           const code = `+${match[1]}`;
    //           const digitsOnly = cleaned.replace(/\D/g, '');
    //           const localNumberLength = digitsOnly.length - match[1].length;

    //           const countryPhoneLengths: Record<string, { exact?: number; min?: number; max?: number }> = {
    //             '+91': { exact: 10 },
    //             '+1': { exact: 10 },
    //             '+44': { min: 10, max: 11 },
    //             '+971': { exact: 9 },
    //             '+49': { min: 7, max: 11 },
    //             '+33': { exact: 9 },
    //           };

    //           const rule = countryPhoneLengths[code];

    //           if (rule?.exact !== undefined) {
    //             if (localNumberLength !== rule.exact) {
    //               newErrors.phoneNumber = `Phone number for ${code} must be exactly ${rule.exact} digits`;
    //             } else {
    //               delete newErrors.phoneNumber;
    //             }
    //           } else if (rule?.min !== undefined && rule?.max !== undefined) {
    //             if (localNumberLength < rule.min || localNumberLength > rule.max) {
    //               newErrors.phoneNumber = `Phone number for ${code} must be between ${rule.min} and ${rule.max} digits`;
    //             } else {
    //               delete newErrors.phoneNumber;
    //             }
    //           } else {
    //             if (localNumberLength < 7 || localNumberLength > 15) {
    //               newErrors.phoneNumber = ERROR_MESSAGES.PHONE_NUMBER_LEHGTH;
    //             } else {
    //               delete newErrors.phoneNumber;
    //             }
    //           }
    //         } else {
    //           newErrors.phoneNumber = ERROR_MESSAGES.COUNTRY_CODE;
    //         }
    //       }
    //     } else {
    //       delete newErrors.phoneNumber;
    //     }
    //     break;
    //   case 'city':
    //   case 'state':
    //   case 'country':
    //     if (value && !/^[A-Za-z\s]+$/.test(value)) {
    //       newErrors[name] = ERROR_MESSAGES.CITY_ERROR;
    //     } else {
    //       delete newErrors[name];
    //     }
    //     break;

    //   case 'pincode':
    //     if (value && !/^[a-zA-Z0-9\s-]{1,9}$/.test(value)) {
    //       newErrors.pincode = ERROR_MESSAGES.PINCODE_ERROR;
    //     } else {
    //       delete newErrors.pincode;
    //     }
    //     break;
    //   case 'gstnumber':
    //     if (value) {
    //       const gstRegex = /^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}Z[0-9A-Z]{1}$/;
    //       if (!gstRegex.test(value.toUpperCase())) {
    //         newErrors.gstnumber = ERROR_MESSAGES.GST_INVALID_FORMAT;
    //       } else {
    //         delete newErrors.gstnumber;
    //       }
    //     } else {
    //       delete newErrors.gstnumber;
    //     }
    //     break;

    //   default:
    //     delete newErrors[name];
    // }

    setErrors(newErrors);
    return newErrors[name];
  };

  const handleInputChange = (
    e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
  ) => {
    const { name, value } = e.target;
    setNewCustomer((prev) => ({ ...prev, [name]: value }));
    setTouched((prev) => ({ ...prev, [name]: true }));
    validateField(name, value);
  };

  const showSnackbar = (
    message: string,
    severity: "error" | "success" = "success"
  ) => {
    setSnackbar({ open: true, message, severity });
  };
  const closeSnackbar = () => setSnackbar((prev) => ({ ...prev, open: false }));
  const handleCustomerClick = (
    id: string,
    customerName: string,
    customerEmail: string,
    customerNo: string,
    customergstnumber: string
  ) => {
    navigate(`/customerdetails/${customerNo}`, {
      state: { id, customerName, customerEmail, customerNo, customergstnumber },
    });
  };

  const handleCreateOrUpdateCustomer = async () => {
    try {
      // 🔻 Removed Clerk session check
      // if (!user) {
      //   throw new Error('User session not available');
      // }

      const validationErrors: Record<string, string> = {};

      if (!newCustomer.email) {
        validationErrors.email = "Email is required";
      } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(newCustomer.email)) {
        validationErrors.email = "Please enter a valid email address";
      }

      //   if (!newCustomer.fullName) {
      //     validationErrors.fullName = ERROR_MESSAGES.FULLNAME_REQUIRED;
      //   } else if (!/^[A-Za-z\s]+$/.test(newCustomer.fullName)) {
      //     validationErrors.fullName = 'Name should only contain letters and spaces';
      //   }

      //   if (!isEdit) {
      //     if (!newCustomer.password) {
      //       validationErrors.password = ERROR_MESSAGES.PASSWORD_REQ;
      //     } else if (newCustomer.password.length < 8) {
      //       validationErrors.password = ERROR_MESSAGES.PSWD_LENGTH;
      //     } else if (!/[A-Z]/.test(newCustomer.password)) {
      //       validationErrors.password = ERROR_MESSAGES.PSWD_UPPERCASE;
      //     } else if (!/[a-z]/.test(newCustomer.password)) {
      //       validationErrors.password = ERROR_MESSAGES.PSWD_SMALLCASE;
      //     } else if (!/[0-9]/.test(newCustomer.password)) {
      //       validationErrors.password = ERROR_MESSAGES.PSWD_NUMBER;
      //     } else if (!/[!@#$%^&*(),.?":{}|<>]/.test(newCustomer.password)) {
      //       validationErrors.password = ERROR_MESSAGES.PSWD_SPECIAL;
      //     }
      //   }

      //   if (newCustomer.phoneNumber && !TEXT.PHONE_REGEX.test(newCustomer.phoneNumber)) {
      //     validationErrors.phoneNumber = ERROR_MESSAGES.INCLUDE_COUNTRY_CODE;
      //   }
      //   if (newCustomer.city && !/^[A-Za-z\s]+$/.test(newCustomer.city)) {
      //     validationErrors.city = ERROR_MESSAGES.CITY_SPACE_ERROR;
      //   }
      //   if (newCustomer.state && !/^[A-Za-z\s]+$/.test(newCustomer.state)) {
      //     validationErrors.state = ERROR_MESSAGES.STATE_ERROR;
      //   }
      //   if (newCustomer.country && !/^[A-Za-z\s]+$/.test(newCustomer.country)) {
      //     validationErrors.country = ERROR_MESSAGES.COUNTRY_ERROR;
      //   }

      //   if (newCustomer.pincode && !/^[a-zA-Z0-9\s-]{1,9}$/.test(newCustomer.pincode)) {
      //     validationErrors.pincode = 'Pincode can only contain letters, numbers, spaces, and hyphens (max 9 chars)';
      //   }

      //   if (newCustomer.gstnumber && !/^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}Z[0-9A-Z]{1}$/.test(newCustomer.gstnumber)) {
      //     validationErrors.gstnumber = ERROR_MESSAGES.GST_INVALID_FORMAT;
      //   }

      if (Object.keys(validationErrors).length > 0) {
        const errorMessages = Object.values(validationErrors).join("\n");
        showSnackbar(errorMessages, "error");
        return;
      }

      // Map UI form to backend input shape
      const inputCreate = {
        email: newCustomer.email,
        username: (newCustomer.email || "").split("@")[0] || newCustomer.email,
        password: newCustomer.password || "",
        userType: newCustomer.userType,
      };

      const inputUpdate: any = {
        id: editingCustomerId,
      };

      if (
        isEdit &&
        (!newCustomer.password || newCustomer.password.trim() === "")
      ) {
        // do not send password to keep unchanged
      } else if (
        !isEdit &&
        (!newCustomer.password || newCustomer.password.trim() === "")
      ) {
        showSnackbar("Password is required for creating a customer", "error");
        return;
      } else if (newCustomer.password && newCustomer.password.trim() !== "") {
        inputUpdate.password = newCustomer.password.trim();
      }

      if (isEdit && editingCustomerId) {
        const { data } = await updateCustomer({
          variables: { input: inputUpdate },
        });
        showSnackbar(
          `${
            data.updateCustomer.username || data.updateCustomer.email
          } was updated successfully.`
        );
      } else {
        const { data } = await createCustomer({
          variables: { input: inputCreate },
        });
        showSnackbar(
          `${
            data.createCustomer.username || data.createCustomer.email
          } was created successfully.`
        );
      }

      await refetch();
      setDrawerOpen(false);
      resetForm();
    } catch (err: any) {
      console.error("Error saving customer:", err);
      showSnackbar(err.message || "Error saving customer", "error");
    }
  };

  const handleEdit = () => {
    setIsEdit(true);
    setIsView(false);
  };

  const handleView = (customer: Customer) => {
    setIsView(true);
    setIsEdit(false);
    setEditingCustomerId(customer._id);
    setNewCustomer({
      email: customer.email,
      password: "",
      userType: (customer.userType as any) || "CUSTOMER",
    });
    setDrawerOpen(true);
  };

  const handleDelete = async (id: string, customerNo: string, name: string) => {
    try {
      await deleteCustomer({ variables: { id } });
      showSnackbar(
        `${name} has been deleted successfully.`,
        "success"
      );
      setConfirmDialog({
        open: false,
        title: "",
        message: "",
        confirmText: "",
        onConfirm: () => {},
      });
      await refetch();
    } catch (err: any) {
      console.error("Error deleting customer:", err);
      showSnackbar(err.message || "Error deleting customer", "error");
    }
  };

  const resetForm = () => {
    setIsEdit(false);
    setEditingCustomerId(null);
    setNewCustomer({
      email: "",
      password: "",
      userType: "CUSTOMER",
    });
  };

  const StatusSwitch: React.FC<StatusSwitchProps> = ({
    id,
    status,
    showSnackbar,
    fullName,
  }) => {
    const [updateStatusMuataion] = useMutation(UPDATE_CUSTOMER_STATUS);

    const handleChange = async (event: React.ChangeEvent<HTMLInputElement>) => {
      const newStatus = event.target.checked;
      setCustomers((prev) =>
        prev.map((c) =>
          String(c.id) === String(id) || String(c._id) === String(id)
            ? { ...c, approval: newStatus, active_status: newStatus }
            : c
        )
      );

      const variables = { id: id, approval: newStatus };
      try {
        const { data } = await updateStatusMuataion({ variables });
        const { success, message } = data.updateCustomerStatus;

        if (success) {
          showSnackbar(
            `${fullName} status has been updated to ${
              newStatus ? "Approved" : "Unapproved"
            }.`,
            "success"
          );
          refetch({
            page: paginationModel.page,
            perPage: paginationModel.pageSize,
            searchQuery: searchQuery,
          });
        } else {
          showSnackbar(message || "Status update failed", "error");
        }
      } catch (error) {
        console.error("Failed to update status:", error);
        setCustomers((prev) =>
          prev.map((c) =>
            String(c.id) === String(id) || String(c._id) === String(id)
              ? { ...c, approval: !newStatus, active_status: !newStatus }
              : c
          )
        );
      }
    };
    return (
      <>
        <FormControlLabel
          control={
            <Switch
              checked={status}
              sx={{
                "& .css-byenzh-MuiButtonBase-root-MuiSwitch-switchBase.Mui-checked":
                  {
                    color: "#007BFF",
                  },
                "& .css-byenzh-MuiButtonBase-root-MuiSwitch-switchBase.Mui-checked+.MuiSwitch-track":
                  {
                    backgroundColor: "#007BFF",
                  },
                "& .MuiSwitch-switchBase.Mui-checked": {
                  color: "#007BFF",
                },
                "& .MuiSwitch-switchBase.Mui-checked + .MuiSwitch-track": {
                  backgroundColor: "#007BFF",
                },
              }}
              onChange={handleChange}
            />
          }
          label=""
        />
        <span>{status ? "Active" : "Inactive"}</span>
      </>
    );
  };

  const columns: GridColDef[] = [
    {
      field: "serial_no",
      headerName: "S.No",
      width: isMobile ? 70 : 90,
      sortable: false,
    },
    {
      field: "username",
      headerName: "Username",
      flex: 1,
      sortable: false,
      minWidth: isMobile ? 150 : 200,
    },
    {
      field: "email",
      headerName: "Email",
      flex: 1,
      sortable: false,
      minWidth: isMobile ? 150 : 220,
    },
    {
      field: "phoneNumber",
      headerName: "Phone Number",
      flex: 1,
      sortable: false,
      minWidth: isMobile ? 130 : 180,
    },
    {
      field: "companyName",
      headerName: "Company Name",
      flex: 1,
      sortable: false,
      minWidth: isMobile ? 150 : 200,
    },
    {
      field: "userType",
      headerName: "Role",
      flex: 1,
      sortable: false,
      minWidth: isMobile ? 100 : 140,
      valueFormatter: (params) => {
        const v = String(params.value ?? "");
        if (!v) return "";
        const lower = v.toLowerCase();
        return lower.charAt(0).toUpperCase() + lower.slice(1);
      },
    },
    {
      field: "approval",
      headerName: "Approved",
      flex: 1,
      minWidth: isMobile ? 100 : 150,
      sortable: false,
      renderCell: (params: any) => (
        <StatusSwitch
          status={Boolean(params.value)}
          id={String(params.id)}
          fullName={params.row.username || params.row.email}
          showSnackbar={showSnackbar}
        />
      ),
    },
    {
      field: "actions",
      headerName: "Actions",
      flex: 1,
      minWidth: isMobile ? 100 : 150,
      sortable: false,
      filterable: false,
      renderCell: (params) => (
        <Box display="flex" gap={1}>
          <IconButton
            size="small"
            onClick={() => {
              setIsEditMode(true);
              setForm({ id: String(params.row.id), email: params.row.email, password: '', userType: (params.row.userType as any) || 'CUSTOMER' });
              setModalOpen(true);
            }}
            sx={{ color: themestyle.colors.primary }}
          >
            <Edit />
          </IconButton>
          <IconButton
            size="small"
            onClick={() => {
              setConfirmDialog({
                open: true,
                title: "Confirm Delete",
                confirmText: "Delete",
                message: `Are you sure you want to delete ${params.row.username || params.row.email}?`,
                onConfirm: async () => {
                  if (params.row.id) {
                    await handleDelete(
                      String(params.row.id),
                      String(params.row.id),
                      params.row.username || params.row.email
                    );
                  }
                },
              });
            }}
            sx={{ color: themestyle.colors.primary }}
          >
            <Delete />
          </IconButton>
        </Box>
      ),
    },
  ];

  return (
    <Box
      sx={{
        width: "auto",
        p: 0,
        ml: 1,
        mt: isMobile ? 2 : isTablet ? 3 : 4,
      }}
    >
      <Box sx={{ mb: 2 }}>
        <Box>
          <Box
            sx={{
              display: "flex",
              justifyContent: isMobile ? "flex-start" : "flex-end",
            }}
          >
            <Button
              variant="contained"
              sx={{
                textTransform: "none",
                fontSize: "0.9rem",
                bgcolor: themestyle.colors.primary,
                color: "#FFFFFF",
                borderRadius: "24px",
                px: 2.5,
                height: 36,
                boxShadow: "none",
                "&:hover": { backgroundColor: themestyle.colors.primary, boxShadow: "none" },
              }}
              onClick={() => {
                setIsEditMode(false);
                setForm({ id: null, email: "", password: "", userType: "CUSTOMER" });
                setEmailError("");
                setPasswordError("");
                setModalOpen(true);
              }}
            >
              Create User
            </Button>
          </Box>
        </Box>
      </Box>
      <Dialog open={modalOpen} onClose={() => setModalOpen(false)} fullWidth maxWidth="sm" 
        PaperProps={{ sx: { borderRadius: 2, overflow: 'hidden' } }}
      >
        <DialogTitle sx={{ fontWeight: 700, fontSize: '1.25rem', borderBottom: '1px solid #eee', py: 2 }}>
          {isEditMode ? "Edit User" : "Create User"}
        </DialogTitle>
        <DialogContent dividers={false} sx={{ pt: 2, pb: 1 }}>
          <Box sx={{ display: 'grid', gap: 1.5 }}>
            <TextField
              label="Email"
              type="email"
              value={form.email}
              onChange={(e) => {
                const val = e.target.value;
                setForm((prev) => ({ ...prev, email: val }));
                if (!val) {
                  setEmailError("Email is required");
                } else if (!ERROR_MESSAGES.EMAILREG.test(val)) {
                  setEmailError("Please enter a valid email address");
                } else {
                  setEmailError("");
                }
              }}
              fullWidth
              disabled={isEditMode}
              required
              error={!!emailError}
              helperText={emailError}
              size="small"
              margin="dense"
              InputProps={{ sx: { borderRadius: 2 } }}
            />
            <TextField
              label="Password"
              type="password"
              value={form.password}
              onChange={(e) => {
                const val = e.target.value;
                setForm((prev) => ({ ...prev, password: val }));
                if (!isEditMode) {
                  if (!val) setPasswordError('Password is required');
                  else if (val.length < 8) setPasswordError('Password must be at least 8 characters');
                  else setPasswordError('');
                } else {
                  // In edit mode, password is optional; validate only if provided
                  if (val && val.length < 8) setPasswordError('Password must be at least 8 characters');
                  else setPasswordError('');
                }
              }}
              fullWidth
              required={!isEditMode}
              placeholder={isEditMode ? "Leave blank to keep current password" : ""}
              error={!!passwordError}
              helperText={passwordError}
              size="small"
              margin="dense"
              InputProps={{ sx: { borderRadius: 2 } }}
            />
            <FormControl fullWidth size="small" margin="dense">
              <InputLabel id="user-type">User Type</InputLabel>
              <Select
                labelId="user-type"
                label="User Type"
                value={form.userType}
                onChange={(e) => setForm((prev) => ({ ...prev, userType: e.target.value as any }))}
                MenuProps={{ PaperProps: { sx: { borderRadius: 2 } } }}
              >
                <MenuItem value={"CUSTOMER"}>Customer</MenuItem>
                <MenuItem value={"ADMIN"}>Admin</MenuItem>
              </Select>
            </FormControl>
          </Box>
        </DialogContent>
        <DialogActions sx={{ px: 3, py: 2, borderTop: '1px solid #eee' }}>
          <Button onClick={() => setModalOpen(false)} variant="outlined" sx={{
            textTransform: 'none',
            fontSize: '0.9rem',
            color: themestyle.colors.primary,
            borderColor: themestyle.colors.primary,
            borderRadius: 24,
            px: 3,
            height: 36,
          }}>Cancel</Button>
          <Button onClick={async () => {
            try {
              if (!form.email || (!isEditMode && !form.password)) {
                showSnackbar('Please fill required fields', 'error');
                return;
              }
              if (!ERROR_MESSAGES.EMAILREG.test(form.email)) {
                setEmailError("Please enter a valid email address");
                return;
              }
              if (!isEditMode) {
                if (!form.password || form.password.length < 8) {
                  setPasswordError('Password must be at least 8 characters');
                  return;
                }
              } else if (form.password && form.password.length < 8) {
                setPasswordError('Password must be at least 8 characters');
                return;
              }
              if (isEditMode && form.id) {
                const variables: any = { input: { id: form.id, userType: form.userType } };
                if (form.password && form.password.trim()) variables.input.password = form.password.trim();
                const { data } = await updateCustomer({ variables });
                showSnackbar(`${data.updateCustomer.username || data.updateCustomer.email} updated successfully.`);
              } else {
                const input = {
                  email: form.email,
                  username: (form.email || '').split('@')[0] || form.email,
                  password: form.password,
                  userType: form.userType,
                };
                const { data } = await createCustomer({ variables: { input } });
                showSnackbar(`${data.createCustomer.username || data.createCustomer.email} created successfully.`);
              }
              setModalOpen(false);
              setForm({ id: null, email: '', password: '', userType: 'CUSTOMER' });
              setEmailError("");
              setPasswordError("");
              await refetch();
            } catch (e: any) {
              console.error(e);
              const raw = e?.message || 'Operation failed';
              const friendly = raw
                .replace(/^Create customer failed:\s*/i, '')
                .replace(/^Update customer failed:\s*/i, '')
                .replace(/^GraphQL error:\s*/i, '');
              showSnackbar(friendly, 'error');
            }
          }} variant="contained" sx={{
            textTransform: 'none',
            fontSize: '0.9rem',
            bgcolor: themestyle.colors.primary,
            color: '#FFFFFF',
            borderRadius: 24,
            px: 3,
            height: 36,
            boxShadow: 'none',
            '&:hover': { backgroundColor: themestyle.colors.primary, boxShadow: 'none' },
          }}>{isEditMode ? 'Save' : 'Create'}</Button>
        </DialogActions>
      </Dialog>
      <Box
        sx={{
          display: "flex",
          justifyContent: "center",
          alignItems: "center",
          width: "100%",
          maxWidth: "100%",
          padding: "0 20px",
        }}
      >
        <Box sx={{ height: "calc(100vh - 200px)", width: "100%" }}>
          <Datagrids
            rows={customers}
            columns={columns}
            pageSizeOptions={[5, 10, 20, 30]}
            rowCount={totalPages}
            style={{ border: "0px" }}
            paginationMode="server"
            paginationModel={paginationModel}
            onPaginationModelChange={handlePaginationChange}
            onSearchQueryChange={handleSearchQueryChange}
            searchQuery={searchQuery}
            loading={loading}
          />
        </Box>
      </Box>
      <Drawer
        anchor="right"
        open={drawerOpen}
        onClose={() => {
          setDrawerOpen(false);
          resetForm();
          setErrors({});
          setTouched({});
        }}
        variant={isMobile ? "temporary" : "persistent"}
        sx={{
          "& .MuiDrawer-paper": {
            width: isMobile ? "100%" : 400,
            p: isMobile ? 2 : 2,
            position: "fixed",
            height: "100%",
            boxShadow: "0 2px 4px rgba(0,0,0,0.1)",
            display: "flex",
            flexDirection: "column",
          },
        }}
      >
        <Box
          sx={{
            display: "flex",
            justifyContent: "space-between",
            alignItems: "center",
            mb: 2,
            position: "sticky",
            top: isMobile ? 15 : 0,
            backgroundColor: "background.paper",
            zIndex: 1,
            py: 0,
            px: { xs: 1, sm: 1 },
          }}
        >
          <Typography
            variant="subtitle1"
            fontWeight={500}
            sx={{ fontSize: { xs: "0.9rem", sm: "1rem" } }}
          >
            User Details
          </Typography>
          <Box
            sx={{
              display: "flex",
              alignItems: "center",
              gap: { xs: 1, sm: 1.5 },
            }}
          >
            {isView && !isEdit && (
              <Button
                variant="outlined"
                onClick={handleEdit}
                sx={{
                  textTransform: "none",
                  fontSize: { xs: "0.75rem", sm: "0.850rem" },
                  color: "#007BFF",
                  backgroundColor: "#FFFFFF",
                  borderColor: "#007BFF",
                  borderRadius: "20px",
                  px: { xs: 1.5, sm: 2 },
                  py: { xs: 0.25, sm: 0.5 },
                  height: { xs: "32px", sm: "28px" },
                  "&:hover": {
                    backgroundColor: "#007BFF",
                    color: "#FFFFFF",
                    borderColor: "#007BFF",
                  },
                }}
              >
                Edit
              </Button>
            )}
            <IconButton
              onClick={() => {
                setDrawerOpen(false);
                resetForm();
              }}
              sx={{ color: "text.secondary" }}
            >
              <CloseIcon />
            </IconButton>
          </Box>
        </Box>

        <Box sx={{ flex: 1, pt: 1 }}>
          <Box sx={{ display: "grid", gap: 2 }}>
            <TextField
              size="small"
              label="Email"
              name="email"
              type="email"
              disabled={isView || isEdit}
              value={newCustomer.email}
              onChange={handleInputChange}
              fullWidth
              required
              helperText={isEdit ? "Email cannot be edited" : errors["email"]}
              InputLabelProps={{ sx: { fontSize: "0.85rem" } }}
              inputProps={{ style: { fontSize: "0.9rem" } }}
              sx={{
                "& .MuiInputBase-root": { borderRadius: "8px !important" },
              }}
            />
            <TextField
              size="small"
              label="Password"
              name="password"
              type="password"
              disabled={isView}
              value={newCustomer.password}
              onChange={handleInputChange}
              fullWidth
              required={!isEdit}
              helperText={isEdit ? "Leave blank to keep current password" : ""}
              InputLabelProps={{ sx: { fontSize: "0.85rem" } }}
              inputProps={{ style: { fontSize: "0.9rem" } }}
              sx={{
                "& .MuiInputBase-root": { borderRadius: "8px !important" },
              }}
            />
            <FormControl fullWidth size="small">
              <InputLabel id="user-type-label">User Type</InputLabel>
              <Select
                labelId="user-type-label"
                label="User Type"
                value={newCustomer.userType}
                onChange={(e) =>
                  setNewCustomer((prev) => ({
                    ...prev,
                    userType: e.target.value as any,
                  }))
                }
                disabled={isView}
              >
                <MenuItem value={"CUSTOMER"}>Customer</MenuItem>
                <MenuItem value={"ADMIN"}>Admin</MenuItem>
              </Select>
            </FormControl>
          </Box>
        </Box>

        <Box
          sx={{
            mx: "0 10px 0 0",
            pt: 2,
            gap: "20px",
            borderTop: "1px solid #eee",
            display: "flex",
            justifyContent: "flex-end",
            position: "sticky",
            bottom: 0,
            backgroundColor: "background.paper",
            zIndex: 1,
          }}
        >
          <Button
            variant="outlined"
            onClick={() => {
              setDrawerOpen(false);
              resetForm();
            }}
             sx={{
                        textTransform: "none",
                        fontSize: "0.85rem",
                        color: themestyle.colors.primary,
                        backgroundColor: "#FFFFFF",
                        borderRadius: "20px",
                        borderColor: themestyle.colors.primary,
                        width: "120px",
                        height: "35px",
                        "&:hover": {
                          borderColor: themestyle.colors.primary,
                          color: themestyle.colors.primary,
                        },
                      }}
          >
            Cancel
          </Button>
          {!isView && (
            <Button
              variant="contained"
              onClick={handleCreateOrUpdateCustomer}
                sx={{
                          textTransform: "none",
                          fontSize: "0.85rem",
                          bgcolor: themestyle.colors.primary,
                          color: "#FFFFFF",
                          borderRadius: "20px",
                          width: "120px",
                          height: "35px",
                          "&:hover": {
                            backgroundColor: themestyle.colors.primary,
                          },
                        }}
            >
              {isEdit ? "Update" : "Save"}
            </Button>
          )}
        </Box>
      </Drawer>
      <Snackbar
        open={snackbar.open}
        autoHideDuration={4000}
        onClose={closeSnackbar}
        anchorOrigin={{ vertical: "top", horizontal: "center" }}
        sx={{
          maxWidth: "90vw",
          width: "auto",
        }}
      >
        <Alert
          onClose={closeSnackbar}
          severity={snackbar.severity}
          sx={{
            width: "auto",
            maxWidth: "600px",
            whiteSpace: "pre-wrap",
            wordBreak: "break-word",
            padding: 2,
          }}
        >
          {snackbar.message}
        </Alert>
      </Snackbar>
      <ConfirmDialog
        open={confirmDialog.open}
        title={confirmDialog.title}
        message={confirmDialog.message}
        confirmText={confirmDialog.confirmText}
        onConfirm={confirmDialog.onConfirm}
        onClose={() =>
          setConfirmDialog({
            open: false,
            title: "",
            message: "",
            confirmText: "",
            onConfirm: () => {},
          })
        }
      />
    </Box>
  );
};

export default AdminUserManagement;
