import React, { useEffect, useState, useRef, useMemo, Fragment } from 'react';
import MainCard from 'components/MainCard';
import axios from 'axios';
import { useTheme } from '@mui/material/styles';
import Loader from 'components/Loader';
import { Empty } from 'antd';
import dayjs from 'dayjs';
import { enqueueSnackbar } from 'notistack';
import Geocode from 'react-geocode';
import LocationOnIcon from '@mui/icons-material/LocationOn';
import parse from 'autosuggest-highlight/parse';
import { debounce } from '@mui/material/utils';
import {
  Stack,
  Table,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TableBody,
  Typography,
  IconButton,
  Box,
  Grid,
  Autocomplete,
  TextField,
  Tooltip,
  Collapse,
  Tab,
  Tabs,
  Divider,
  Card,
  CardContent,
  CardActions,
  Button,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  FormLabel,
  TablePagination,
  Skeleton,
  Avatar,
  Paper
} from '@mui/material';
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,
  MdMyLocation,
  MdPersonPin
} 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 { useQuery } from '@tanstack/react-query';
import { getalltenants, gettenantsummary } from 'pages/api/api';
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: 16,
  radiusInner: 12,
  shadowSoft: '0 14px 40px rgba(15, 23, 42, 0.10)',
  shadowMd: '0 8px 24px rgba(15, 23, 42, 0.08)',
  shadowPop: '0 18px 50px rgba(15, 23, 42, 0.18)',
  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');

const pillFieldSx = (color) => ({
  cursor: 'pointer',
  '& .MuiOutlinedInput-root': {
    borderRadius: DT.radiusPill + 'px',
    bgcolor: tint(color),
    fontWeight: 600,
    color: DT.textPrimary,
    paddingRight: '8px',
    cursor: 'pointer',
    transition: 'border-color 0.15s, box-shadow 0.15s, background-color 0.2s',
    '& fieldset': { borderColor: edge(color), borderWidth: 1.5 },
    '&:hover fieldset': { borderColor: color },
    '&.Mui-focused': { boxShadow: `0 0 0 3px ${ring(color)}` },
    '&.Mui-focused fieldset': { borderColor: color, borderWidth: 2 }
  },
  '& .MuiAutocomplete-endAdornment .MuiSvgIcon-root': { color: color }
});

// 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: MdCheckCircle,    countKey: 'active' },
  { key: 'pending',  label: 'Pending Approval', color: '#f59e0b', icon: MdHourglassEmpty, countKey: 'pending' },
  { key: 'inactive', label: 'Inactive Tenants', color: '#ef4444', icon: MdCancel,         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>
);

// ==============================|| 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 [isloader, setisloader] = useState(false);
  const [appId, setAppId] = useState(0);
  const [locaName, setLocoName] = useState('');
  const [locations] = useState('All');
  const [value, setValue] = React.useState(null);
  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 [appPricing, setAppPricing] = useState([]);
  const [selectedPricing, setSelectedPricing] = useState({});
  const [isPrice, setIsprice] = useState(true);
  const [address, setAddress] = useState('');
  const [city, setCity] = useState('');
  const [zipcode, setZipcode] = useState('');
  const [latlong, setLatlong] = useState({});
  const [editClient, setEditClient] = useState({});
  const [page, setPage] = useState(0);
  const [tabStatus, setTabStatus] = useState('Active');

  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) => {
    setTabStatus(newValue == 0 ? 'Active' : newValue == 1 ? 'Pending' : 'InActive');
    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
  // 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
    });
  };
  // ==============================|| google address ||============================== //
  const GOOGLE_MAPS_API_KEY = process.env.REACT_APP_GOOGLE_MAPS_API_KEY;

  function loadScript(src, position, id) {
    if (!position) {
      return;
    }

    const script = document.createElement('script');
    script.setAttribute('async', '');
    script.setAttribute('id', id);
    script.src = src;
    position.appendChild(script);
  }

  const autocompleteService = { current: null };
  // ==============================|| for google address ||============================== //
  const [inputValue, setInputValue] = useState('');
  const [options, setOptions] = useState([]);
  const loaded = useRef(false);
  if (typeof window !== 'undefined' && !loaded.current) {
    if (!document.querySelector('#google-maps')) {
      loadScript(
        `https://maps.googleapis.com/maps/api/js?key=${GOOGLE_MAPS_API_KEY}&libraries=places`,
        document.querySelector('head'),
        'google-maps'
      );
    }

    loaded.current = true;
  }

  const fetch = useMemo(
    () =>
      debounce((request, callback) => {
        autocompleteService.current.getPlacePredictions(request, callback);
      }, 400),
    []
  );
  useEffect(() => {
    let active = true;
    if (!autocompleteService.current && window.google) {
      autocompleteService.current = new window.google.maps.places.AutocompleteService();
    }
    if (!autocompleteService.current) {
      return undefined;
    }

    if (inputValue === '') {
      setOptions(value ? [value] : []);
      return undefined;
    }
    fetch({ input: inputValue }, (results) => {
      if (active) {
        let newOptions = [];

        if (value) {
          newOptions = [value];
        }

        if (results) {
          newOptions = [...newOptions, ...results];
        }
        setOptions(newOptions);
      }
    });

    return () => {
      active = false;
    };
  }, [value, inputValue, fetch]);

  Geocode.setApiKey(process.env.REACT_APP_GOOGLE_MAPS_API_KEY);
  useEffect(() => {
    try {
      console.log('selected address =>', address);
      Geocode.fromAddress(address).then(
        (response) => {
          console.log('lat long response =>', response.results[0]);
          if (response.status == 'OK') {
            const { lat, lng } = response.results[0].geometry.location;
            setLatlong({
              lat,
              lng
            });
            setEditClient({
              ...editClient,
              latitude: lat.toString(),
              longitude: lng.toString()
            });
            // setSelectedCustomer({
            //   ...selectedCustomer,
            //   latitude: lat,
            //   longitude: lng,
            // });
            if (response.results[0].address_components) {
              let place = response.results[0];
              let city1, zipcode1, state1, suburb1;
              for (let i = 0; i < place.address_components.length; i++) {
                for (let j = 0; j < place.address_components[i].types.length; j++) {
                  switch (place.address_components[i].types[j]) {
                    case 'locality':
                      city1 = place.address_components[i].long_name;
                      break;
                    case 'administrative_area_level_1':
                      state1 = place.address_components[i].long_name;
                      break;
                    case 'postal_code':
                      zipcode1 = place.address_components[i].long_name;
                      break;
                    case 'sublocality':
                      suburb1 = place.address_components[i].long_name;
                      break;
                  }
                }
              }
              setCity(city1 || '');
              setState(state1 || '');
              setZipcode(zipcode1 || '');
              setSuburb(suburb1 || '');
              setEditClient({
                ...editClient,
                city: city1 || '',
                state: state1 || '',
                postcode: zipcode || '',
                suburb: suburb1 || ''
              });
            }
          }
        },
        (error) => {
          console.log(error);
        }
      );
    } catch (err) {
      console.log(err);
    }
  }, [address]);

  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 || ============================================= */

  const fetchclientpricelist = async () => {
    await axios
      .get(`${process.env.REACT_APP_URL}/tenants/getpricinglist/?tenantid=${selectedTenid}`)
      .then((res) => {
        console.log('getpricinglist', res);
        if (res.data.status) {
          setClientpricelist(res.data.details);
        }
      })
      .catch((err) => {
        console.log(err);
      });
  };
  useEffect(() => {
    selectedTenid && fetchclientpricelist();
  }, [selectedTenid]);

  /* ============================================= || fetchTenanatPricing || ============================================= */
  const fetchTenanatPricing = async (id) => {
    try {
      let tenantPricing = await axios.get(`${process.env.REACT_APP_URL}/tenants/gettenantpricing/?tenantid=${id}`);
      console.log('tenantPricing', tenantPricing.data.details);
      setTenanatPricing(tenantPricing.data.details);
    } catch (error) {
      console.log('fetchTenanatPricing', error);
    }
  };
  useEffect(() => {
    selectedTenid && fetchTenanatPricing(selectedTenid);
  }, [selectedTenid]);
  /* ============================================= || tenantupdate || ============================================= */

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

    await axios
      .put(`${process.env.REACT_APP_URL}/tenants/update`, updateData)
      .then((res) => {
        if (res.data.status) {
          opentoast(
            value0 == 0 ? 'Inactivated Successfully' : value0 == 1 ? 'Approved Successfully' : 'Activate Successfully',
            'success',
            2000
          );
          getalltenantsRefetch();
          summaryDataRefetch();
          setisloader(false);
        }
      })
      .catch((err) => {
        console.log(err);
        opentoast(err.message, 'error', 1500);
        setisloader(false);
      });
    // }
  };
  /* ============================================= || getAppPricing || ============================================= */
  const getAppPricing = async (id) => {
    console.log('id', id);
    try {
      let appPricingRes = await axios.get(`${process.env.REACT_APP_URL}/utils/getapppricing/?applocationid=${id}`);
      console.log('appPricingRes', appPricingRes.data.details);
      setAppPricing(appPricingRes.data.details);
    } catch (error) {
      console.log('appPricingRes', error);
    }
  };
  /* ============================================= || createpricing || ============================================= */
  const createpricing = async () => {
    setisloader(true);
    await axios
      .post(`${process.env.REACT_APP_URL}/tenants/createpricing`, {
        tenantpricingid: 0,
        applocationid: appId,
        pricingid: selectedPricing.pricingid,
        tenantid: selectedTenid,
        pricingdate: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        configid: selectedPricing.configid,
        pricingtypeid: selectedPricing.pricingtypeid,
        slab: selectedPricing.slab,
        baseprice: +selectedPricing.baseprice,
        priceperkm: +selectedPricing.priceperkm,
        minkm: +selectedPricing.minkm,
        maxkm: +selectedPricing.maxkm,
        orders: +selectedPricing.minorder,
        othercharges: 0
      })
      .then((res) => {
        if (res.data.status) {
          enqueueSnackbar('Price Created Successfully', {
            variant: 'success',
            anchorOrigin: { vertical: 'top', horizontal: 'right' },
            autoHideDuration: 2000
          });
          dialogclose();
          setSelectedPricing({});
          tenantupdate(-1);
          fetchclientpricelist();
        }
      })
      .catch((err) => {
        console.log(err);
      });
  };
  /* ============================================= || updateClient || ============================================= */
  const updateClient = async () => {
    try {
      const arr = { ...editClient, tenantid: selectedTenid };

      console.log('updateClient', arr);
      const updateRes = await axios.put(`${process.env.REACT_APP_URL}/tenants/update`, arr);
      console.log('updateClient', updateRes.data.message);
      if (updateRes.data.status) {
        opentoast(updateRes.data.message, 'success', 1500);
      }
      getalltenantsRefetch();
      summaryDataRefetch();
    } catch (err) {
      console.log('updateClient', err);
    }
  };

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

  return (
    <>
      {(getalltenantsIsLoading || summaryDataIsLoading || isloader) && <Loader />}
      {/* ============================================= || Header | ============================================= */}
      <Paper
        elevation={0}
        sx={{
          mb: { xs: 1.5, md: 2 },
          p: { xs: 1.5, sm: 2, md: 2.5 },
          borderRadius: DT.radiusCard / 8,
          border: '1px solid',
          borderColor: DT.borderSubtle,
          background: `linear-gradient(135deg, ${tint('#6366f1')} 0%, ${tint('#0ea5e9')} 100%)`,
          boxShadow: DT.shadowMd
        }}
      >
        <Stack
          direction={{ xs: 'column', sm: 'row' }}
          alignItems={{ xs: 'flex-start', sm: 'center' }}
          justifyContent="space-between"
          spacing={{ xs: 1.5, sm: 2 }}
        >
          <Stack direction="row" alignItems="center" spacing={{ xs: 1.25, sm: 1.75 }}>
            <Avatar
              sx={{
                width: { xs: 40, sm: 48 },
                height: { xs: 40, sm: 48 },
                bgcolor: '#6366f1',
                color: '#fff',
                boxShadow: '0 6px 18px rgba(99,102,241,0.32)'
              }}
            >
              <MdGroups size={22} />
            </Avatar>
            <Stack>
              <Typography
                variant="h3"
                sx={{
                  fontWeight: 800,
                  color: DT.textPrimary,
                  lineHeight: 1.1,
                  fontSize: { xs: '1.25rem', sm: '1.5rem', md: '1.75rem' }
                }}
              >
                Tenants
              </Typography>
              <Stack direction="row" alignItems="center" spacing={0.75} sx={{ mt: 0.5 }}>
                <Box
                  sx={{
                    width: 8,
                    height: 8,
                    borderRadius: '50%',
                    bgcolor: '#10b981',
                    boxShadow: '0 0 0 4px rgba(16,185,129,0.18)'
                  }}
                />
                <Typography variant="caption" sx={{ color: DT.textSecondary, fontWeight: 600 }}>
                  Live · {locaName || 'All Zones'}
                </Typography>
              </Stack>
            </Stack>
          </Stack>
          <LocationAutocomplete
            locations={locations}
            locaName={locaName}
            setAppId={setAppId}
            setLocoName={setLocoName}
            setPage={setPage}
            pill
            accentColor="#6366f1"
            icon={<MdMyLocation size={14} />}
            placeholder="Select Zone"
            paperComponent={SoftPaper}
            sx={{ width: { xs: '100%', sm: 280 }, zIndex: 100 }}
          />
        </Stack>
      </Paper>

      {/* ============================================= || KPI Cards | ============================================= */}
      <Grid container spacing={{ xs: 1.25, sm: 1.5, md: 2 }} sx={{ mt: '1px' }}>
        {KPI_META.map((item) => {
          const Icon = item.icon;
          const value = summaryData?.[item.countKey] ?? 0;
          return (
            <Grid item key={item.key} xs={12} sm={4}>
              <Paper
                elevation={0}
                sx={{
                  position: 'relative',
                  overflow: 'hidden',
                  p: { xs: 1.25, sm: 1.75, md: 2.25 },
                  borderRadius: DT.radiusCard / 8,
                  border: '1px solid',
                  borderColor: DT.borderSubtle,
                  background: '#fff',
                  transition: 'transform 0.2s, box-shadow 0.2s, border-color 0.2s',
                  cursor: 'pointer',
                  '&:hover': {
                    transform: 'translateY(-3px)',
                    boxShadow: DT.shadowMd,
                    borderColor: edge(item.color)
                  }
                }}
                onClick={() => {
                  const idx = STATUS_TABS.findIndex((t) => t.countKey === item.countKey);
                  if (idx >= 0) handleChange(null, idx);
                }}
              >
                <Box
                  sx={{
                    position: 'absolute',
                    top: 0,
                    left: 0,
                    right: 0,
                    height: 3,
                    background: `linear-gradient(90deg, ${item.color} 0%, ${soft(item.color)} 100%)`
                  }}
                />
                <Stack direction="row" alignItems="flex-start" justifyContent="space-between" spacing={1}>
                  <Stack spacing={0.5} sx={{ minWidth: 0, flex: 1 }}>
                    <Typography
                      variant="caption"
                      sx={{
                        color: DT.textSecondary,
                        fontWeight: 700,
                        letterSpacing: 0.4,
                        textTransform: 'uppercase',
                        fontSize: { xs: 10, sm: 11 },
                        whiteSpace: 'nowrap',
                        overflow: 'hidden',
                        textOverflow: 'ellipsis'
                      }}
                    >
                      {item.label}
                    </Typography>
                    {summaryDataIsLoading ? (
                      <Skeleton sx={{ width: 70, height: { xs: 28, md: 36 } }} animation="wave" />
                    ) : (
                      <Typography
                        sx={{
                          fontWeight: 800,
                          color: DT.textPrimary,
                          lineHeight: 1.1,
                          fontSize: { xs: '1.5rem', sm: '1.75rem', md: '2rem' }
                        }}
                      >
                        {value}
                      </Typography>
                    )}
                  </Stack>
                  <Avatar
                    sx={{
                      width: { xs: 36, sm: 42, md: 48 },
                      height: { xs: 36, sm: 42, md: 48 },
                      bgcolor: soft(item.color),
                      color: item.color,
                      boxShadow: `inset 0 0 0 1px ${edge(item.color)}`,
                      flexShrink: 0
                    }}
                  >
                    <Icon size={20} />
                  </Avatar>
                </Stack>
              </Paper>
            </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: 999,
                    border: `1.5px solid ${active ? meta.color : edge(meta.color)}`,
                    bgcolor: active ? meta.color : tint(meta.color),
                    color: active ? '#fff' : meta.color,
                    fontWeight: 700,
                    boxShadow: active ? `0 6px 18px ${ring(meta.color)}` : 'none',
                    transition: 'all 0.18s',
                    '&:hover': {
                      borderColor: meta.color,
                      boxShadow: active ? `0 6px 18px ${ring(meta.color)}` : `0 0 0 3px ${ring(meta.color)}`
                    }
                  }}
                >
                  <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: 800, 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: 800,
                      bgcolor: active ? 'rgba(255,255,255,0.22)' : '#fff',
                      color: active ? '#fff' : meta.color,
                      border: active ? 'none' : `1px solid ${edge(meta.color)}`
                    }}
                  >
                    {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('#6366f1'),
                '& fieldset': { borderColor: edge('#6366f1'), borderWidth: 1.5 },
                '&:hover fieldset': { borderColor: '#6366f1' },
                '&.Mui-focused fieldset': { borderColor: '#6366f1', borderWidth: 2 },
                '&.Mui-focused': { boxShadow: `0 0 0 3px ${ring('#6366f1')}` }
              }}
            />
          </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={{
            maxHeight: { xs: 'calc(100vh - 220px)', md: 'calc(100vh - 190px)' },
            '&::-webkit-scrollbar': { width: '10px', height: '10px' },
            '&::-webkit-scrollbar-thumb': {
              backgroundColor: edge('#6366f1'),
              borderRadius: '8px',
              '&:hover': { backgroundColor: '#6366f1' }
            },
            '&::-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="#6366f1" 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 ? '#6366f1' : soft('#6366f1'),
                                color: openRowIndex1 === index ? '#fff' : '#6366f1',
                                border: `1px solid ${edge('#6366f1')}`,
                                '&:hover': { bgcolor: '#6366f1', color: '#fff' }
                              }}
                              onClick={() => {
                                setSelectedCustomer(row);
                                handleCollapseToggle1(index);
                                setOpenRowIndex2(-1);
                                setSelectedtenid(row.tenantid);
                              }}
                            >
                              {openRowIndex1 === index ? <EyeInvisibleOutlined style={{ fontSize: 14 }} /> : <EyeOutlined style={{ fontSize: 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>Date</TableCell>
                                          <TableCell>Slab</TableCell>
                                          <TableCell>Base Price</TableCell>
                                          <TableCell>Min Kms</TableCell>
                                          <TableCell>Price/Km</TableCell>
                                          <TableCell>Other Charges</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.id || i} sx={{ bgcolor: 'white' }}>
                                              <TableCell>{i + 1}</TableCell>
                                              <TableCell>{dayjs(val.pricingdate).format('DD-MM-YYYY')}</TableCell>
                                              <TableCell>{val.slab}</TableCell>
                                              <TableCell>{val.baseprice}</TableCell>
                                              <TableCell>{val.minkm}</TableCell>
                                              <TableCell>{val.priceperkm}</TableCell>
                                              <TableCell>{val.othercharges}</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>
                                                <Autocomplete
                                                  id="google-map-demo"
                                                  sx={{}}
                                                  fullWidth
                                                  label={'Address'}
                                                  getOptionLabel={(option) => (typeof option === 'string' ? option : option.description)}
                                                  filterOptions={(x) => x}
                                                  options={options}
                                                  autoComplete
                                                  includeInputInList
                                                  filterSelectedOptions
                                                  defaultValue={selectedCustomer.address}
                                                  noOptionsText="No locations"
                                                  onChange={(event, newValue) => {
                                                    setOptions(newValue ? [newValue, ...options] : options);
                                                    setValue(newValue || '');
                                                    console.log('newValue', newValue);
                                                    setAddress(newValue?.description || '');
                                                    setEditClient({
                                                      ...editClient,
                                                      address: newValue?.description || ''
                                                    });
                                                  }}
                                                  onInputChange={(event, newInputValue) => {
                                                    setInputValue(newInputValue);
                                                  }}
                                                  renderInput={(params) => (
                                                    <TextField {...params} fullWidth label="Address" variant="outlined" />
                                                  )}
                                                  renderOption={(props, option) => {
                                                    const matches = option.structured_formatting.main_text_matched_substrings || [];

                                                    const parts = parse(
                                                      option.structured_formatting.main_text,
                                                      matches.map((match) => [match.offset, match.offset + match.length])
                                                    );

                                                    return (
                                                      <li {...props}>
                                                        <Grid container alignItems="center">
                                                          <Grid
                                                            item
                                                            sx={{
                                                              display: 'flex',
                                                              width: 44
                                                            }}
                                                          >
                                                            <LocationOnIcon
                                                              sx={{
                                                                color: 'text.secondary'
                                                              }}
                                                            />
                                                          </Grid>
                                                          <Grid
                                                            item
                                                            sx={{
                                                              width: 'calc(100% - 44px)',
                                                              wordWrap: 'break-word'
                                                            }}
                                                          >
                                                            {parts.map((part, index) => (
                                                              <Box
                                                                key={index}
                                                                component="span"
                                                                sx={{
                                                                  fontWeight: part.highlight ? 'bold' : 'regular'
                                                                }}
                                                              >
                                                                {part.text}
                                                              </Box>
                                                            ))}
                                                            <Typography variant="body2" color="text.secondary">
                                                              {option.structured_formatting.secondary_text}
                                                            </Typography>
                                                          </Grid>
                                                        </Grid>
                                                      </li>
                                                    );
                                                  }}
                                                />
                                              </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>Date</TableCell>
                                        <TableCell>Slab</TableCell>
                                        <TableCell>Base Price</TableCell>
                                        <TableCell>Min Kms</TableCell>
                                        <TableCell>Price/Km</TableCell>
                                        <TableCell>Other Charges</TableCell>
                                      </TableRow>
                                    </TableHead>
                                    <TableBody>
                                      {clientpricelist?.length === 0 ? (
                                        <TableRow>
                                          <TableCell colSpan={7} align="center">
                                            <Empty />
                                          </TableCell>
                                        </TableRow>
                                      ) : (
                                        clientpricelist.map((val, i) => (
                                          <TableRow key={val.id || i} sx={{ bgcolor: 'white' }}>
                                            <TableCell>{i + 1}</TableCell>
                                            <TableCell>{dayjs(val.pricingdate).format('DD-MM-YYYY')}</TableCell>
                                            <TableCell>{val.slab}</TableCell>
                                            <TableCell>{val.baseprice}</TableCell>
                                            <TableCell>{val.minkm}</TableCell>
                                            <TableCell>{val.priceperkm}</TableCell>
                                            <TableCell>{val.othercharges}</TableCell>
                                          </TableRow>
                                        ))
                                      )}
                                    </TableBody>
                                  </Table>
                                </TableContainer>
                              </Card>
                            )}
                          </MainCard>
                          {/* </Collapse> */}
                        </TableCell>
                      </TableRow>
                    )}
                  </Fragment>
                  );
                })
              )}
            </TableBody>
          </Table>
        </TableContainer>
        {/* ============================================= || 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} open={dialogopen} onClose={dialogclose} scroll={'paper'} maxWidth="sm" TransitionComponent={PopupTransition}>
        <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>
                <Autocomplete
                  disablePortal
                  id="combo-box-demo"
                  options={appPricing}
                  getOptionLabel={(option) => `${option.slab}`}
                  fullWidth
                  selectOnFocus
                  renderInput={(params) => <TextField {...params} label="Slab" />}
                  onChange={(event, value, reason) => {
                    setSelectedPricing(value);
                    console.log('pricing', value);
                    setIsprice(false);

                    if (reason === 'clear') {
                      setIsprice(true);
                    }
                  }}
                />
              </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>Min Kms</FormLabel>
                <TextField
                  type="number"
                  fullWidth
                  value={!isPrice ? selectedPricing.minkm : 0}
                  onChange={(e) => {
                    setSelectedPricing({
                      ...selectedPricing,
                      minkm: e.target.value
                    });
                  }}
                />
              </Grid>
              <Grid item xs={12} sm={6}>
                <FormLabel>Max Kms</FormLabel>
                <TextField
                  type="number"
                  fullWidth
                  value={!isPrice ? selectedPricing.maxkm : 0}
                  onChange={(e) => {
                    setSelectedPricing({
                      ...selectedPricing,
                      maxkm: e.target.value
                    });
                  }}
                />
              </Grid>
              <Grid item xs={12} sm={6}>
                <FormLabel>Min Orders</FormLabel>
                <TextField
                  type="number"
                  fullWidth
                  value={!isPrice ? selectedPricing.minorder : 0}
                  onChange={(e) => {
                    setSelectedPricing({
                      ...selectedPricing,
                      minorder: 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>
    </>
  );
};

export default Clients1;
