"use client";

import React, { useState, useEffect } from "react";
import {
  Card,
  Box,
  Typography,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableFooter,
  TablePagination,
  TableRow,
  Paper,
  IconButton,
  TableHead,
  Button,
  TextField,
  DialogActions,
  DialogContent,
  DialogTitle,
  FormControl,
  InputLabel,
  MenuItem,
  FormHelperText,
} from "@mui/material";
import { ArrowUpward, ArrowDownward} from '@mui/icons-material';
import Select, { SelectChangeEvent } from "@mui/material/Select";
import AddIcon from "@mui/icons-material/Add";
import ClearIcon from "@mui/icons-material/Clear";
import CustomerService, {CustomerOPData,CustomerIdInData} from "@/service/CustomerService";
import { ToastContainer, toast} from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import { customerTouchFields,CustomerFormValues,CustomerValidationSchema } from '@lib/ValidationSchemas';
import { useFormik  } from 'formik';
import TablePaginationActions from "../../Pagination";
import BootstrapDialog from "../../BootstrapModel";
import {handleFetchWithTokenRefresh} from '@utils/common';
import { useCookies } from 'react-cookie';
import InputMask from 'react-input-mask';
import CustomerAddressService from "@/service/CustomerAddressService";
import MasterService,{CityData, StateData, CountryData} from "@/service/MasterService";
import {RoleEnum, defaultStateId } from "@constant/StaticData";
import UserOtpService from "@/service/UserOtpService";
import SearchIcon from '@mui/icons-material/Search';
import InputAdornment from '@mui/material/InputAdornment';
import withAuth from "@/withAuth";
import routes from "@/routes";

const Customer: React.FC = () => {
  const [page, setPage] = React.useState(0);
  const [rowsPerPage, setRowsPerPage] = React.useState(10);
  const [customerData, setcustomerData] = useState<CustomerOPData | undefined>(undefined);
  const [customerDataById, setCustomerDataById] = useState<CustomerIdInData | undefined>(undefined);
  const [open, setOpen] = useState(false);
  const [delOpen, setDelOpen] = useState(false);
  const [viewOpen, setViewOpen] = useState(false);
  const [viewOpenOTP, setViewOpenOTP] = useState(false);
  const [title, setTitle] = useState("Add New");
  const [delId, setDelId] = useState(0);
  const [authId, setAuthId] = useState(0);
  const [FId, setFId] = useState(0);
  const [changes, setChanges] = useState("");
  const [btnName, setBtnName] = useState("Create");
  const [cookies, setCookie, removeCookie] = useCookies();
  const [isPagination, setIsPagination] = useState(false);
  const [countryId, setCountryId] = React.useState<string>("");
  const [countryData, setCountryData] = useState<CountryData | null>(null);
  const [stateData, setStateData] = useState<StateData | null>(null);
  const [cityData, setCityData] = useState<CityData | null>(null);
  const [stateId, setStateId] = useState(defaultStateId);
  const [sortOrder, setSortOrder] = useState<'DESC' | 'ASC'>('DESC');
  const [quickSearch, setQuickSearch] = React.useState<string>("");

  const handleChange = (event: SelectChangeEvent) => {
    formik.handleChange(event);
  };
  
  const handleSubmit = async(values:any) =>{
    const errors = await formik.validateForm();
      formik.setTouched(customerTouchFields);   
     if (Object.keys(errors).length === 0) {
        try {
          
          let successMsg;
          if (changes === 'Add') {
            successMsg = "Inserted data successfully !!";
            const customerInsData = await CustomerService.createCustomerSignUp(values);
             if(customerInsData?.AppSignup && customerInsData?.AppSignup?.id != undefined){
              const customerupdateData = await CustomerService.updateCustomer(values,customerInsData?.AppSignup?.id);
              const CustomerSignupId = customerInsData?.AppSignup?.id || 0;
              const addressData = await CustomerAddressService.createCustomerAddress(values,CustomerSignupId);
              const CustomerbyIdData = await CustomerService.getCustomerById(CustomerSignupId); 
              const customerSendOtp = await UserOtpService.createOtpSignin(values)
              setcustomerData((prevData) => {
                if (!prevData || !prevData.UserFind) {
                  return prevData;
                }
                const newRow = CustomerbyIdData?.UserFindOneById;
                if (!newRow) {
                  return prevData; 
                }
                
                const existingRows = prevData?.UserFind?.rows || [];
                const total = prevData?.UserFind?.total  || 0;   
                const pages = Math.ceil(total / rowsPerPage);
                               
                return {
                  ...prevData,
                  UserFind: {
                    rows: [newRow,...existingRows],
                    total: total + 1,
                    pages: pages
                  },
                }; 
              }); 
              toast.success(successMsg, {
                position: "bottom-left",
                autoClose: 2000,
            });
            }  
          } else if (changes === 'Edit') {
              successMsg = "Updated data successfully !!";
            const customerInsData = await CustomerService.updateCustomer(values,FId);

        if(customerInsData?.UserUpdate && customerInsData.UserUpdate.affected > 0){
            const customerId = customerInsData.UserUpdate.affectedRows?.[0]?.id || 0;
            const custmerAddressUpData = await CustomerAddressService.updateCustomerAddress(values,customerId);
            const CustomerbyIdData = await CustomerService.getCustomerById(customerId); 
           
                setcustomerData((prevData) => {
                  if (!prevData || !prevData.UserFind) {
                      return prevData;
                  }
                  const newRow = CustomerbyIdData?.UserFindOneById;
                  if (!newRow) {
                    return prevData; 
                  }
                  const existingRows = prevData?.UserFind?.rows || [];
                  const total = prevData?.UserFind?.total  || 0;   
                  const pages = Math.ceil(total / rowsPerPage); 

                    const updatedRows = existingRows.map(row =>
                    row.id === newRow.id ? newRow : row
                  );
                
                  const isNewRowAdded = !existingRows.some(row => row.id === newRow.id);
                  if (isNewRowAdded) {
                    updatedRows.unshift(newRow);
                  }
                
                  const updatedTotal = isNewRowAdded ? total + 1 : total
                
                  return {
                      ...prevData,
                      UserFind: {
                          ...prevData.UserFind,
                          rows: updatedRows,
                          total:updatedTotal,
                          pages: pages
                      },
                  };
              }); 
                if(customerInsData?.UserUpdate?.snapshot?.error[0]){
                  const errorMsg = customerInsData?.UserUpdate?.snapshot?.error[0]
                  toast.error(errorMsg, {
                    position: "bottom-left",
                    autoClose: 2000,
                  });
                  }else{
                  toast.success(successMsg, {
                    position: "bottom-left",
                    autoClose: 2000,
                });
              }   
            }  
          }
          setOpen(false);
          setFId(0);
        }catch (error:any) {
          console.log('GraphQL Mutation Error:', error);
          handleFetchWithTokenRefresh(error, cookies, setCookie, handleSubmit, error, values);
        }
      }  
  }

  const formik = useFormik<CustomerFormValues>({
    initialValues: {
      fname: "",
      lname:"",
      primary_email : "",
      primary_mobile: "",
      address:"",
      city_id: "",
      country_id : "",
      state_id  :  "",
      signup_source:"web"
    },
    validationSchema: CustomerValidationSchema,
    onSubmit: async(values) => {
      handleSubmit(values);
    },
  });

  const fetchData = async () => {
    try {		
      const start = (page)*rowsPerPage;
      const CustomerData = await CustomerService.getCustomer(rowsPerPage, start, quickSearch,sortOrder);
      if(CustomerData != undefined && CustomerData != null && CustomerData?.UserFind){
        setcustomerData(CustomerData);
      }
    } catch (err:any) {
      console.error('Error during fetch data:', err);
      handleFetchWithTokenRefresh(err, cookies, setCookie, fetchData, "Error during fetch data");
    }
  };

  useEffect(() => {
    fetchData();
  },[page, rowsPerPage, quickSearch,sortOrder]);

  useEffect(() => {
    if (isPagination) {
      fetchData();
      setIsPagination(false); 
    }
  }, [isPagination]);

  const fetchDataByID = async () => {
    try {		
      const CustomerIdData = await CustomerService.getCustomerById(FId);
      if(CustomerIdData != undefined && CustomerIdData != null && CustomerIdData?.UserFindOneById){
        setCustomerDataById(CustomerIdData);
      }
    } catch (err:any) {
      console.error('Error during fetch data:', err);
      handleFetchWithTokenRefresh(err, cookies, setCookie, fetchDataByID, "Error during fetch data");
    }
  };

  useEffect(() => {
    if (FId !== 0) {
      fetchDataByID();
    }
  },[FId]);

  useEffect(() => {
    const fetchStateData = async () => {
      try {
        const statedata = await MasterService.GetState(parseInt(countryId));
        setStateData(statedata ?? null);
      } catch (error:any) {
        console.log('Error fetching state data:', error);
        handleFetchWithTokenRefresh(error, cookies, setCookie, fetchStateData, "Error during fetch data"); 
        setStateData(null); 
      }
    };
    fetchStateData();
  }, [countryId]); 

  useEffect(() => {
    const fetchCityData = async () => {
      try {
        const citydata = await MasterService.GetCity(stateId);
        setCityData(citydata ?? null);
      } catch (error:any) {
        console.log('Error fetching city data:', error);
        handleFetchWithTokenRefresh(error, cookies, setCookie, fetchCityData, "Error during fetch data"); 
        setCityData(null);
      }
    };
   fetchCityData();
  }, [stateId]); 

  useEffect(() => {
    const fetchCountryData = async () => {
      try {
        const countrydata = await MasterService.GetCountry();
        setCountryData(countrydata ?? null);
      } catch (error:any) {
        console.log('Error fetching country data:', error);
        handleFetchWithTokenRefresh(error, cookies, setCookie, fetchCountryData, "Error during fetch data"); 
      }
    };
    fetchCountryData();
  }, []);

  const countryChange = async(event: SelectChangeEvent<string>) => {
    formik.setFieldValue('country_id', event.target.value); 
    setCountryId(event.target.value);
  };

  const stateChange = async(event: SelectChangeEvent<string>) =>{
    formik.setFieldValue('state_id', event.target.value); 
    setStateId(parseInt(event.target.value));
  }


  const setFormikValues = () => {
    if (customerDataById) {
      formik.setValues({
        fname:customerDataById?.UserFindOneById?.fname || "",
        lname:customerDataById?.UserFindOneById?.lname || "",
        primary_email :customerDataById?.UserFindOneById?.primary_email || "",
        primary_mobile:customerDataById?.UserFindOneById?.primary_mobile || "",
        address:customerDataById?.UserFindOneById?.fr_user_addresses?.[0]?.address || "",
        city_id:Number(customerDataById?.UserFindOneById?.fr_user_addresses?.[0]?.fr_city?.id) || 0,
        state_id:Number(customerDataById?.UserFindOneById?.fr_user_addresses?.[0]?.fr_state?.id)|| 0,
        country_id:customerDataById?.UserFindOneById?.fr_user_addresses?.[0]?.country_id || 0,
        signup_source:"web"
      });
    }
  }
  
  useEffect(() => {
    setFormikValues();
  }, [customerDataById]);

  const emptyRows =
    page > 0 ? Math.max(0, (1 + page) * rowsPerPage - (customerData?.UserFind?.total || 0)) : 0;

  const handleChangePage = (
    event: React.MouseEvent<HTMLButtonElement> | null,
    newPage: number
  ) => {
    setPage(newPage);
  };

  const handleChangeRowsPerPage = (
    event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
  ) => {
    setRowsPerPage(parseInt(event.target.value, 10));
    setPage(0);
  };

  
  const handleClickOpen = (Title:string) => {
    setTitle(Title);
    setOpen(true);
    formik.resetForm();  
    setChanges("Add");  
    setBtnName("Create");
  };

  const handleEditOpen = (Title:string, Id: number,CountrID:number,cityID: number) => {
    setTitle(Title);
    setFId(Id);
    setOpen(true);
    if(countryId !=undefined)
    setCountryId(CountrID.toString());
    setStateId(cityID);
 
     if(formik.values.fname === ''){
      setFormikValues();
    } 
    setChanges("Edit"); 
    setBtnName("Update");
  };
  const handleClose = () => {
    setOpen(false);
    setFId(0);
    setCountryId("");
    setStateId(0);
    formik.resetForm();
  };

  const handleDelClickOpen = (Id:number,authID:number) => {
    setDelId(Id);
    setAuthId(authID)
    setDelOpen(true);
  };
  const handleDelClose = () => {
    setDelOpen(false);
    setFId(0);
  };

  const handleViewClickOpen = (Id:number) => {
    setViewOpen(true);
    setFId(Id);
    setBtnName("Send");
    if(formik.values.fname === ''){
      setFormikValues();
    } 
  };

  const handleViewClose = () => {
    setViewOpen(false);
    setViewOpenOTP(false)
    setFId(0);
  };


  const handleResendOtp = async(OTpEmail:any)=>{
    let customerSendOtp
    try{
       customerSendOtp = await UserOtpService.createOtpSigninFromButtonClick(OTpEmail);
       console.log(customerSendOtp);
       
      if(customerSendOtp?.AppOtpSignin?.snapshot?.success){
          toast.success(customerSendOtp?.AppOtpSignin?.snapshot?.success[0], {
            position: "bottom-left",
            autoClose: 2000,
        });
      }
    }catch(error:any){
      console.log('GraphQL Mutation Error:', error);
      handleFetchWithTokenRefresh(error, cookies, setCookie, handleResendOtp, `${error}`);
    }
 }
 

  const handleDelSubmit = async() => {
    try {	
      const AuthorizationDelete = await CustomerService.deleteCustomerAuthorization(authId);
      const AuthenticationDelete = await CustomerService.deleteCustomerAuthentication(delId);
      const AddressDelete = await CustomerAddressService.deleteCustomerAddress(delId);
      const customerDelData = await CustomerService.deleteCustomer(delId);
      if(customerDelData && customerDelData.UserDelete?.affected == 1){
        setcustomerData((prevData) => {
          if (!prevData || !prevData.UserFind) {
              return prevData;
          }

          const filteredRows = (prevData.UserFind.rows || []).filter(item => item.id !== delId);
          const total = ((prevData.UserFind.total-1) || 0);
          const pages = Math.ceil(total / rowsPerPage); 
          setFId(0);

          if(prevData?.UserFind?.pages !== pages){
            setIsPagination(true);
          }
          
          return {
              ...prevData,
              UserFind: {
                  ...prevData.UserFind,
                  rows: filteredRows,
                  total: total,
                  pages: pages
              },
          };
       });
        if(customerDelData?.UserDelete?.snapshot?.error[0]){
          const errorMsg =  customerDelData?.UserDelete?.snapshot?.error[0]
          toast.error(errorMsg, {
            position: "bottom-left",
            autoClose: 2000,
          });
        }else{
          toast.success('Entry Deleted Successfully !!', {
            position: "bottom-left",
            autoClose: 2000,
        });
      }
        setPage(0);
        setDelOpen(false);
      }
      
    } catch (err:any) {
      console.error('Error during delete data:', err);
      handleFetchWithTokenRefresh(err, cookies, setCookie, handleDelSubmit, "Error during delete data");
    } 

  };

  const handleSort = async() => {
    const newSortOrder = sortOrder === 'ASC' ? 'DESC' : 'ASC';
    setSortOrder(newSortOrder);
    await fetchData(); 
  };

  const handleInputChange = () => (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { value } = e.target;
    setQuickSearch(value);
  };


  return (
    <>
      <Card
        sx={{
          boxShadow: "none",
          borderRadius: "7px",
          mb: "25px",
          padding: { xs: "18px", sm: "20px", lg: "25px" },
        }}
        className="rmui-card"
      >

            <Box
              sx={{
                display: { xs: "block", sm: "flex" },
                alignItems: "center",
                justifyContent: "space-between",
                float:"left"
              }}
            >
            <TextField
                  variant="outlined"
                  placeholder="Search"
                  name="floorPlan"
                  fullWidth
                  //onBlur={(e) => handleInputChange()(e)}
                  onBlur={(e) => handleInputChange()(e)}
                  InputProps={{
                    startAdornment: (
                      <InputAdornment position="start">
                        <SearchIcon />
                      </InputAdornment>
                    ),
                  }}
                  sx={{
                    flexGrow: 1,
                    borderRadius: '50px', 
                    padding: '5px 15px', 
                    '& .MuiOutlinedInput-root': {
                      borderRadius: '50px', 
                    },
                    '& input': {
                      padding: '10px 10px', 
                    },
                  }}
                />
            </Box>
        <Box
          sx={{
            display: { xs: "block", sm: "flex" },
            alignItems: "center",
            justifyContent: "space-between",
            mb: "25px",
            float:"right"
          }}
        >
          <Button
            onClick={() => handleClickOpen("Add New Buyer")}
            variant="outlined"
            sx={{
              textTransform: "capitalize",
              borderRadius: "7px",
              fontWeight: "500",
              fontSize: "13px",
              padding: "6px 13px",
            }}
            title="Add"
            color="primary"
          >
            <AddIcon sx={{ position: "relative", top: "-1px" }} /> Add New
          </Button>
        </Box>

        {/* Table */}
        <Box
          sx={{
            marginLeft: "-25px",
            marginRight: "-25px",
          }}
        >
          <TableContainer
            component={Paper}
            sx={{
              boxShadow: "none",
              borderRadius: "0",
            }}
            className="rmui-table"
          >
            <Table sx={{ minWidth: 700 }} aria-label="Offer Strength Table">
              <TableHead className="bg-primary-50">
                <TableRow>
                  <TableCell
                    sx={{
                      fontWeight: "500",
                      padding: "10px 24px",
                      fontSize: "14px",
                      width:"15%"
                    }}
                    className="text-black border-bottom"
                  >
                     <IconButton
                          aria-label="sort"
                          color="primary"
                          sx={{ padding: "5px" }}
                          onClick={handleSort}
                        >
                          {sortOrder === 'ASC' ? (
                            <ArrowUpward sx={{ fontSize: '16px' }} />
                          ) : (
                            <ArrowDownward sx={{ fontSize: '16px' }} />
                          )}
                        </IconButton>
                     Name
                  </TableCell>

                  <TableCell
                    sx={{
                      fontWeight: "500",
                      padding: "10px 20px",
                      fontSize: "14px",
                    }}
                    className="text-black border-bottom"
                  >
                    E-mail
                  </TableCell>

                  <TableCell
                    sx={{
                      fontWeight: "500",
                      padding: "10px 20px",
                      fontSize: "14px",
                    }}
                    className="text-black border-bottom"
                  >
                    Phone 
                  </TableCell>
                  <TableCell
                    sx={{
                      fontWeight: "500",
                      padding: "10px 20px",
                      fontSize: "14px",
                    }}
                    className="text-black border-bottom"
                  >
                     Address
                  </TableCell>

                  <TableCell
                    sx={{
                      fontWeight: "500",
                      padding: "10px 20px",
                      fontSize: "14px",
                      width:"10%",
                      textAlign:"center"
                    }}
                    className="text-black border-bottom"
                  >
                    Action
                  </TableCell>
                </TableRow>
              </TableHead>

              <TableBody>
                {customerData?.UserFind?.rows && customerData.UserFind?.rows.length > 0 ? (
                customerData.UserFind?.rows.map((row) => (
                    <TableRow key={row.id}>
                      <TableCell
                        sx={{
                          padding: "5px 13px",
                          fontSize: "14px",
                          width: "65px",
                        }}
                        className="border-bottom"
                      >
                      {row?.fname} {row?.lname}
                      </TableCell>

                      <TableCell
                        sx={{
                          padding: "15px 20px",
                          fontSize: "14px",
                        }}
                        className="border-bottom"
                      >
                        {row?.primary_email}
                      </TableCell>
                      <TableCell
                        sx={{
                          padding: "15px 20px",
                          fontSize: "14px",
                        }}
                        className="border-bottom"
                      >
                     {row?.primary_mobile} 
                      </TableCell>
                      <TableCell
                        sx={{
                          padding: "15px 20px",
                          fontSize: "14px",
                        }}
                        className="border-bottom"
                      >
                         {row?.fr_user_addresses[0]?.address} 
                      </TableCell>

                      <TableCell
                        sx={{
                          padding: "15px 20px",
                        }}
                        className="border-bottom"
                      >
                        <Box
                          sx={{
                            display: "flex",
                            alignItems: "center",
                            float:"right"
                          }}
                        >
                          <IconButton
                          aria-label="view"
                          color="primary"
                          title="View"
                          sx={{ padding: "5px" }}
                          onClick={() => handleViewClickOpen(row?.fr_user_authorisations?.[0]?.au_id)}
                          >
                          <i
                              className="material-symbols-outlined"
                              style={{ fontSize: "16px" }}
                          >
                              visibility
                          </i>
                          </IconButton>


                          <IconButton
                          aria-label="edit"
                          color="secondary"
                          title="edit"
                          sx={{ padding: "5px" }}
                          onClick={() => 
                            handleEditOpen("Edit Buyer", row?.fr_user_authorisations?.[0]?.au_id,row?.fr_user_addresses?.[0]?.country_id,row?.fr_user_addresses?.[0]?.state_id)}
                          >
                          <i
                              className="material-symbols-outlined"
                              style={{ fontSize: "16px" }}
                          >
                              edit
                          </i>
                          </IconButton>
                          

                          <IconButton
                            aria-label="delete"
                            color="error"
                            title="Delete"
                            sx={{ padding: "5px" }}
                            onClick={() => handleDelClickOpen(row?.fr_user_authorisations?.[0]?.au_id,row?.fr_user_authorisations?.[0]?.id)}
                          >
                            <i
                              className="material-symbols-outlined"
                              style={{ fontSize: "16px" }}
                            >
                              delete
                            </i>
                          </IconButton>

                        {/* <Button
                          variant="text"
                          color="primary"
                          size="small"
                          
                          sx={{ textTransform: "none", padding: "5px" }} 
                        >
                          Regenerate Password
                        </Button> */}

                        <IconButton
                          aria-label="regenerate-password"
                          color="primary"
                          sx={{ padding: "5px" }}
                          title="Resend Password"
                          onClick={() => handleResendOtp(row?.primary_email)} 
                        >
                          <i className="material-symbols-outlined" style={{ fontSize: "16px" }}>
                          mail
                          </i>
                        </IconButton>   
                        </Box>
                      </TableCell>
                    </TableRow>
                  ))
                ) : (
                  <TableRow>
                    <TableCell colSpan={8} align="center">
                      No data available.
                    </TableCell>
                  </TableRow>
                )}
                {emptyRows > 0 && (
                  <TableRow style={{ height: 53 * emptyRows }}>
                    <TableCell colSpan={8} />
                  </TableRow>
                )}
              </TableBody>

              <TableFooter>
                <TableRow>
                  <TablePagination
                    rowsPerPageOptions={[
                      5,
                      10,
                      25,
                      { label: "All", value: -1 },
                    ]}
                    colSpan={8}
                    count={customerData?.UserFind?.total || 0}
                    rowsPerPage={rowsPerPage}
                    page={page}
                    slotProps={{
                      select: {
                        inputProps: {
                          "aria-label": "rows per page",
                        },
                        native: true,
                      },
                    }}
                    onPageChange={handleChangePage}
                    onRowsPerPageChange={handleChangeRowsPerPage}
                    ActionsComponent={TablePaginationActions}
                    sx={{
                      border: "none",
                    }}
                  />
                </TableRow>
              </TableFooter>
            </Table>
          </TableContainer>
        </Box>
      </Card>

      {/* Modal */}
     <BootstrapDialog
        onClose={handleClose}
        aria-labelledby="customized-dialog-title"
        open={open}
        className="rmu-modal"
        PaperProps={{
            sx: { width: { xs: '100%', sm: '100%', md: '100%' }, maxWidth: '500px' }
          }}
      >
        <Box>
          <Box
            sx={{
              display: "flex",
              justifyContent: "space-between",
              alignItems: "center",
              background: "#f6f7f9",
              padding: { xs: "15px 20px", md: "25px" },
            }}
            className="rmu-modal-header"
          >
            <Typography
              id="modal-modal-title"
              variant="h6"
              sx={{
                fontWeight: "600",
                fontSize: { xs: "16px", md: "18px" },
              }}
              className="text-black"
            >
              {title}
            </Typography>

            <IconButton aria-label="remove" size="small" onClick={handleClose}>
              <ClearIcon />
            </IconButton>
          </Box>

          <Box className="rmu-modal-content">
            <Box component="form" onSubmit={formik.handleSubmit}>
              <Box
                sx={{
                  padding: "25px",
                  borderRadius: "8px",
                }}
                className="bg-white"
              >
             
                <Box mb={2}>
                    <Typography
                      component="h5"
                      sx={{
                        fontWeight: "500",
                        fontSize: "14px",
                        mb: "12px",
                      }}
                      className="text-black"
                    >
                    First Name
                    </Typography>

                    <TextField
                      autoComplete="fname"
                      name="fname"
                      fullWidth
                      id="fname"
                      label="First Name"
                      value = {formik.values.fname}
                      onChange={formik.handleChange}
                      onBlur={formik.handleBlur}
                      error={Boolean(formik.touched.fname && formik.errors.fname)}
                      helperText={formik.touched.fname && formik.errors.fname}
                    />
                </Box>

                <Box mb={2}>
                    <Typography
                      component="h5"
                      sx={{
                        fontWeight: "500",
                        fontSize: "14px",
                        mb: "12px",
                      }}
                      className="text-black"
                    >
                    Last Name
                    </Typography>

                    <TextField
                      autoComplete="lname"
                      name="lname"
                      fullWidth
                      id="lname"
                      label="Last Name"
                      value = {formik.values.lname}
                      onChange={formik.handleChange}
                      onBlur={formik.handleBlur}
                      error={Boolean(formik.touched.lname && formik.errors.lname)}
                      helperText={formik.touched.lname && formik.errors.lname}
                    />
                </Box>

                <Box mb={2}>
                    <Typography
                      component="h5"
                      sx={{
                        fontWeight: "500",
                        fontSize: "14px",
                        mb: "12px",
                      }}
                      className="text-black"
                    >
                      Email
                    </Typography>

                    <TextField
                      autoComplete="primary_email"
                      name="primary_email"
                      fullWidth
                      id="primary_email"
                      label="Email"
                      value = {formik.values.primary_email}
                      onChange={formik.handleChange}
                      onBlur={formik.handleBlur}
                      error={Boolean(formik.touched.primary_email && formik.errors.primary_email)}
                      helperText={formik.touched.primary_email && formik.errors.primary_email}
                    />
                </Box>

                <Box mb={2}>
                    <Typography
                      component="h5"
                      sx={{
                        fontWeight: "500",
                        fontSize: "14px",
                        mb: "12px",
                      }}
                      className="text-black"
                    >
                      Phone
                    </Typography>
                   
                    <FormControl fullWidth>
                    <InputMask
                      mask="999-9999999"
                      type="text"
                      name="primary_mobile"
                      id="primary_mobile"
                      placeholder="(xxx) xxx-xxx"
                      className={`phoneinput ${formik.touched.primary_mobile && formik.errors.primary_mobile ? 'is-invalid' : ''}`}
                      value={formik.values.primary_mobile}
                      onChange={handleChange}
                    />
                      {formik.touched.primary_mobile && formik.errors.primary_mobile ? (
                          <div className="invalid-feedback mt-3 ms-2" style={{color:'red',fontSize:"10px"}}>{formik.errors.primary_mobile}</div>
                          ) : null}
                    </FormControl>
                </Box>

                <Box flex={1} >
                    <Typography
                          component="h5"
                          sx={{
                            fontWeight: "500",
                            fontSize: "14px",
                            mb: "12px",
                          }}
                          className="text-black"
                        >
                          Address
                        </Typography>

                    <TextField
                      autoComplete="address"
                      name="address"
                      fullWidth
                      id="address"
                      label="Address"
                      value = {formik.values.address}
                      onChange={formik.handleChange}
                      onBlur={formik.handleBlur}
                      error={Boolean(formik.touched.address && formik.errors.address)}
                      helperText={formik.touched.address && formik.errors.address}
                    />
                </Box>
                <Box flex={1} mt={2}>
                      <Typography
                              component="h5"
                              sx={{
                                fontWeight: "500",
                                fontSize: "14px",
                                mb: "12px",
                              }}
                              className="text-black"
                            >
                            Country
                        </Typography>
                        <FormControl fullWidth>
                          <InputLabel id="country-label">Country</InputLabel>
                          {countryData?.CountryFind?.rows && (
                            <Select
                             autoComplete="country_id"
                              labelId="country-label"
                              id="country_id"
                              value={String(formik.values.country_id) || ""}
                              label="Country"
                              name="country_id"
                              placeholder="Country"
                              onChange={countryChange}
                              onBlur={formik.handleBlur}
                            >
                            {countryData.CountryFind.rows.map((row) => (
                                <MenuItem key={row.id} value={row.id}> 
                                    {row.name} 
                                </MenuItem>
                            ))}
                            
                          </Select>
                          )}
                          {formik.touched.country_id && formik.errors.country_id && (
                              <FormHelperText sx={{ color: "red" }}>{formik.errors.country_id}</FormHelperText>
                            )}
                        </FormControl>
                </Box>
                <Box mb={2} mt={2} display="flex" justifyContent="space-between">
                      <Box flex={1} mr={1}>
                        <Typography
                              component="h5"
                              sx={{
                                fontWeight: "500",
                                fontSize: "14px",
                                mb: "12px",
                              }}
                              className="text-black"
                            >
                              State
                        </Typography>
                        <FormControl fullWidth>
                          <InputLabel id="state-label">State</InputLabel>
                          {stateData?.StateFind?.rows && (
                            <Select
                                labelId="state-label"
                                id="state_id"
                                name="state_id"
                                value={String(formik.values.state_id) || ""}
                                label="State"
                                placeholder="State"
                                onChange={stateChange}
                                onBlur={formik.handleBlur}
                              >
                              {stateData.StateFind.rows.map((row) => (
                                  <MenuItem key={row.id} value={row.id}> 
                                      {row.name} 
                                  </MenuItem>
                              ))}
                              
                            </Select>
                          )}
                            {formik.touched.state_id && formik.errors.state_id && (
                                <FormHelperText sx={{ color: "red" }}>{formik.errors.state_id}</FormHelperText>
                              )}
                          </FormControl>
                      </Box>

                      <Box flex={1} ml={1}>
                        <Typography
                          component="h5"
                          sx={{
                            fontWeight: "500",
                            fontSize: "14px",
                            mb: "12px",
                          }}
                          className="text-black"
                        >
                          City
                        </Typography>
                        <FormControl fullWidth>
                        <InputLabel id="city-label">City</InputLabel>
                        
                        {cityData?.CityFind?.rows && (
                        <Select
                            labelId="city-label"
                            id="city_id"
                            value={String(formik.values.city_id) || ""}
                            label="City"
                            name="city_id"
                            placeholder="City"
                            onChange={formik.handleChange}
                            onBlur={formik.handleBlur}
                          >
                          
                          {cityData.CityFind.rows.map((row) => (
                              <MenuItem key={row.id} value={row.id}> 
                                  {row.name} 
                              </MenuItem>
                          ))}
                        </Select>
                        )}
                        {formik.touched.city_id && formik.errors.city_id && (
                          <FormHelperText sx={{ color: "red" }}>{formik.errors.city_id}</FormHelperText>
                        )}
                        </FormControl>
                      </Box>
                </Box>
                 
                <Box mt={2} display="flex" justifyContent="flex-end" gap="10px">
                    <Box
                      sx={{
                        display: "flex",
                        alignItems: "center",
                        justifyContent: "end",
                        gap: "10px",
                      }}
                    >
                      <Button
                        onClick={handleClose}
                        variant="outlined"
                        color="error"
                        sx={{
                          textTransform: "capitalize",
                          borderRadius: "8px",
                          fontWeight: "500",
                          fontSize: "13px",
                          padding: "11px 30px",
                        }}
                      >
                        Cancel
                      </Button>

                      <Button
                        type="submit"
                        variant="contained"
                        sx={{
                          textTransform: "capitalize",
                          borderRadius: "8px",
                          fontWeight: "500",
                          fontSize: "13px",
                          padding: "11px 30px",
                          color: "#fff !important",
                        }}
                      >
                        <AddIcon
                          sx={{
                            position: "relative",
                            top: "-2px",
                          }}
                          className="mr-5px"
                        />{" "}
                        {btnName}
                      </Button>
                    </Box>
                </Box>
              </Box>
            </Box>
          </Box>
        </Box>
      </BootstrapDialog>

      {/*View */ }
     <BootstrapDialog
        onClose={handleViewClose}
        aria-labelledby="customized-dialog-title"
        open={viewOpen}
        className="rmu-modal"
        PaperProps={{
          sx: { width: { xs: '100%', sm: '100%', md: '100%' }, maxWidth: '500px' }
        }}
      >
        <Box>
          <Box
            sx={{
              display: "flex",
              justifyContent: "space-between",
              alignItems: "center",
              background: "#f6f7f9",
              padding: { xs: "15px 20px", md: "25px" },
            }}
            className="rmu-modal-header"
          >
            <Typography
              id="modal-modal-title"
              variant="h6"
              sx={{
                fontWeight: "600",
                fontSize: { xs: "16px", md: "18px" },
              }}
              className="text-black"
            >
              View Buyer
            </Typography>

            <IconButton aria-label="remove" size="small" onClick={handleViewClose}>
              <ClearIcon />
            </IconButton>
          </Box>

          <Box className="rmu-modal-content">
            <Box component="form">
              <Box
                sx={{
                  paddingLeft: "50px",
                  paddingRight: "50px",
                  paddingTop:"25px",
                  borderRadius: "8px",
                  backgroundColor: "white",
                }}
              >
                {[
                  { label: "Name ", value:  ": "+formik.values.fname},
                  { label: "Email ", value: ": "+formik.values.primary_email },
                  { label: "Phone ", value: ": "+formik.values.primary_mobile },
                  { label: "Address ", value: ": "+formik.values.address },

                ].map((field, index) => (
                  <Box mb={2} display="flex" justifyContent="space-between" key={index}>
                    <Typography
                      component="h5"
                      sx={{
                        fontWeight: "500",
                        fontSize: "14px",
                        mb: "12px",
                        flex: "1", 
                      }}
                      className="text-black"
                    >
                      {field.label}
                    </Typography>
                    <Typography
                      sx={{
                        fontSize: "14px",
                        color: "#555",
                        flex: "2", 
                      }}
                    >
                      {field.value}
                    </Typography>
                  </Box>
                ))}
              </Box>
            </Box>
          </Box>
        </Box>
      </BootstrapDialog> 
  
       {/* Delete Modal */}
      <BootstrapDialog
        onClose={handleDelClose}
        aria-labelledby="customized-dialog-title"
        open={delOpen}
        className="rmu-modal"
      >
        <Box>
          <Box
            sx={{
              display: "flex",
              justifyContent: "space-between",
              alignItems: "center",
              background: "#f6f7f9",
              padding: { xs: "15px 20px", md: "5px" },
            }}
            className="rmu-modal-header"
          >
            <DialogTitle sx={{ m: 0, p: 2 }} id="customized-dialog-title">
              Delete Confirmation
            </DialogTitle>
            <IconButton aria-label="remove" size="small" onClick={handleDelClose}>
              <ClearIcon />
            </IconButton>
          </Box>

           <DialogContent dividers>
              <Typography gutterBottom>
                Are you sure want to delete this entry ?
              </Typography>
              
            </DialogContent>
            
            <DialogActions>
                <Button variant="outlined"
                          color="error" 
                          onClick={handleDelSubmit}>Delete</Button>
                <Button variant="outlined"
                          onClick={handleDelClose}>Cancel</Button>
            </DialogActions> 
            
         
        </Box>
      </BootstrapDialog>

    
      <ToastContainer/>
    </>
  );
};
//export default Customer;
export default withAuth(Customer, routes.customer.auth, RoleEnum.ADMIN);