import React, { useEffect, useState, useRef, Fragment } from 'react';
import MainCard from 'components/MainCard';
import { useTheme } from '@mui/material/styles';
import Loader from 'components/Loader';
import { Empty } from 'antd';
import dayjs from 'dayjs';
import { enqueueSnackbar } from 'notistack';
import AddressAutocomplete from 'components/nearle_components/AddressAutocomplete';
import {
  Stack,
  Table,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TableBody,
  Typography,
  IconButton,
  Box,
  Grid,
  TextField,
  Tooltip,
  Collapse,
  Tab,
  Tabs,
  Divider,
  Card,
  CardContent,
  CardActions,
  Button,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  FormLabel,
  TablePagination,
  Skeleton,
  Avatar,
  Paper,
  Select,
  MenuItem,
  useMediaQuery
} from '@mui/material';
import { MobileCard, MobileCardList, MobileField, MobileFieldGrid } from 'components/nearle_components/MobileCard';
import {
  EyeOutlined,
  EyeInvisibleOutlined,
  EditOutlined,
  IssuesCloseOutlined,
  StopOutlined,
  CloseOutlined
} from '@ant-design/icons';
import { PopupTransition } from 'components/@extended/Transitions';
import { FaRegCheckCircle, FaRegAddressCard } from 'react-icons/fa';
import { TbBrandDatabricks, TbWorldLongitude, TbWorldLatitude } from 'react-icons/tb';
import { GiMoneyStack, GiModernCity } from 'react-icons/gi';
import { FiUser, FiPhoneCall } from 'react-icons/fi';
import {
  MdNumbers,
  MdGroups,
  MdCheckCircle,
  MdHourglassEmpty,
  MdCancel,
  MdOutlineCheckCircle,
  MdOutlinePendingActions,
  MdOutlineCancel,
  MdMyLocation,
  MdPersonPin,
  MdPlace,
  MdAdd,
  MdEdit,
  MdDeleteOutline,
  MdPeopleAlt
} from 'react-icons/md';
import { LuMail } from 'react-icons/lu';
import { BiUser } from 'react-icons/bi';
import LocationAutocomplete from 'components/nearle_components/LocationAutocomplete';
import DebounceSearchBar from 'components/nearle_components/DebounceSearchBar';
import PageHeader from 'components/nearle_components/PageHeader';
import StatCard from 'components/nearle_components/StatCard';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { getalltenants, gettenantsummary } from 'pages/api/api';
import {
  getAdminPricing,
  getDoormilePricing,
  createAdminPricing,
  updateAdminTenant,
  getTenantLocations,
  createTenantLocation,
  updateTenantLocation,
  getTenantCustomers,
  createTenantCustomer,
  updateTenantCustomer,
  deleteTenantCustomer
} from 'pages/api/doormileApi';
import { OrdersTableSkeleton } from '../orders/OrdersTableSkeleton';

// ============================================================================
// Design tokens — shared with the deliveries page so every surface (header,
// filters, KPI tiles, tabs, badges, dialogs) speaks the same visual language.
// ============================================================================
const DT = {
  radiusPill: 999,
  radiusCard: 14,
  radiusInner: 12,
  shadowSoft: '0 1px 2px rgba(15, 23, 42, 0.04), 0 8px 24px rgba(15, 23, 42, 0.05)',
  shadowMd: '0 1px 3px rgba(15, 23, 42, 0.06)',
  shadowPop: '0 12px 32px rgba(15, 23, 42, 0.12)',
  textPrimary: '#0f172a',
  textSecondary: '#64748b',
  textMuted: '#94a3b8',
  borderSubtle: '#e2e8f0',
  divider: '#f1f5f9',
  surface: '#ffffff',
  surfaceAlt: '#f8fafc'
};

const a = (c, suffix) => `${c}${suffix}`;
const tint = (c) => a(c, '08');
const soft = (c) => a(c, '18');
const ring = (c) => a(c, '26');
const edge = (c) => a(c, '55');

// Status palette — drives the pill tabs and per-row badges.
const STATUS_META = {
  active:   { label: 'Active',   color: '#10b981', icon: MdCheckCircle,    statusKey: 'active' },
  pending:  { label: 'Pending',  color: '#f59e0b', icon: MdHourglassEmpty, statusKey: 'pending' },
  inactive: { label: 'Inactive', color: '#ef4444', icon: MdCancel,         statusKey: 'inactive' }
};

const STATUS_TABS = [
  { status: 'active',   countKey: 'active',   tabStatus: 'Active' },
  { status: 'pending',  countKey: 'pending',  tabStatus: 'Pending' },
  { status: 'inactive', countKey: 'inactive', tabStatus: 'InActive' }
];

const KPI_META = [
  { key: 'active',   label: 'Active Tenants',   color: '#10b981', icon: MdOutlineCheckCircle,    countKey: 'active' },
  { key: 'pending',  label: 'Pending Approval', color: '#f59e0b', icon: MdOutlinePendingActions, countKey: 'pending' },
  { key: 'inactive', label: 'Inactive Tenants', color: '#ef4444', icon: MdOutlineCancel,         countKey: 'inactive' }
];

const SoftPaper = (props) => (
  <Paper
    {...props}
    sx={{
      mt: 0.75,
      borderRadius: 2,
      boxShadow: DT.shadowPop,
      border: '1px solid',
      borderColor: 'divider',
      overflow: 'hidden'
    }}
  />
);

const AccentAvatar = ({ color, selected, size = 24, children }) => (
  <Avatar
    sx={{
      width: size,
      height: size,
      bgcolor: selected ? color : soft(color),
      color: selected ? '#fff' : color,
      transition: 'background-color 0.15s, color 0.15s'
    }}
  >
    {children}
  </Avatar>
);

// ==============================|| Tenant locations (branches/sites) dialog ||============================== //
// Self-contained — deliberately does not touch the existing openRowIndex1/2 +
// Tabs collapse machinery above, which is fragile legacy state. GET/POST/PUT
// /admin/tenants/:id/locations + /admin/tenantlocations/:id per
// jupiter2doormile.md §2.4 — no location UI existed anywhere before this.
const emptyLocationForm = {
  locationid: null,
  locationname: '',
  address: '',
  city: '',
  state: '',
  pincode: '',
  isprimary: false,
  status: 'active'
};

const TenantLocationsDialog = ({ tenant, open, onClose }) => {
  const queryClient = useQueryClient();
  const [form, setForm] = useState(emptyLocationForm);
  const [formOpen, setFormOpen] = useState(false);

  const { data: locations = [], isLoading } = useQuery({
    queryKey: ['tenant-locations', tenant?.tenantid],
    queryFn: () => getTenantLocations(tenant.tenantid),
    enabled: !!tenant?.tenantid && open
  });

  const saveMutation = useMutation({
    mutationFn: (payload) =>
      payload.locationid ? updateTenantLocation(payload.locationid, payload.data) : createTenantLocation(tenant.tenantid, payload.data),
    onSuccess: (res) => {
      if (res.success) {
        enqueueSnackbar(form.locationid ? 'Location updated' : 'Location added', {
          variant: 'success',
          anchorOrigin: { vertical: 'top', horizontal: 'right' },
          autoHideDuration: 2000
        });
        queryClient.invalidateQueries({ queryKey: ['tenant-locations', tenant?.tenantid] });
        setForm(emptyLocationForm);
        setFormOpen(false);
      } else {
        enqueueSnackbar(res.message || 'Failed to save location', {
          variant: 'error',
          anchorOrigin: { vertical: 'top', horizontal: 'right' },
          autoHideDuration: 2000
        });
      }
    },
    onError: (err) => {
      enqueueSnackbar(err.response?.data?.message || err.message || 'Failed to save location', {
        variant: 'error',
        anchorOrigin: { vertical: 'top', horizontal: 'right' },
        autoHideDuration: 2000
      });
    }
  });

  const handleSave = () => {
    if (!form.locationname || !form.address) {
      enqueueSnackbar('Fill Location Name and Address', {
        variant: 'error',
        anchorOrigin: { vertical: 'top', horizontal: 'right' },
        autoHideDuration: 2000
      });
      return;
    }
    const { locationid, ...data } = form;
    saveMutation.mutate({ locationid, data });
  };

  const openEdit = (loc) => {
    setForm({
      locationid: loc.locationid,
      locationname: loc.locationname || '',
      address: loc.address || '',
      city: loc.city || '',
      state: loc.state || '',
      pincode: loc.pincode || '',
      isprimary: !!loc.isprimary,
      status: loc.status || 'active'
    });
    setFormOpen(true);
  };

  return (
    <Dialog open={open} onClose={onClose} maxWidth="sm" fullWidth>
      <DialogTitle sx={{ fontWeight: 700 }}>
        Locations · {tenant?.tenantname}
      </DialogTitle>
      <DialogContent dividers>
        {isLoading ? (
          <Typography variant="body2" sx={{ color: DT.textSecondary, py: 2 }}>
            Loading locations…
          </Typography>
        ) : locations.length === 0 && !formOpen ? (
          <Empty description="No locations added yet" />
        ) : (
          <Stack spacing={1.5}>
            {locations.map((loc) => (
              <Paper key={loc.locationid} variant="outlined" sx={{ p: 1.5, borderRadius: 2 }}>
                <Stack direction="row" justifyContent="space-between" alignItems="flex-start">
                  <Box>
                    <Typography sx={{ fontWeight: 700 }}>
                      {loc.locationname} {loc.isprimary && '· Primary'}
                    </Typography>
                    <Typography variant="caption" sx={{ color: DT.textSecondary }}>
                      {[loc.address, loc.city, loc.state, loc.pincode].filter(Boolean).join(', ')}
                    </Typography>
                  </Box>
                  <IconButton size="small" onClick={() => openEdit(loc)}>
                    <MdEdit size={14} />
                  </IconButton>
                </Stack>
              </Paper>
            ))}
          </Stack>
        )}

        {formOpen && (
          <Grid container spacing={1.5} sx={{ mt: 1.5, pt: 1.5, borderTop: `1px solid ${DT.divider}` }}>
            <Grid item xs={12} sm={6}>
              <TextField
                fullWidth
                label="Location Name"
                value={form.locationname}
                onChange={(e) => setForm((f) => ({ ...f, locationname: e.target.value }))}
              />
            </Grid>
            <Grid item xs={12} sm={6}>
              <TextField fullWidth label="Pincode" value={form.pincode} onChange={(e) => setForm((f) => ({ ...f, pincode: e.target.value }))} />
            </Grid>
            <Grid item xs={12}>
              <TextField fullWidth label="Address" value={form.address} onChange={(e) => setForm((f) => ({ ...f, address: e.target.value }))} />
            </Grid>
            <Grid item xs={12} sm={6}>
              <TextField fullWidth label="City" value={form.city} onChange={(e) => setForm((f) => ({ ...f, city: e.target.value }))} />
            </Grid>
            <Grid item xs={12} sm={6}>
              <TextField fullWidth label="State" value={form.state} onChange={(e) => setForm((f) => ({ ...f, state: e.target.value }))} />
            </Grid>
          </Grid>
        )}
      </DialogContent>
      <DialogActions sx={{ px: 3, pb: 2 }}>
        {formOpen ? (
          <>
            <Button
              onClick={() => {
                setFormOpen(false);
                setForm(emptyLocationForm);
              }}
            >
              Cancel
            </Button>
            <Button variant="contained" onClick={handleSave}>
              {form.locationid ? 'Save Changes' : 'Add Location'}
            </Button>
          </>
        ) : (
          <>
            <Button onClick={onClose}>Close</Button>
            <Button variant="contained" startIcon={<MdAdd size={16} />} onClick={() => setFormOpen(true)}>
              Add Location
            </Button>
          </>
        )}
      </DialogActions>
    </Dialog>
  );
};

// ==============================|| Tenant customers dialog ||============================== //
// GET /admin/tenantcustomers has no documented tenantid filter (unlike
// locations, which are nested under /admin/tenants/:id/locations) — filtered
// client-side here the same way fetchclientpricelist already filters
// /admin/pricing client-side, since neither endpoint accepts the param.
// createclient.js used to (incorrectly) create tenant customers instead of
// tenants; now that it correctly creates tenants, this dialog is the only
// place left that can create one.
const emptyCustomerForm = { id: null, firstname: '', lastname: '', phone: '', email: '' };

// GET /admin/tenantcustomers doesn't document its id field name either — same
// defensive fallback as customers.js's custId() rather than assuming `id`.
const tenantCustId = (row) => row.id ?? row.tenantcustomerid ?? row.customerid;

const TenantCustomersDialog = ({ tenant, open, onClose }) => {
  const queryClient = useQueryClient();
  const [form, setForm] = useState(emptyCustomerForm);
  const [formOpen, setFormOpen] = useState(false);

  const { data: allCustomers = [], isLoading } = useQuery({
    queryKey: ['tenant-customers-all'],
    queryFn: getTenantCustomers,
    enabled: open
  });

  const customers = (allCustomers || []).filter((c) => !tenant?.tenantid || c.tenantid === tenant.tenantid);

  const saveMutation = useMutation({
    mutationFn: (payload) => (payload.id ? updateTenantCustomer(payload.id, payload.data) : createTenantCustomer(payload.data)),
    onSuccess: (res) => {
      if (res.success) {
        enqueueSnackbar(form.id ? 'Customer updated' : 'Customer added', {
          variant: 'success',
          anchorOrigin: { vertical: 'top', horizontal: 'right' },
          autoHideDuration: 2000
        });
        queryClient.invalidateQueries({ queryKey: ['tenant-customers-all'] });
        setForm(emptyCustomerForm);
        setFormOpen(false);
      } else {
        enqueueSnackbar(res.message || 'Failed to save customer', {
          variant: 'error',
          anchorOrigin: { vertical: 'top', horizontal: 'right' },
          autoHideDuration: 2000
        });
      }
    },
    onError: (err) => {
      enqueueSnackbar(err.response?.data?.message || err.message || 'Failed to save customer', {
        variant: 'error',
        anchorOrigin: { vertical: 'top', horizontal: 'right' },
        autoHideDuration: 2000
      });
    }
  });

  const deleteMutation = useMutation({
    mutationFn: (id) => deleteTenantCustomer(id),
    onSuccess: (res) => {
      if (res.success) {
        enqueueSnackbar('Customer deleted', {
          variant: 'success',
          anchorOrigin: { vertical: 'top', horizontal: 'right' },
          autoHideDuration: 2000
        });
        queryClient.invalidateQueries({ queryKey: ['tenant-customers-all'] });
      } else {
        enqueueSnackbar(res.message || 'Failed to delete customer', {
          variant: 'error',
          anchorOrigin: { vertical: 'top', horizontal: 'right' },
          autoHideDuration: 2000
        });
      }
    },
    onError: (err) => {
      enqueueSnackbar(err.response?.data?.message || err.message || 'Failed to delete customer', {
        variant: 'error',
        anchorOrigin: { vertical: 'top', horizontal: 'right' },
        autoHideDuration: 2000
      });
    }
  });

  const handleSave = () => {
    if (!form.firstname || !form.phone) {
      enqueueSnackbar('Fill Name and Phone', {
        variant: 'error',
        anchorOrigin: { vertical: 'top', horizontal: 'right' },
        autoHideDuration: 2000
      });
      return;
    }
    const { id, ...data } = form;
    saveMutation.mutate({ id, data });
  };

  const openEdit = (row) => {
    setForm({
      id: tenantCustId(row),
      firstname: row.firstname || '',
      lastname: row.lastname || '',
      phone: row.phone || '',
      email: row.email || ''
    });
    setFormOpen(true);
  };

  const handleDelete = (row) => {
    if (window.confirm(`Delete customer "${row.firstname}"?`)) deleteMutation.mutate(tenantCustId(row));
  };

  return (
    <Dialog open={open} onClose={onClose} maxWidth="sm" fullWidth>
      <DialogTitle sx={{ fontWeight: 700 }}>Customers · {tenant?.tenantname}</DialogTitle>
      <DialogContent dividers>
        {isLoading ? (
          <Typography variant="body2" sx={{ color: DT.textSecondary, py: 2 }}>
            Loading customers…
          </Typography>
        ) : customers.length === 0 && !formOpen ? (
          <Empty description="No customers yet" />
        ) : (
          <Stack spacing={1.5}>
            {customers.map((c) => (
              <Paper key={tenantCustId(c)} variant="outlined" sx={{ p: 1.5, borderRadius: 2 }}>
                <Stack direction="row" justifyContent="space-between" alignItems="flex-start">
                  <Box>
                    <Typography sx={{ fontWeight: 700 }}>
                      {c.firstname} {c.lastname}
                    </Typography>
                    <Typography variant="caption" sx={{ color: DT.textSecondary }}>
                      {[c.phone, c.email].filter(Boolean).join(' · ')}
                    </Typography>
                  </Box>
                  <Stack direction="row" spacing={0.5}>
                    <IconButton size="small" onClick={() => openEdit(c)}>
                      <MdEdit size={14} />
                    </IconButton>
                    <IconButton size="small" onClick={() => handleDelete(c)} sx={{ color: '#ef4444' }}>
                      <MdDeleteOutline size={14} />
                    </IconButton>
                  </Stack>
                </Stack>
              </Paper>
            ))}
          </Stack>
        )}

        {formOpen && (
          <Grid container spacing={1.5} sx={{ mt: 1.5, pt: 1.5, borderTop: `1px solid ${DT.divider}` }}>
            <Grid item xs={12} sm={6}>
              <TextField fullWidth label="First Name" value={form.firstname} onChange={(e) => setForm((f) => ({ ...f, firstname: e.target.value }))} />
            </Grid>
            <Grid item xs={12} sm={6}>
              <TextField fullWidth label="Last Name" value={form.lastname} onChange={(e) => setForm((f) => ({ ...f, lastname: e.target.value }))} />
            </Grid>
            <Grid item xs={12} sm={6}>
              <TextField fullWidth label="Phone" value={form.phone} onChange={(e) => setForm((f) => ({ ...f, phone: e.target.value }))} />
            </Grid>
            <Grid item xs={12} sm={6}>
              <TextField fullWidth label="Email" value={form.email} onChange={(e) => setForm((f) => ({ ...f, email: e.target.value }))} />
            </Grid>
          </Grid>
        )}
      </DialogContent>
      <DialogActions sx={{ px: 3, pb: 2 }}>
        {formOpen ? (
          <>
            <Button
              onClick={() => {
                setFormOpen(false);
                setForm(emptyCustomerForm);
              }}
            >
              Cancel
            </Button>
            <Button variant="contained" onClick={handleSave}>
              {form.id ? 'Save Changes' : 'Add Customer'}
            </Button>
          </>
        ) : (
          <>
            <Button onClick={onClose}>Close</Button>
            <Button variant="contained" startIcon={<MdAdd size={16} />} onClick={() => setFormOpen(true)}>
              Add Customer
            </Button>
          </>
        )}
      </DialogActions>
    </Dialog>
  );
};

// ==============================|| Starts here||============================== //
const Clients1 = () => {
  const textFieldRef = useRef(null);
  const [searchword, setSearchword] = useState('');
  const [debouncedSearch, setDebouncedSearch] = useState('');
  const [rowsPerPage, setRowsPerPage] = React.useState(10);
  // const [tenantList, settenantList] = useState([]);
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down('md'));
  const [isloader, setisloader] = useState(false);
  const [appId, setAppId] = useState(0);
  const [locaName, setLocoName] = useState('');
  const [locations] = useState('All');
  const [value0, setValue0] = useState(0);
  const [value1, setValue1] = useState(0);
  const [value2, setValue2] = useState(0);
  const [selectedTenid, setSelectedtenid] = useState(null);
  const [clientpricelist, setClientpricelist] = useState([]);
  const [status, setstatus] = useState('active');
  const [selectedCustomer, setSelectedCustomer] = useState({}); // to edit
  const [dialogopen, setDialogopen] = useState(false);
  const [, setAppPricing] = useState([]);
  const [selectedPricing, setSelectedPricing] = useState({});
  const [isPrice, setIsprice] = useState(true);
  const [city, setCity] = useState('');
  const [zipcode, setZipcode] = useState('');
  const [latlong, setLatlong] = useState({});
  const [editClient, setEditClient] = useState({});
  const [page, setPage] = useState(0);

  const handleChangePage = (event, newPage) => {
    setPage(newPage);
  };

  const handleChangeRowsPerPage = (event) => {
    setRowsPerPage(parseInt(event.target.value, 10));
    setPage(0);
  };
  const dialogclose = () => {
    setDialogopen(false);
  };

  const handleChange = (event, newValue) => {
    setValue0(newValue);
    setSearchword('');
    setPage(0);
  };
  const handleChange1 = (event, newValue1) => {
    console.log('newValue1', newValue1);
    setValue1(newValue1);
  };
  const handleChange2 = (event, newValue2) => {
    console.log('newValue2', newValue2);
    setValue2(newValue2);
  };

  const [openRowIndex1, setOpenRowIndex1] = useState(null); // Initially no row is open for collapsible section 1
  const [openRowIndex2, setOpenRowIndex2] = useState(null); // Initially no row is open for collapsible section 2
  const [locationsDialogTenant, setLocationsDialogTenant] = useState(null);
  const [customersDialogTenant, setCustomersDialogTenant] = useState(null);
  // Handle toggling for collapsible section 1
  const handleCollapseToggle1 = (rowIndex) => {
    setOpenRowIndex1((prevIndex) => (prevIndex === rowIndex ? null : rowIndex));
  };
  // Handle toggling for collapsible section 2
  const handleCollapseToggle2 = (rowIndex) => {
    setOpenRowIndex2((prevIndex) => (prevIndex === rowIndex ? null : rowIndex));
  };
  useEffect(() => {
    console.log('selectedCustomer', selectedCustomer);
  }, [selectedCustomer]);
  useEffect(() => {
    setOpenRowIndex1(-1);
    setOpenRowIndex2(-1);
  }, [value0]);

  /* ============================================= || opentoast || ============================================= */

  const opentoast = (message, variant, duration) => {
    enqueueSnackbar(message, {
      variant: variant,
      anchorOrigin: { vertical: 'top', horizontal: 'right' },
      autoHideDuration: duration
    });
  };
  // ==============================|| address autocomplete ||============================== //
  const handleAddressPlaceSelected = (place) => {
    const lat = place.geometry.location.lat();
    const lng = place.geometry.location.lng();
    setLatlong({ lat, lng });
    setEditClient((prev) => ({
      ...prev,
      address: place.formatted_address,
      latitude: lat.toString(),
      longitude: lng.toString()
    }));

    let city1, zipcode1, state1, suburb1;
    place.address_components.forEach((component) => {
      component.types.forEach((type) => {
        switch (type) {
          case 'locality':
            city1 = component.long_name;
            break;
          case 'administrative_area_level_1':
            state1 = component.long_name;
            break;
          case 'postal_code':
            zipcode1 = component.long_name;
            break;
          case 'sublocality':
          case 'sublocality_level_1':
            suburb1 = component.long_name;
            break;
        }
      });
    });
    setCity(city1 || '');
    setState(state1 || '');
    setZipcode(zipcode1 || '');
    setSuburb(suburb1 || '');
    setEditClient((prev) => ({
      ...prev,
      city: city1 || '',
      state: state1 || '',
      postcode: zipcode1 || '',
      suburb: suburb1 || ''
    }));
  };

  useEffect(() => {
    selectedCustomer &&
      setLatlong({
        lat: selectedCustomer.latitude,
        lng: selectedCustomer.longitude
      });
  }, [selectedCustomer]);
  /* ============================================= || handleKeyPress (ctrl+k)| ============================================= */
  useEffect(() => {
    const handleKeyPress = (event) => {
      if (event.key === 'k' && (event.metaKey || event.ctrlKey)) {
        event.preventDefault();

        textFieldRef.current.focus();
      }
      if (event.key === 'Escape' && document.activeElement === textFieldRef.current) {
        // Remove focus from the TextField
        textFieldRef.current.blur();
      }
    };
    document.addEventListener('keydown', handleKeyPress);

    return () => {
      document.removeEventListener('keydown', handleKeyPress);
    };
  }, []);

  /* ============================================= || getalltenants| ============================================= */

  const {
    data: tenantList,
    isLoading: getalltenantsIsLoading,
    refetch: getalltenantsRefetch
  } = useQuery({
    queryKey: ['tenantList', appId, debouncedSearch, status, page, rowsPerPage],
    queryFn: getalltenants
  });

  // ==============================|| gettenantsummary  ||============================== //
  const {
    data: summaryData = [],
    isLoading: summaryDataIsLoading,
    refetch: summaryDataRefetch
  } = useQuery({
    queryKey: ['gettenantsummary', appId, status],
    queryFn: gettenantsummary
  });

  /* ============================================= || fetchclientpricelist || ============================================= */

  // /admin/pricing has no tenantid query param documented — filter client-side.
  const fetchclientpricelist = async () => {
    try {
      const pricing = await getAdminPricing();
      setClientpricelist((pricing || []).filter((p) => p.tenantid === selectedTenid));
    } catch (err) {
      console.log(err);
    }
  };
  useEffect(() => {
    selectedTenid && fetchclientpricelist();
  }, [selectedTenid]);

  /* ============================================= || fetchTenanatPricing || ============================================= */
  const fetchTenanatPricing = async (id) => {
    try {
      const pricing = await getAdminPricing();
      setTenanatPricing((pricing || []).filter((p) => p.tenantid === id));
    } catch (error) {
      console.log('fetchTenanatPricing', error);
    }
  };
  useEffect(() => {
    selectedTenid && fetchTenanatPricing(selectedTenid);
  }, [selectedTenid]);
  /* ============================================= || tenantupdate || ============================================= */

  const tenantupdate = async (tenid) => {
    setisloader(true);
    let targetId;
    let updateData;
    if (tenid == -1) {
      targetId = selectedTenid;
      updateData = { approved: 1 };
    } else {
      targetId = tenid;
      updateData = { status: status === 'active' ? 'InActive' : 'Active' };
    }

    try {
      const res = await updateAdminTenant(targetId, updateData);
      if (res.success) {
        opentoast(
          value0 == 0 ? 'Inactivated Successfully' : value0 == 1 ? 'Approved Successfully' : 'Activate Successfully',
          'success',
          2000
        );
        getalltenantsRefetch();
        summaryDataRefetch();
      }
    } catch (err) {
      console.log(err);
      opentoast(err.message, 'error', 1500);
    } finally {
      setisloader(false);
    }
  };
  /* ============================================= || getAppPricing || ============================================= */
  // /admin/doormile-pricing has no zone query param documented — filter client-side.
  const getAppPricing = async (id) => {
    try {
      const pricing = await getDoormilePricing();
      setAppPricing((pricing || []).filter((p) => !id || p.applocationid === id));
    } catch (error) {
      console.log('appPricingRes', error);
    }
  };
  /* ============================================= || createpricing || ============================================= */
  const createpricing = async () => {
    setisloader(true);
    try {
      const res = await createAdminPricing({
        applocationid: appId,
        tenantid: selectedTenid,
        vehicletype: selectedPricing.vehicletype || 'Bike',
        baseprice: +selectedPricing.baseprice || 0,
        baseweight: +selectedPricing.baseweight || 0,
        priceperkm: +selectedPricing.priceperkm || 0,
        priceperkg: +selectedPricing.priceperkg || 0,
        basedistance: +selectedPricing.basedistance || 0,
        handlingcharges: +selectedPricing.handlingcharges || 0,
        effectivefrom: dayjs().format('YYYY-MM-DD'),
        currency: 'INR',
        priority: 1,
        status: 'active'
      });
      if (res.success) {
        enqueueSnackbar('Price Created Successfully', {
          variant: 'success',
          anchorOrigin: { vertical: 'top', horizontal: 'right' },
          autoHideDuration: 2000
        });
        dialogclose();
        setSelectedPricing({});
        tenantupdate(-1);
        fetchclientpricelist();
      } else {
        opentoast(res.message || 'Failed to save pricing', 'error', 2000);
      }
    } catch (err) {
      console.log(err);
      opentoast(err.response?.data?.message || err.message || 'Failed to save pricing', 'error', 2000);
    }
  };
  /* ============================================= || updateClient || ============================================= */
  const updateClient = async () => {
    try {
      const updateRes = await updateAdminTenant(selectedTenid, editClient);
      if (updateRes.success) {
        opentoast(updateRes.message || 'Updated Successfully', 'success', 1500);
      } else {
        opentoast(updateRes.message || 'Update Failed', 'error', 1500);
      }
      getalltenantsRefetch();
      summaryDataRefetch();
    } catch (err) {
      console.log('updateClient', err);
      opentoast(err.response?.data?.message || err.message || 'Update Failed', 'error', 1500);
    }
  };

  const activeTabMeta = STATUS_META[STATUS_TABS[value0]?.status] || STATUS_META.active;

  return (
    <>
      {(getalltenantsIsLoading || summaryDataIsLoading || isloader) && <Loader />}
      {/* ============================================= || Header | ============================================= */}
      <PageHeader
        title="Tenants"
        subtitle={`Live · ${locaName || 'All Zones'}`}
        live
        action={
          <LocationAutocomplete
            locations={locations}
            locaName={locaName}
            setAppId={setAppId}
            setLocoName={setLocoName}
            setPage={setPage}
            pill
            accentColor="#662582"
            icon={<MdMyLocation size={14} />}
            placeholder="Select Zone"
            paperComponent={SoftPaper}
            sx={{ width: { xs: '100%', sm: 280 }, zIndex: 100 }}
          />
        }
      />

      {/* ============================================= || KPI Cards | ============================================= */}
      <Grid container spacing={{ xs: 2, md: 2.5 }} sx={{ mb: { xs: 1.5, md: 2 } }}>
        {KPI_META.map((item, idx) => {
          const Icon = item.icon;
          const value = summaryData?.[item.countKey] ?? 0;
          return (
            <Grid item key={item.key} xs={12} sm={4}>
              <Box
                onClick={() => {
                  if (idx >= 0) handleChange(null, idx);
                }}
                sx={{ cursor: 'pointer', height: '100%' }}
              >
                <StatCard
                  title={item.label}
                  value={value ?? 0}
                  icon={<Icon size={20} />}
                  color={idx === 0 ? '#662582' : item.color}
                  loading={summaryDataIsLoading}
                />
              </Box>
            </Grid>
          );
        })}
      </Grid>

      {/* ============================================= || Status Tabs + Search || ============================================= */}
      <Paper
        elevation={0}
        sx={{
          mt: { xs: 1.5, md: 2 },
          p: { xs: 1, md: 1.5 },
          borderTopLeftRadius: DT.radiusCard / 8,
          borderTopRightRadius: DT.radiusCard / 8,
          borderBottomLeftRadius: 0,
          borderBottomRightRadius: 0,
          border: '1px solid',
          borderColor: DT.borderSubtle,
          borderBottom: 0,
          background: '#fff'
        }}
      >
        <Stack
          direction="row"
          alignItems="center"
          justifyContent="space-between"
          gap={1.5}
          sx={{ flexWrap: 'wrap-reverse' }}
        >
          <Stack
            direction="row"
            spacing={0.75}
            sx={{
              flex: 1,
              overflowX: 'auto',
              py: 0.5,
              px: 0.25,
              '&::-webkit-scrollbar': { height: 6 },
              '&::-webkit-scrollbar-thumb': { backgroundColor: DT.borderSubtle, borderRadius: 4 }
            }}
          >
            {STATUS_TABS.map((t, idx) => {
              const meta = STATUS_META[t.status];
              const Icon = meta.icon;
              const active = value0 === idx;
              const count = summaryData?.[t.countKey] ?? 0;
              return (
                <Box
                  key={t.status}
                  onClick={() => {
                    setstatus(t.status);
                    handleChange(null, idx);
                  }}
                  sx={{
                    display: 'inline-flex',
                    alignItems: 'center',
                    gap: { xs: 0.625, md: 0.875 },
                    pl: 0.5,
                    pr: { xs: 1, md: 1.25 },
                    py: 0.5,
                    flexShrink: 0,
                    cursor: 'pointer',
                    borderRadius: '10px',
                    border: `1px solid ${active ? meta.color : '#e2e8f0'}`,
                    bgcolor: active ? meta.color : '#fff',
                    color: active ? '#fff' : '#64748b',
                    fontWeight: 600,
                    boxShadow: 'none',
                    transition: 'background-color 0.15s, border-color 0.15s, color 0.15s',
                    '&:hover': {
                      borderColor: active ? meta.color : '#cbd5e1',
                      bgcolor: active ? meta.color : '#f8fafc'
                    }
                  }}
                >
                  <Avatar
                    sx={{
                      width: { xs: 22, md: 26 },
                      height: { xs: 22, md: 26 },
                      bgcolor: active ? 'rgba(255,255,255,0.22)' : soft(meta.color),
                      color: active ? '#fff' : meta.color
                    }}
                  >
                    <Icon size={13} />
                  </Avatar>
                  <Typography
                    variant="caption"
                    sx={{ fontWeight: 600, fontSize: { xs: 11.5, md: 13 }, lineHeight: 1 }}
                  >
                    {meta.label}
                  </Typography>
                  <Box
                    sx={{
                      minWidth: { xs: 22, md: 26 },
                      height: { xs: 18, md: 22 },
                      px: 0.625,
                      display: 'inline-flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      borderRadius: 999,
                      fontSize: { xs: 10, md: 11 },
                      fontWeight: 700,
                      bgcolor: active ? 'rgba(255,255,255,0.22)' : '#f8fafc',
                      color: active ? '#fff' : '#64748b',
                      border: 'none'
                    }}
                  >
                    {summaryDataIsLoading ? <Skeleton variant="text" width={14} height={10} /> : count}
                  </Box>
                </Box>
              );
            })}
          </Stack>

          {/* Search */}
          <Box sx={{ width: { xs: '100%', sm: 240, lg: 280 }, flex: { xs: '1 1 100%', sm: '0 0 auto' } }}>
            <DebounceSearchBar
              value={searchword}
              onChange={setSearchword}
              onDebouncedChange={setDebouncedSearch}
              sx={{
                m: 0,
                width: '100%',
                borderRadius: 999,
                bgcolor: tint('#662582'),
                '& fieldset': { borderColor: edge('#662582'), borderWidth: 1.5 },
                '&:hover fieldset': { borderColor: '#662582' },
                '&.Mui-focused fieldset': { borderColor: '#662582', borderWidth: 2 },
                '&.Mui-focused': { boxShadow: `0 0 0 3px ${ring('#662582')}` }
              }}
            />
          </Box>
        </Stack>
      </Paper>

      {/* ============================================= || Table || ============================================= */}
      <Paper
        elevation={0}
        sx={{
          borderTopLeftRadius: 0,
          borderTopRightRadius: 0,
          borderBottomLeftRadius: DT.radiusCard / 8,
          borderBottomRightRadius: DT.radiusCard / 8,
          border: '1px solid',
          borderColor: DT.borderSubtle,
          overflow: 'hidden',
          background: '#fff'
        }}
      >
        <TableContainer
          sx={{
            display: { xs: 'none', md: 'block' },
            maxHeight: { xs: 'calc(100vh - 220px)', md: 'calc(100vh - 190px)' },
            '&::-webkit-scrollbar': { width: '10px', height: '10px' },
            '&::-webkit-scrollbar-thumb': {
              backgroundColor: edge('#662582'),
              borderRadius: '8px',
              '&:hover': { backgroundColor: '#662582' }
            },
            '&::-webkit-scrollbar-track': { backgroundColor: DT.surfaceAlt }
          }}
        >
          <Table stickyHeader sx={{ minWidth: { xs: 720, md: 960 } }}>
            <TableHead>
              <TableRow
                sx={{
                  '& th': {
                    backgroundColor: DT.surfaceAlt,
                    color: DT.textSecondary,
                    fontSize: { xs: 10, md: 11 },
                    fontWeight: 800,
                    letterSpacing: 0.6,
                    textTransform: 'uppercase',
                    whiteSpace: 'nowrap',
                    borderBottom: `1px solid ${DT.borderSubtle}`,
                    py: { xs: 1, md: 1.25 },
                    px: { xs: 1, md: 2 }
                  }
                }}
              >
                <TableCell>#</TableCell>
                <TableCell>Status</TableCell>
                <TableCell>Client</TableCell>
                <TableCell>Contact</TableCell>
                <TableCell>Address</TableCell>
                <TableCell align="right">Actions</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {getalltenantsIsLoading && <OrdersTableSkeleton />}

              {tenantList?.length == 0 && !isloader ? (
                <TableRow>
                  <TableCell colSpan={6} sx={{ py: 6 }}>
                    <Stack alignItems="center" spacing={1.5}>
                      <Avatar sx={{ width: 64, height: 64, bgcolor: soft('#94a3b8'), color: DT.textMuted }}>
                        <MdGroups size={28} />
                      </Avatar>
                      <Typography variant="subtitle1" sx={{ fontWeight: 700, color: DT.textPrimary }}>
                        No tenants to show
                      </Typography>
                      <Typography variant="caption" sx={{ color: DT.textSecondary }}>
                        {`No ${activeTabMeta.label.toLowerCase()} tenants for this filter.`}
                      </Typography>
                    </Stack>
                  </TableCell>
                </TableRow>
              ) : (
                tenantList?.map((row, index) => {
                  const rowStatusKey = (value0 === 0 ? 'active' : value0 === 1 ? 'pending' : 'inactive');
                  const rowStatusMeta = STATUS_META[rowStatusKey];
                  const RowStatusIcon = rowStatusMeta.icon;
                  return (
                  <Fragment key={row.tenantid ?? index}>
                    {/* ============================================ || tablerow 1 || ============================================ */}
                    <TableRow
                      sx={{
                        cursor: 'pointer',
                        transition: 'background-color 0.15s',
                        '& td': {
                          borderBottom: `1px solid ${DT.divider}`,
                          py: { xs: 1, md: 1.5 },
                          px: { xs: 1, md: 2 }
                        },
                        '&:hover': { backgroundColor: DT.surfaceAlt }
                      }}
                    >
                      <TableCell>
                        <Typography variant="caption" sx={{ fontWeight: 700, color: DT.textMuted }}>
                          {String(index + 1 + page * rowsPerPage).padStart(2, '0')}
                        </Typography>
                      </TableCell>
                      <TableCell>
                        <Stack
                          direction="row"
                          alignItems="center"
                          spacing={0.5}
                          sx={{
                            display: 'inline-flex',
                            pl: 0.5,
                            pr: 1,
                            py: 0.25,
                            borderRadius: 999,
                            bgcolor: tint(rowStatusMeta.color),
                            border: `1px solid ${edge(rowStatusMeta.color)}`,
                            color: rowStatusMeta.color
                          }}
                        >
                          <AccentAvatar color={rowStatusMeta.color} size={20}>
                            <RowStatusIcon size={12} />
                          </AccentAvatar>
                          <Typography variant="caption" sx={{ fontWeight: 800, fontSize: 11, lineHeight: 1 }}>
                            {rowStatusMeta.label}
                          </Typography>
                        </Stack>
                      </TableCell>
                      <TableCell>
                        <Stack direction="row" alignItems="center" spacing={1}>
                          <AccentAvatar color="#662582" size={32}>
                            <MdPersonPin size={16} />
                          </AccentAvatar>
                          <Stack>
                            <Typography variant="subtitle2" sx={{ fontWeight: 700, color: DT.textPrimary, whiteSpace: 'nowrap' }}>
                              {row.tenantname}
                            </Typography>
                            <Typography variant="caption" sx={{ color: DT.textSecondary }}>
                              ID #{row.tenantid}
                            </Typography>
                          </Stack>
                        </Stack>
                      </TableCell>
                      <TableCell>
                        <Stack>
                          <Typography variant="subtitle2" sx={{ fontWeight: 700, color: DT.textPrimary, whiteSpace: 'nowrap' }}>
                            {row.primarycontact || '—'}
                          </Typography>
                          <Typography variant="caption" sx={{ color: DT.textSecondary }}>
                            {row.primaryemail || '—'}
                          </Typography>
                        </Stack>
                      </TableCell>
                      <TableCell sx={{ maxWidth: 280 }}>
                        <Tooltip title={row.address || ''} placement="top">
                          <Typography
                            variant="caption"
                            sx={{
                              color: DT.textSecondary,
                              display: '-webkit-box',
                              WebkitLineClamp: 2,
                              WebkitBoxOrient: 'vertical',
                              overflow: 'hidden'
                            }}
                          >
                            {row.address || '—'}
                          </Typography>
                        </Tooltip>
                      </TableCell>
                      <TableCell align="right">
                        <Stack direction="row" spacing={0.75} justifyContent="flex-end">
                          {value0 == 0 && (
                            <Tooltip title="Inactivate" placement="top">
                              <IconButton
                                size="small"
                                sx={{
                                  bgcolor: soft('#ef4444'),
                                  color: '#ef4444',
                                  border: `1px solid ${edge('#ef4444')}`,
                                  '&:hover': { bgcolor: '#ef4444', color: '#fff' }
                                }}
                                onClick={() => {
                                  setSelectedCustomer(row);
                                  setSelectedtenid(row.tenantid);
                                  setAppId(row.applocationid);
                                  setTimeout(() => {
                                    tenantupdate(row.tenantid);
                                  }, 100);
                                }}
                              >
                                <StopOutlined style={{ fontSize: 14 }} />
                              </IconButton>
                            </Tooltip>
                          )}
                          {value0 == 1 && (
                            <Tooltip title="Approve" placement="top">
                              <IconButton
                                size="small"
                                sx={{
                                  bgcolor: soft('#f59e0b'),
                                  color: '#f59e0b',
                                  border: `1px solid ${edge('#f59e0b')}`,
                                  '&:hover': { bgcolor: '#f59e0b', color: '#fff' }
                                }}
                                onClick={() => {
                                  setSelectedCustomer(row);
                                  setDialogopen(true);
                                  setSelectedtenid(row.tenantid);
                                  setAppId(row.applocationid);
                                  getAppPricing(row.applolcationid);
                                }}
                              >
                                <IssuesCloseOutlined style={{ fontSize: 14 }} />
                              </IconButton>
                            </Tooltip>
                          )}
                          {value0 == 2 && (
                            <Tooltip title="Activate" placement="top">
                              <IconButton
                                size="small"
                                sx={{
                                  bgcolor: soft('#10b981'),
                                  color: '#10b981',
                                  border: `1px solid ${edge('#10b981')}`,
                                  '&:hover': { bgcolor: '#10b981', color: '#fff' }
                                }}
                                onClick={() => {
                                  setSelectedCustomer(row);
                                  setSelectedtenid(row.tenantid);
                                  setAppId(row.applocationid);
                                  setTimeout(() => {
                                    tenantupdate(row.tenantid);
                                  }, 100);
                                }}
                              >
                                <FaRegCheckCircle style={{ fontSize: 14 }} />
                              </IconButton>
                            </Tooltip>
                          )}
                          <Tooltip title={openRowIndex1 === index ? 'Hide details' : 'View details'} placement="top">
                            <IconButton
                              size="small"
                              sx={{
                                bgcolor: openRowIndex1 === index ? '#662582' : soft('#662582'),
                                color: openRowIndex1 === index ? '#fff' : '#662582',
                                border: `1px solid ${edge('#662582')}`,
                                '&:hover': { bgcolor: '#662582', color: '#fff' }
                              }}
                              onClick={() => {
                                setSelectedCustomer(row);
                                handleCollapseToggle1(index);
                                setOpenRowIndex2(-1);
                                setSelectedtenid(row.tenantid);
                              }}
                            >
                              {openRowIndex1 === index ? <EyeInvisibleOutlined style={{ fontSize: 14 }} /> : <EyeOutlined style={{ fontSize: 14 }} />}
                            </IconButton>
                          </Tooltip>
                          <Tooltip title="Locations" placement="top">
                            <IconButton
                              size="small"
                              sx={{
                                bgcolor: soft('#0ea5e9'),
                                color: '#0ea5e9',
                                border: `1px solid ${edge('#0ea5e9')}`,
                                '&:hover': { bgcolor: '#0ea5e9', color: '#fff' }
                              }}
                              onClick={() => setLocationsDialogTenant(row)}
                            >
                              <MdPlace size={14} />
                            </IconButton>
                          </Tooltip>
                          <Tooltip title="Customers" placement="top">
                            <IconButton
                              size="small"
                              sx={{
                                bgcolor: soft('#14b8a6'),
                                color: '#14b8a6',
                                border: `1px solid ${edge('#14b8a6')}`,
                                '&:hover': { bgcolor: '#14b8a6', color: '#fff' }
                              }}
                              onClick={() => setCustomersDialogTenant(row)}
                            >
                              <MdPeopleAlt size={14} />
                            </IconButton>
                          </Tooltip>
                          {value0 !== 1 && (
                            <Tooltip title={openRowIndex2 === index ? 'Close' : 'Edit'} placement="top">
                              <IconButton
                                size="small"
                                sx={{
                                  bgcolor: openRowIndex2 === index ? '#8b5cf6' : soft('#8b5cf6'),
                                  color: openRowIndex2 === index ? '#fff' : '#8b5cf6',
                                  border: `1px solid ${edge('#8b5cf6')}`,
                                  '&:hover': { bgcolor: '#8b5cf6', color: '#fff' }
                                }}
                                onClick={() => {
                                  setSelectedCustomer(row);
                                  handleCollapseToggle2(index);
                                  setOpenRowIndex1(-1);
                                  setSelectedtenid(row.tenantid);
                                  setAppId(row.applocationid);
                                }}
                              >
                                {openRowIndex2 === index ? <CloseOutlined style={{ fontSize: 14 }} /> : <EditOutlined style={{ fontSize: 14 }} />}
                              </IconButton>
                            </Tooltip>
                          )}
                        </Stack>
                      </TableCell>
                    </TableRow>
                    {/* ============================================ || collapsive row  (1) (view) || ============================================ */}
                    {openRowIndex1 === index && (
                      <TableRow>
                        <TableCell sx={{ '&:hover': { backgroundColor: 'white !important' } }} colSpan={15}>
                          <Collapse
                            in={open}
                            timeout={800}
                            easing="ease-in-out"
                            mountOnEnter
                            unmountOnExit={false}
                            sx={{
                              '& .MuiCollapse-wrapperInner': {
                                transition: 'transform 800ms ease, opacity 800ms ease'
                              }
                            }}
                          >
                            <MainCard
                              content={false}
                              sx={{
                                transform: open ? 'translateY(0)' : 'translateY(-8px)',
                                opacity: open ? 1 : 0
                              }}
                              title={
                                <Tabs
                                  sx={{ bgcolor: 'primary.lighter' }}
                                  value={value1}
                                  onChange={handleChange1}
                                  aria-label="basic tabs example"
                                >
                                  <Tab
                                    label=" Details"
                                    icon={
                                      <TbBrandDatabricks
                                        style={{
                                          marginRight: 5,
                                          fontSize: '20px',
                                          marginBottom: -1
                                        }}
                                      />
                                    }
                                    sx={{
                                      alignItems: 'center',
                                      flexDirection: 'row'
                                    }}
                                  />
                                  <Tab
                                    label="Pricing"
                                    icon={
                                      <GiMoneyStack
                                        style={{
                                          marginRight: 5,
                                          fontSize: '20px',
                                          marginBottom: -1
                                        }}
                                      />
                                    }
                                    sx={{
                                      alignItems: 'center',
                                      flexDirection: 'row'
                                    }}
                                  />
                                </Tabs>
                              }
                            >
                              {/* ============================================= || Details || ============================================= */}
                              {value1 == 0 && (
                                <Grid container sx={{ m: 1 }} spacing={2.5} alignItems="center">
                                  <Grid item xs={6}>
                                    <Grid container spacing={4} alignItems="center">
                                      <Grid item>
                                        <FiUser
                                          style={{
                                            fontSize: '20px',
                                            fontWeight: 'lighter'
                                          }}
                                        />
                                      </Grid>
                                      <Grid item xs zeroMinWidth>
                                        <Typography align="left">{row.tenantname}</Typography>
                                        <Typography align="left" variant="caption" color="secondary">
                                          Tenant
                                        </Typography>
                                      </Grid>
                                    </Grid>
                                  </Grid>
                                  <Grid item xs={6}>
                                    <Grid container spacing={4} alignItems="center">
                                      <Grid item>
                                        <FiUser
                                          style={{
                                            fontSize: '20px',
                                            fontWeight: 'lighter'
                                          }}
                                        />
                                      </Grid>
                                      <Grid item xs zeroMinWidth>
                                        <Typography align="left">{row.firstname}</Typography>
                                        <Typography align="left" variant="caption" color="secondary">
                                          Contact Person
                                        </Typography>
                                      </Grid>
                                    </Grid>
                                  </Grid>
                                  <Grid item xs={6}>
                                    <Grid container spacing={4} alignItems="center">
                                      <Grid item>
                                        <FiPhoneCall
                                          style={{
                                            fontSize: '20px',
                                            fontWeight: 'lighter'
                                          }}
                                        />
                                      </Grid>
                                      <Grid item xs zeroMinWidth>
                                        <Typography align="left">{row.primarycontact}</Typography>
                                        <Typography align="left" variant="caption" color="secondary">
                                          Phone
                                        </Typography>
                                      </Grid>
                                    </Grid>
                                  </Grid>
                                  <Grid item xs={6}>
                                    <Grid container spacing={4} alignItems="center">
                                      <Grid item>
                                        <LuMail
                                          style={{
                                            fontSize: '20px',
                                            fontWeight: 'lighter'
                                          }}
                                        />
                                      </Grid>
                                      <Grid item xs zeroMinWidth>
                                        <Typography align="left">{row.primaryemail}</Typography>
                                        <Typography align="left" variant="caption" color="secondary">
                                          E-Mail
                                        </Typography>
                                      </Grid>
                                    </Grid>
                                  </Grid>
                                  <Grid item xs={12}>
                                    <Grid container spacing={4} alignItems="center">
                                      <Grid item>
                                        <FaRegAddressCard
                                          style={{
                                            fontSize: '20px',
                                            fontWeight: 'lighter'
                                          }}
                                        />
                                      </Grid>
                                      <Grid item xs zeroMinWidth>
                                        <Typography align="left">{row.address}</Typography>
                                        <Typography align="left" variant="caption" color="secondary">
                                          Address
                                        </Typography>
                                      </Grid>
                                    </Grid>
                                  </Grid>

                                  {/* <Grid item xs={12}>
                                    <Grid container spacing={4} alignItems="center">
                                      <Grid item>
                                        <TbCategoryMinus
                                          style={{
                                            fontSize: '20px',
                                            fontWeight: 'lighter'
                                          }}
                                        />
                                      </Grid>
                                      <Grid item xs zeroMinWidth>
                                        <Typography align="left">{row.subcategoryname}</Typography>
                                        <Typography align="left" variant="caption" color="secondary">
                                          Category
                                        </Typography>
                                      </Grid>
                                      <Grid item>
                                        <MdMyLocation
                                          style={{
                                            fontSize: '20px',
                                            fontWeight: 'lighter'
                                          }}
                                        />
                                      </Grid>
                                      <Grid item xs zeroMinWidth>
                                        <Typography align="left" variant="subtitle1">
                                          {row.suburb}
                                        </Typography>
                                        <Typography align="left" variant="caption" color="secondary">
                                          Location
                                        </Typography>
                                      </Grid>
                                    </Grid>
                                  </Grid> */}

                                  <Grid item xs={12}>
                                    <Grid container spacing={4} alignItems="center">
                                      <Grid item>
                                        <GiModernCity
                                          style={{
                                            fontSize: '20px',
                                            fontWeight: 'lighter'
                                          }}
                                        />
                                      </Grid>
                                      <Grid item xs zeroMinWidth>
                                        <Typography align="left">{row.city}</Typography>
                                        <Typography align="left" variant="caption" color="secondary">
                                          City
                                        </Typography>
                                      </Grid>
                                      <Grid item>
                                        <MdNumbers
                                          style={{
                                            fontSize: '20px',
                                            fontWeight: 'lighter'
                                          }}
                                        />
                                      </Grid>
                                      <Grid item xs zeroMinWidth>
                                        <Typography align="left" variant="subtitle1">
                                          {row.postcode}
                                        </Typography>
                                        <Typography align="left" variant="caption" color="secondary">
                                          PostCode
                                        </Typography>
                                      </Grid>
                                    </Grid>
                                  </Grid>
                                  <Grid item xs={12}>
                                    <Grid container spacing={4} alignItems="center">
                                      <Grid item>
                                        <TbWorldLatitude
                                          style={{
                                            fontSize: '20px',
                                            fontWeight: 'lighter'
                                          }}
                                        />
                                      </Grid>
                                      <Grid item xs zeroMinWidth>
                                        <Typography align="left">{row.latitude}</Typography>
                                        <Typography align="left" variant="caption" color="secondary">
                                          Latitude
                                        </Typography>
                                      </Grid>
                                      <Grid item>
                                        <TbWorldLongitude
                                          style={{
                                            fontSize: '20px',
                                            fontWeight: 'lighter'
                                          }}
                                        />
                                      </Grid>
                                      <Grid item xs zeroMinWidth>
                                        <Typography align="left" variant="subtitle1">
                                          {row.longitude}
                                        </Typography>
                                        <Typography align="left" variant="caption" color="secondary">
                                          Longitude
                                        </Typography>
                                      </Grid>
                                    </Grid>
                                  </Grid>
                                </Grid>
                              )}
                              {/* ============================================= || Pricing || ============================================= */}
                              {value1 == 1 && (
                                <Card variant="outlined" key={'left - card'} sx={{}}>
                                  <TableContainer>
                                    <Table>
                                      <TableHead>
                                        <TableRow>
                                          <TableCell>#</TableCell>
                                          <TableCell>Vehicle</TableCell>
                                          <TableCell>Base Price</TableCell>
                                          <TableCell>Price/Km</TableCell>
                                          <TableCell>Price/Kg</TableCell>
                                          <TableCell>Handling</TableCell>
                                          <TableCell>Status</TableCell>
                                        </TableRow>
                                      </TableHead>
                                      <TableBody>
                                        {clientpricelist?.length === 0 ? (
                                          <TableRow>
                                            <TableCell colSpan={7} align="center">
                                              <Empty description="No Pricing List" />
                                            </TableCell>
                                          </TableRow>
                                        ) : (
                                          clientpricelist.map((val, i) => (
                                            <TableRow key={val.pricingid || i} sx={{ bgcolor: 'white' }}>
                                              <TableCell>{i + 1}</TableCell>
                                              <TableCell>{val.vehicletype || '—'}</TableCell>
                                              <TableCell>{val.baseprice ?? '—'}</TableCell>
                                              <TableCell>{val.priceperkm ?? '—'}</TableCell>
                                              <TableCell>{val.priceperkg ?? '—'}</TableCell>
                                              <TableCell>{val.handlingcharges ?? '—'}</TableCell>
                                              <TableCell>{val.status || '—'}</TableCell>
                                            </TableRow>
                                          ))
                                        )}
                                      </TableBody>
                                    </Table>
                                  </TableContainer>
                                </Card>
                              )}
                            </MainCard>
                          </Collapse>
                        </TableCell>
                      </TableRow>
                    )}
                    {/* ============================================ || collapsive row (2) (edit)|| ============================================ */}
                    {openRowIndex2 === index && (
                      <TableRow>
                        <TableCell
                          sx={{ backgroundColor: 'white!important', '&:hover': { backgroundColor: 'white!important' } }}
                          colSpan={15}
                        >
                          {/* <Collapse in={true} timeout="auto" unmountOnExit> */}
                          <MainCard
                            content={false}
                            title={
                              <Box
                                sx={{
                                  bgcolor: 'primary.lighter',
                                  display: 'flex',
                                  justifyContent: 'space-between',
                                  alignItems: 'center'
                                }}
                              >
                                <Tabs value={value2} onChange={handleChange2} aria-label="basic tabs example">
                                  <Tab
                                    label="Edit Details"
                                    icon={
                                      <TbBrandDatabricks
                                        style={{
                                          marginRight: 5,
                                          fontSize: '20px',
                                          marginBottom: -1
                                        }}
                                      />
                                    }
                                    sx={{
                                      alignItems: 'center',
                                      flexDirection: 'row'
                                    }}
                                  />
                                  {value0 !== 1 && (
                                    <Tab
                                      label="Edit Pricing"
                                      icon={
                                        <GiMoneyStack
                                          style={{
                                            marginRight: 5,
                                            fontSize: '20px',
                                            marginBottom: -1
                                          }}
                                        />
                                      }
                                      sx={{
                                        alignItems: 'center',
                                        flexDirection: 'row'
                                      }}
                                      onClick={() => {
                                        getAppPricing(selectedCustomer.applolcationid);
                                      }}
                                    />
                                  )}
                                </Tabs>

                                {value2 == 1 && (
                                  <Button
                                    variant="contained"
                                    color={'error'}
                                    size="smaller"
                                    startIcon={<EditOutlined size={'small'} />}
                                    sx={{
                                      mr: 1.8,
                                      height: '30px'
                                    }}
                                    onClick={() => {
                                      setDialogopen(true);
                                    }}
                                  >
                                    Add Pricing
                                  </Button>
                                )}
                              </Box>
                            }
                          >
                            {/* ============================================= || Edit Details || ============================================= */}
                            {value2 == 0 && (
                              <Card variant="outlined" key={'left - card'} sx={{ m: 2 }}>
                                <Grid container spacing={0}>
                                  {/* =========================|| Edit Details (right) || =========================*/}
                                  <Grid item xs={12}>
                                    <Card variant="outlined">
                                      <CardContent>
                                        <Grid container spacing={2.5} alignItems="center">
                                          {/* =========================|| Tenant || =========================*/}
                                          <Grid item xs={6}>
                                            <Grid container spacing={4} alignItems="center">
                                              <Grid item>
                                                <BiUser
                                                  style={{
                                                    fontSize: '20px',
                                                    fontWeight: 'lighter'
                                                  }}
                                                />
                                              </Grid>
                                              <Grid item xs zeroMinWidth>
                                                <TextField
                                                  fullWidth
                                                  id="outlined-basic"
                                                  label={'Tenant Name'}
                                                  defaultValue={selectedCustomer.tenantname}
                                                  variant="outlined"
                                                  onChange={(e) => {
                                                    setEditClient({
                                                      ...editClient,
                                                      tenantname: e.target.value
                                                    });
                                                  }}
                                                  sx={{ mt: 2 }}
                                                />
                                              </Grid>
                                            </Grid>
                                          </Grid>{' '}
                                          {/* =========================|| Contact Person || =========================*/}
                                          <Grid item xs={6}>
                                            <Grid container spacing={4} alignItems="center">
                                              <Grid item>
                                                <FiUser
                                                  style={{
                                                    fontSize: '20px',
                                                    fontWeight: 'lighter'
                                                  }}
                                                />
                                              </Grid>
                                              <Grid item xs zeroMinWidth>
                                                <TextField
                                                  fullWidth
                                                  id="outlined-basic"
                                                  label={'Contact Person'}
                                                  defaultValue={row.firstname}
                                                  variant="outlined"
                                                  onChange={(e) => {
                                                    setEditClient({
                                                      ...editClient,
                                                      firstname: e.target.value
                                                    });
                                                  }}
                                                  sx={{ mt: 2 }}
                                                />
                                              </Grid>
                                            </Grid>
                                          </Grid>
                                          {/* =========================|| Contact Number || =========================*/}
                                          <Grid item xs={6}>
                                            <Grid container spacing={4} alignItems="center">
                                              <Grid item>
                                                <FiPhoneCall
                                                  style={{
                                                    fontSize: '20px',
                                                    fontWeight: 'lighter'
                                                  }}
                                                />
                                              </Grid>
                                              <Grid item xs zeroMinWidth>
                                                <TextField
                                                  inputProps={{ maxLength: 10 }}
                                                  fullWidth
                                                  id="outlined-basic"
                                                  label={'Contact Number'}
                                                  defaultValue={selectedCustomer.primarycontact}
                                                  variant="outlined"
                                                  onChange={(e) => {
                                                    setEditClient({
                                                      ...editClient,
                                                      primarycontact: e.target.value
                                                    });
                                                  }}
                                                  sx={{ mt: 2 }}
                                                />
                                              </Grid>
                                            </Grid>
                                          </Grid>
                                          {/* =========================|| E-Mail || =========================*/}
                                          <Grid item xs={6}>
                                            <Grid container spacing={4} alignItems="center">
                                              <Grid item>
                                                <LuMail
                                                  style={{
                                                    fontSize: '20px',
                                                    fontWeight: 'lighter'
                                                  }}
                                                />
                                              </Grid>
                                              <Grid item xs zeroMinWidth>
                                                <TextField
                                                  fullWidth
                                                  id="outlined-basic"
                                                  label={'E-Mail'}
                                                  defaultValue={selectedCustomer.primaryemail}
                                                  variant="outlined"
                                                  onChange={(e) => {
                                                    setEditClient({
                                                      ...editClient,
                                                      primaryemail: e.target.value
                                                    });
                                                  }}
                                                  sx={{ mt: 2 }}
                                                />
                                              </Grid>
                                            </Grid>
                                          </Grid>
                                          {/* =========================|| Address || =========================*/}
                                          <Grid item xs={12}>
                                            <Grid container spacing={4} alignItems="center">
                                              <Grid item>
                                                <FaRegAddressCard
                                                  style={{
                                                    fontSize: '20px',
                                                    fontWeight: 'lighter'
                                                  }}
                                                />
                                              </Grid>
                                              <Grid item xs zeroMinWidth>
                                                <AddressAutocomplete
                                                  id="address-autocomplete"
                                                  fullWidth
                                                  label="Address"
                                                  value={editClient?.address ?? selectedCustomer.address ?? ''}
                                                  onChange={(text) =>
                                                    setEditClient((prev) => ({
                                                      ...prev,
                                                      address: text
                                                    }))
                                                  }
                                                  onPlaceSelected={handleAddressPlaceSelected}
                                                  TextFieldProps={{ variant: 'outlined' }}
                                                />
                                              </Grid>
                                            </Grid>
                                          </Grid>
                                          {/* =========================|| category name || =========================*/}
                                          {/* <Grid item xs={12}>
                                            <Grid container spacing={4} alignItems="center">
                                              <Grid item>
                                                <TbCategoryMinus
                                                  style={{
                                                    fontSize: '20px',
                                                    fontWeight: 'lighter'
                                                  }}
                                                />
                                              </Grid>
                                              <Grid item xs zeroMinWidth>
                                                <TextField
                                                  fullWidth
                                                  required
                                                  id="outlined-required"
                                                  label="Category"
                                                  defaultValue={row.subcategoryname}
                                                  onChange={(e) => {
                                                    setEditClient({
                                                      ...editClient,
                                                      subcategoryname: e.target.value
                                                    });
                                                  }}
                                                />
                                              </Grid>
                                              <Grid item>
                                                <MdMyLocation
                                                  style={{
                                                    fontSize: '20px',
                                                    fontWeight: 'lighter'
                                                  }}
                                                />
                                              </Grid>
                                              <Grid item xs zeroMinWidth>
                                                <TextField
                                                  fullWidth
                                                  required
                                                  id="outlined-required"
                                                  label="Location"
                                                  onChange={(e) => {
                                                    setEditClient({
                                                      ...editClient,
                                                      suburb: e.target.value
                                                    });
                                                  }}
                                                  value={selectedCustomer.suburb}
                                                />
                                              </Grid>
                                            </Grid>
                                          </Grid> */}
                                          {/* =========================|| city || =========================*/}
                                          <Grid item xs={12}>
                                            <Grid container spacing={4} alignItems="center">
                                              <Grid item>
                                                <GiModernCity
                                                  style={{
                                                    fontSize: '20px',
                                                    fontWeight: 'lighter'
                                                  }}
                                                />
                                              </Grid>
                                              <Grid item xs zeroMinWidth>
                                                <TextField
                                                  fullWidth
                                                  required
                                                  id="outlined-required"
                                                  label="City"
                                                  onChange={(e) => {
                                                    setEditClient({
                                                      ...editClient,
                                                      city: e.target.value
                                                    });
                                                  }}
                                                  value={city == '' ? selectedCustomer.city : city}
                                                />
                                              </Grid>
                                              <Grid item>
                                                <MdNumbers
                                                  style={{
                                                    fontSize: '20px',
                                                    fontWeight: 'lighter'
                                                  }}
                                                />
                                              </Grid>
                                              <Grid item xs zeroMinWidth>
                                                <TextField
                                                  fullWidth
                                                  required
                                                  label=" PostCode"
                                                  id="outlined-required"
                                                  onChange={(e) => {
                                                    {
                                                      setEditClient({
                                                        ...editClient,
                                                        postcode: e.target.value
                                                      });
                                                    }
                                                  }}
                                                  value={zipcode == '' ? selectedCustomer.postcode : zipcode}
                                                />
                                              </Grid>
                                            </Grid>
                                          </Grid>
                                          {/* =========================|| latitude || =========================*/}
                                          <Grid item xs={12}>
                                            <Grid container spacing={4} alignItems="center">
                                              <Grid item>
                                                <TbWorldLatitude
                                                  style={{
                                                    fontSize: '20px',
                                                    fontWeight: 'lighter'
                                                  }}
                                                />
                                              </Grid>
                                              <Grid item xs zeroMinWidth>
                                                <TextField
                                                  variant="outlined"
                                                  readonly
                                                  label="Latitude"
                                                  fullWidth
                                                  value={latlong.lat}
                                                  sx={{ cursor: 'not-allowed' }}
                                                />
                                              </Grid>
                                              <Grid item>
                                                <TbWorldLongitude
                                                  style={{
                                                    fontSize: '20px',
                                                    fontWeight: 'lighter'
                                                  }}
                                                />
                                              </Grid>
                                              <Grid item xs zeroMinWidth>
                                                <TextField
                                                  label="Longitude"
                                                  readonly
                                                  variant="outlined"
                                                  fullWidth
                                                  value={latlong.lng}
                                                  // onChange={(e) => {
                                                  //   setLongi(e.target.value.toString())
                                                  //   setEditClient({
                                                  //     ...editClient,
                                                  //     longitude:
                                                  //       e.target.value.toString(),
                                                  //   });
                                                  // }}
                                                />
                                              </Grid>
                                            </Grid>
                                          </Grid>
                                        </Grid>
                                      </CardContent>
                                      {/* =========================|| update || =========================*/}

                                      <CardActions
                                        sx={{
                                          display: 'flex',
                                          justifyContent: 'end',
                                          mr: 3,
                                          mb: 2
                                        }}
                                      >
                                        <Button
                                          variant="contained"
                                          size="medium"
                                          onClick={() => {
                                            updateClient();
                                          }}
                                        >
                                          Update Client
                                        </Button>
                                      </CardActions>
                                    </Card>
                                  </Grid>
                                </Grid>
                              </Card>
                            )}
                            {/* ============================================= || Edit Pricing || ============================================= */}
                            {value2 == 1 && (
                              <Card variant="outlined" key={'left - card'} sx={{}}>
                                <TableContainer>
                                  <Table>
                                    <TableHead>
                                      <TableRow>
                                        <TableCell>#</TableCell>
                                        <TableCell>Vehicle</TableCell>
                                        <TableCell>Base Price</TableCell>
                                        <TableCell>Price/Km</TableCell>
                                        <TableCell>Price/Kg</TableCell>
                                        <TableCell>Handling</TableCell>
                                        <TableCell>Status</TableCell>
                                      </TableRow>
                                    </TableHead>
                                    <TableBody>
                                      {clientpricelist?.length === 0 ? (
                                        <TableRow>
                                          <TableCell colSpan={7} align="center">
                                            <Empty />
                                          </TableCell>
                                        </TableRow>
                                      ) : (
                                        clientpricelist.map((val, i) => (
                                          <TableRow key={val.pricingid || i} sx={{ bgcolor: 'white' }}>
                                            <TableCell>{i + 1}</TableCell>
                                            <TableCell>{val.vehicletype || '—'}</TableCell>
                                            <TableCell>{val.baseprice ?? '—'}</TableCell>
                                            <TableCell>{val.priceperkm ?? '—'}</TableCell>
                                            <TableCell>{val.priceperkg ?? '—'}</TableCell>
                                            <TableCell>{val.handlingcharges ?? '—'}</TableCell>
                                            <TableCell>{val.status || '—'}</TableCell>
                                          </TableRow>
                                        ))
                                      )}
                                    </TableBody>
                                  </Table>
                                </TableContainer>
                              </Card>
                            )}
                          </MainCard>
                          {/* </Collapse> */}
                        </TableCell>
                      </TableRow>
                    )}
                  </Fragment>
                  );
                })
              )}
            </TableBody>
          </Table>
        </TableContainer>

        {/* ============================================= || Mobile cards (xs only) || ============================================= */}
        {isMobile && (
          <MobileCardList scroll sx={{ display: { xs: 'flex', md: 'none' } }}>
            {getalltenantsIsLoading && (
              <Stack alignItems="center" sx={{ py: 4 }}>
                <Skeleton variant="rounded" width="100%" height={96} animation="wave" />
                <Skeleton variant="rounded" width="100%" height={96} animation="wave" sx={{ mt: 1.25 }} />
              </Stack>
            )}

            {tenantList?.length == 0 && !isloader ? (
              <Stack alignItems="center" spacing={1.5} sx={{ py: 6 }}>
                <Avatar sx={{ width: 64, height: 64, bgcolor: soft('#94a3b8'), color: DT.textMuted }}>
                  <MdGroups size={28} />
                </Avatar>
                <Typography variant="subtitle1" sx={{ fontWeight: 700, color: DT.textPrimary }}>
                  No tenants to show
                </Typography>
                <Typography variant="caption" sx={{ color: DT.textSecondary, textAlign: 'center' }}>
                  {`No ${activeTabMeta.label.toLowerCase()} tenants for this filter.`}
                </Typography>
              </Stack>
            ) : (
              tenantList?.map((row, index) => {
                const rowStatusKey = value0 === 0 ? 'active' : value0 === 1 ? 'pending' : 'inactive';
                const rowStatusMeta = STATUS_META[rowStatusKey];
                const RowStatusIcon = rowStatusMeta.icon;
                const expanded = openRowIndex1 === index;
                return (
                  <MobileCard
                    key={row.tenantid ?? index}
                    accent={rowStatusMeta.color}
                    header={
                      <Stack direction="row" alignItems="flex-start" justifyContent="space-between" spacing={1}>
                        <Stack direction="row" alignItems="center" spacing={1} sx={{ minWidth: 0 }}>
                          <AccentAvatar color="#662582" size={36}>
                            <MdPersonPin size={18} />
                          </AccentAvatar>
                          <Stack sx={{ minWidth: 0 }}>
                            <Typography variant="subtitle2" sx={{ fontWeight: 800, color: DT.textPrimary }} noWrap>
                              {row.tenantname}
                            </Typography>
                            <Stack
                              direction="row"
                              alignItems="center"
                              spacing={0.5}
                              sx={{
                                display: 'inline-flex',
                                mt: 0.25,
                                pl: 0.25,
                                pr: 0.875,
                                py: 0.125,
                                borderRadius: 999,
                                bgcolor: tint(rowStatusMeta.color),
                                border: `1px solid ${edge(rowStatusMeta.color)}`,
                                color: rowStatusMeta.color,
                                alignSelf: 'flex-start'
                              }}
                            >
                              <AccentAvatar color={rowStatusMeta.color} size={16}>
                                <RowStatusIcon size={10} />
                              </AccentAvatar>
                              <Typography sx={{ fontWeight: 800, fontSize: 10, lineHeight: 1 }}>
                                {rowStatusMeta.label}
                              </Typography>
                            </Stack>
                          </Stack>
                        </Stack>
                        <Stack direction="row" spacing={0.5} sx={{ flexShrink: 0 }}>
                          {value0 == 0 && (
                            <IconButton
                              size="small"
                              sx={{
                                bgcolor: soft('#ef4444'),
                                color: '#ef4444',
                                border: `1px solid ${edge('#ef4444')}`,
                                '&:hover': { bgcolor: '#ef4444', color: '#fff' }
                              }}
                              onClick={() => {
                                setSelectedCustomer(row);
                                setSelectedtenid(row.tenantid);
                                setAppId(row.applocationid);
                                setTimeout(() => {
                                  tenantupdate(row.tenantid);
                                }, 100);
                              }}
                            >
                              <StopOutlined style={{ fontSize: 14 }} />
                            </IconButton>
                          )}
                          {value0 == 1 && (
                            <IconButton
                              size="small"
                              sx={{
                                bgcolor: soft('#f59e0b'),
                                color: '#f59e0b',
                                border: `1px solid ${edge('#f59e0b')}`,
                                '&:hover': { bgcolor: '#f59e0b', color: '#fff' }
                              }}
                              onClick={() => {
                                setSelectedCustomer(row);
                                setDialogopen(true);
                                setSelectedtenid(row.tenantid);
                                setAppId(row.applocationid);
                                getAppPricing(row.applolcationid);
                              }}
                            >
                              <IssuesCloseOutlined style={{ fontSize: 14 }} />
                            </IconButton>
                          )}
                          {value0 == 2 && (
                            <IconButton
                              size="small"
                              sx={{
                                bgcolor: soft('#10b981'),
                                color: '#10b981',
                                border: `1px solid ${edge('#10b981')}`,
                                '&:hover': { bgcolor: '#10b981', color: '#fff' }
                              }}
                              onClick={() => {
                                setSelectedCustomer(row);
                                setSelectedtenid(row.tenantid);
                                setAppId(row.applocationid);
                                setTimeout(() => {
                                  tenantupdate(row.tenantid);
                                }, 100);
                              }}
                            >
                              <FaRegCheckCircle style={{ fontSize: 14 }} />
                            </IconButton>
                          )}
                          <IconButton
                            size="small"
                            sx={{
                              bgcolor: expanded ? '#662582' : soft('#662582'),
                              color: expanded ? '#fff' : '#662582',
                              border: `1px solid ${edge('#662582')}`,
                              '&:hover': { bgcolor: '#662582', color: '#fff' }
                            }}
                            onClick={() => {
                              setSelectedCustomer(row);
                              handleCollapseToggle1(index);
                              setOpenRowIndex2(-1);
                              setSelectedtenid(row.tenantid);
                            }}
                          >
                            {expanded ? <EyeInvisibleOutlined style={{ fontSize: 14 }} /> : <EyeOutlined style={{ fontSize: 14 }} />}
                          </IconButton>
                          <IconButton
                            size="small"
                            sx={{
                              bgcolor: soft('#0ea5e9'),
                              color: '#0ea5e9',
                              border: `1px solid ${edge('#0ea5e9')}`,
                              '&:hover': { bgcolor: '#0ea5e9', color: '#fff' }
                            }}
                            onClick={() => setLocationsDialogTenant(row)}
                          >
                            <MdPlace size={14} />
                          </IconButton>
                          <IconButton
                            size="small"
                            sx={{
                              bgcolor: soft('#14b8a6'),
                              color: '#14b8a6',
                              border: `1px solid ${edge('#14b8a6')}`,
                              '&:hover': { bgcolor: '#14b8a6', color: '#fff' }
                            }}
                            onClick={() => setCustomersDialogTenant(row)}
                          >
                            <MdPeopleAlt size={14} />
                          </IconButton>
                          {value0 !== 1 && (
                            <IconButton
                              size="small"
                              sx={{
                                bgcolor: soft('#8b5cf6'),
                                color: '#8b5cf6',
                                border: `1px solid ${edge('#8b5cf6')}`,
                                '&:hover': { bgcolor: '#8b5cf6', color: '#fff' }
                              }}
                              onClick={() => {
                                setSelectedCustomer(row);
                                setSelectedtenid(row.tenantid);
                                setAppId(row.applocationid);
                                getAppPricing(row.applolcationid);
                                setDialogopen(true);
                              }}
                            >
                              <EditOutlined style={{ fontSize: 14 }} />
                            </IconButton>
                          )}
                        </Stack>
                      </Stack>
                    }
                  >
                    <MobileFieldGrid>
                      <MobileField label="Tenant ID" value={`#${row.tenantid}`} />
                      <MobileField label="Contact" value={row.primarycontact || '—'} />
                      <MobileField label="Email" value={row.primaryemail || '—'} full />
                      <MobileField label="Address" full>
                        <Typography sx={{ fontSize: 13, fontWeight: 600, color: DT.textPrimary }}>
                          {row.address || '—'}
                        </Typography>
                      </MobileField>
                    </MobileFieldGrid>

                    {expanded && (
                      <Box sx={{ mt: 1.25, pt: 1.25, borderTop: `1px solid ${DT.divider}` }}>
                        <MobileFieldGrid>
                          <MobileField label="Contact Person" value={row.firstname || '—'} />
                          <MobileField label="City" value={row.city || '—'} />
                          <MobileField label="Postcode" value={row.postcode || '—'} />
                          <MobileField label="Latitude" value={row.latitude || '—'} />
                          <MobileField label="Longitude" value={row.longitude || '—'} />
                        </MobileFieldGrid>
                      </Box>
                    )}
                  </MobileCard>
                );
              })
            )}
          </MobileCardList>
        )}

        {/* ============================================= || Pagination| =============================================  */}
        {!searchword && tenantList?.length > 0 && (
          <>
            <Divider sx={{ borderColor: DT.borderSubtle }} />
            <TablePagination
              rowsPerPageOptions={[5, 10, 25, 50, 100]}
              component="div"
              count={value0 == 0 ? summaryData?.active : value0 == 1 ? summaryData?.pending : value0 == 2 ? summaryData?.inactive : 0}
              rowsPerPage={rowsPerPage}
              page={page}
              onPageChange={handleChangePage}
              onRowsPerPageChange={handleChangeRowsPerPage}
            />
          </>
        )}
      </Paper>
      {/* // ==============================||( Client Pricing ) dialog (dialogopen) ||============================== // */}
      <Dialog
        fullWidth={true}
        fullScreen={isMobile}
        open={dialogopen}
        onClose={dialogclose}
        scroll={'paper'}
        maxWidth="sm"
        TransitionComponent={PopupTransition}
        PaperProps={{ sx: { borderRadius: { xs: 0, sm: 3 } } }}
      >
        <DialogTitle
          sx={{
            bgcolor: '#662582',
            color: '#fff',
            fontSize: '20px'
          }}
        >
          {`Client Pricing  - (${selectedCustomer.tenantname})`}
        </DialogTitle>
        <DialogContent dividers={true}>
          <MainCard sx={{ height: '100%' }}>
            <Grid container spacing={2.5} alignItems={'center'}>
              <Grid item xs={12} sm={6}>
                <FormLabel>Select Slab</FormLabel>
                <Select
                  fullWidth
                  displayEmpty
                  value={selectedPricing.vehicletype || ''}
                  onChange={(e) => {
                    setSelectedPricing({ ...selectedPricing, vehicletype: e.target.value });
                    setIsprice(false);
                  }}
                >
                  <MenuItem value="" disabled>
                    Choose vehicle type
                  </MenuItem>
                  {['Bike', 'Scooter', 'Bicycle', 'Car', 'Van'].map((v) => (
                    <MenuItem key={v} value={v}>
                      {v}
                    </MenuItem>
                  ))}
                </Select>
              </Grid>

              <Grid item xs={12} sm={6}>
                <FormLabel>Base Price</FormLabel>
                <TextField
                  type="number"
                  fullWidth
                  value={!isPrice ? selectedPricing.baseprice : 0}
                  onChange={(e) => {
                    setSelectedPricing({
                      ...selectedPricing,
                      baseprice: e.target.value
                    });
                  }}
                />
              </Grid>
              <Grid item xs={12} sm={6}>
                <FormLabel>Price/Km</FormLabel>
                <TextField
                  type="number"
                  fullWidth
                  value={!isPrice ? selectedPricing.priceperkm : 0}
                  onChange={(e) => {
                    setSelectedPricing({
                      ...selectedPricing,
                      priceperkm: e.target.value
                    });
                  }}
                />
              </Grid>

              <Grid item xs={12} sm={6}>
                <FormLabel>Base Weight (kg)</FormLabel>
                <TextField
                  type="number"
                  fullWidth
                  value={!isPrice ? selectedPricing.baseweight : 0}
                  onChange={(e) => {
                    setSelectedPricing({
                      ...selectedPricing,
                      baseweight: e.target.value
                    });
                  }}
                />
              </Grid>
              <Grid item xs={12} sm={6}>
                <FormLabel>Price/Kg</FormLabel>
                <TextField
                  type="number"
                  fullWidth
                  value={!isPrice ? selectedPricing.priceperkg : 0}
                  onChange={(e) => {
                    setSelectedPricing({
                      ...selectedPricing,
                      priceperkg: e.target.value
                    });
                  }}
                />
              </Grid>
              <Grid item xs={12} sm={6}>
                <FormLabel>Base Distance (km)</FormLabel>
                <TextField
                  type="number"
                  fullWidth
                  value={!isPrice ? selectedPricing.basedistance : 0}
                  onChange={(e) => {
                    setSelectedPricing({
                      ...selectedPricing,
                      basedistance: e.target.value
                    });
                  }}
                />
              </Grid>
              <Grid item xs={12} sm={6}>
                <FormLabel>Handling Charges</FormLabel>
                <TextField
                  type="number"
                  fullWidth
                  value={!isPrice ? selectedPricing.handlingcharges : 0}
                  onChange={(e) => {
                    setSelectedPricing({
                      ...selectedPricing,
                      handlingcharges: e.target.value
                    });
                  }}
                />
              </Grid>
            </Grid>
          </MainCard>
        </DialogContent>
        <DialogActions>
          <Grid container>
            <Grid item xs={12}>
              <Stack direction={'row'} justifyContent={'flex-end'} spacing={2} sx={{ p: 2 }}>
                {value2 == 1 && (
                  <Button
                    disabled={isPrice}
                    variant="contained"
                    onClick={() => {
                      createpricing();
                    }}
                  >
                    Update Pricing
                  </Button>
                )}
                {value0 == 1 && (
                  <Button
                    disabled={isPrice}
                    variant="contained"
                    onClick={() => {
                      createpricing();
                    }}
                  >
                    Save
                  </Button>
                )}
                <Button
                  variant="contained"
                  onClick={() => {
                    setIsprice(true);
                    setTimeout(() => {
                      dialogclose();
                    }, 100);
                    setSelectedPricing({});
                  }}
                  color="error"
                >
                  Cancel
                </Button>
              </Stack>
            </Grid>
          </Grid>
        </DialogActions>
      </Dialog>

      <TenantLocationsDialog
        tenant={locationsDialogTenant}
        open={!!locationsDialogTenant}
        onClose={() => setLocationsDialogTenant(null)}
      />

      <TenantCustomersDialog
        tenant={customersDialogTenant}
        open={!!customersDialogTenant}
        onClose={() => setCustomersDialogTenant(null)}
      />
    </>
  );
};

export default Clients1;
