import React, { useMemo, useRef, useState } from 'react';
import {
  Autocomplete,
  Avatar,
  Box,
  Button,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  Grid,
  IconButton,
  InputLabel,
  MenuItem,
  Paper,
  Select,
  Stack,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TextField,
  Tooltip,
  Typography,
  useMediaQuery,
  useTheme
} from '@mui/material';
import {
  MdLocalOffer,
  MdMyLocation,
  MdGroups,
  MdPlace,
  MdSpeed,
  MdPriceCheck,
  MdReceiptLong,
  MdOutlineLocalOffer,
  MdOutlineGroups,
  MdOutlineAttachMoney,
  MdOutlinePlace,
  MdAdd,
  MdEdit,
  MdDeleteOutline,
  MdCalculate
} from 'react-icons/md';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';

import Loader from 'components/Loader';
import DebounceSearchBar from 'components/nearle_components/DebounceSearchBar';
import LocationAutocomplete from 'components/nearle_components/LocationAutocomplete';
import PageHeader from 'components/nearle_components/PageHeader';
import StatCard from 'components/nearle_components/StatCard';
import { MobileCard, MobileCardList, MobileField, MobileFieldGrid } from 'components/nearle_components/MobileCard';
import { OrdersTableSkeleton } from '../orders/OrdersTableSkeleton';
import { getallpricing, getTenants, fetchAppLocations } from 'pages/api/api';
import { createAdminPricing, updateAdminPricing, deleteAdminPricing, simulatePricing } from 'pages/api/doormileApi';
import { enqueueSnackbar } from 'notistack';

// ============================================================================
// Design tokens — shared with the deliveries / tenants / customers pages so every
// surface (header, KPI tiles, table, badges) speaks the same visual language.
// Keep this block in sync with customers.js / deliveries.js.
// ============================================================================
const DT = {
  radiusPill: 999,
  radiusCard: 14,
  radiusField: 10,
  shadowSoft: '0 1px 2px rgba(15, 23, 42, 0.04), 0 8px 24px rgba(15, 23, 42, 0.05)',
  shadowMd: '0 1px 3px rgba(15, 23, 42, 0.06)',
  shadowPop: '0 12px 32px rgba(15, 23, 42, 0.12)',
  textPrimary: '#0f172a',
  textSecondary: '#64748b',
  textMuted: '#94a3b8',
  borderSubtle: '#e2e8f0',
  borderHover: '#cbd5e1',
  divider: '#f1f5f9',
  surface: '#ffffff',
  surfaceAlt: '#f8fafc',
  brand: '#662582'
};
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 BRAND = '#662582';
const VEHICLE_TYPES = ['Bike', 'Scooter', 'Bicycle', 'Car', 'Van'];

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>
);

const formatRupees = (value) =>
  new Intl.NumberFormat('en-IN', {
    style: 'currency',
    currency: 'INR',
    minimumFractionDigits: 2
  }).format(Number(value) || 0);

const MetricPill = ({ label }) => (
  <Typography
    component="span"
    sx={{ fontSize: 13.5, fontWeight: 700, color: DT.textPrimary, whiteSpace: 'nowrap', fontVariantNumeric: 'tabular-nums' }}
  >
    {label}
  </Typography>
);

const CategoryChip = ({ icon, label }) => (
  <Box
    sx={{
      display: 'inline-flex',
      alignItems: 'center',
      gap: 0.5,
      px: 1,
      py: 0.375,
      borderRadius: 8,
      bgcolor: DT.surfaceAlt,
      border: `1px solid ${DT.borderSubtle}`,
      color: DT.textPrimary,
      fontSize: 12,
      fontWeight: 600,
      whiteSpace: 'nowrap'
    }}
  >
    <Box component="span" sx={{ display: 'inline-flex', color: DT.textMuted }}>
      {icon}
    </Box>
    {label}
  </Box>
);

const emptyForm = {
  pricingid: null,
  tenant: null,
  location: null,
  vehicletype: 'Bike',
  baseprice: '',
  baseweight: '',
  priceperkg: '',
  basedistance: '',
  priceperkm: '',
  handlingcharges: '',
  priority: 1,
  status: 'active'
};

// ==============================|| Pricing page ||============================== //

const ClientsPricing = () => {
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down('md'));
  const containerRef = useRef();
  const queryClient = useQueryClient();
  const [appId, setAppId] = useState(0);
  const [locaName, setLocoName] = useState('All');
  const [searchword, setSearchword] = useState('');
  const [debouncedSearch, setDebouncedSearch] = useState('');
  const [dialogOpen, setDialogOpen] = useState(false);
  const [form, setForm] = useState(emptyForm);
  const [quoteOpen, setQuoteOpen] = useState(false);
  const [quoteForm, setQuoteForm] = useState({ tenant: null, location: null, vehicletype: 'Bike', weight: '', distance: '' });

  const { data: pricing = [], isLoading } = useQuery({
    queryKey: ['getallpricing', appId],
    queryFn: getallpricing,
    keepPreviousData: true
  });

  const { data: tenants = [] } = useQuery({ queryKey: ['pricing-tenants'], queryFn: getTenants });
  const { data: locations = [] } = useQuery({ queryKey: ['pricing-locations'], queryFn: fetchAppLocations });

  const tenantMap = useMemo(() => new Map((tenants || []).map((t) => [t.tenantid, t])), [tenants]);
  const locationMap = useMemo(
    () => new Map((locations || []).filter((l) => l.applocationid).map((l) => [l.applocationid, l])),
    [locations]
  );
  const locationOptions = useMemo(() => (locations || []).filter((l) => l.applocationid), [locations]);

  const tenantName = (row) => row.tenantname || tenantMap.get(row.tenantid)?.tenantname || (row.tenantid ? `Tenant #${row.tenantid}` : '—');
  const zoneName = (row) =>
    row.applocation || locationMap.get(row.applocationid)?.locationname || (row.applocationid ? `Zone #${row.applocationid}` : '—');

  const rows = useMemo(() => {
    if (!debouncedSearch) return pricing;
    const q = debouncedSearch.toLowerCase().trim();
    return pricing.filter((row) =>
      [tenantName(row), row.vehicletype, zoneName(row), String(row.pricingid)]
        .filter(Boolean)
        .some((field) => String(field).toLowerCase().includes(q))
    );
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pricing, debouncedSearch, tenantMap, locationMap]);

  const stats = useMemo(() => {
    const total = pricing.length;
    const tenantsPriced = new Set(pricing.map((r) => r.tenantid).filter(Boolean)).size;
    const avgBase = total ? pricing.reduce((sum, r) => sum + (Number(r.baseprice) || 0), 0) / total : 0;
    const activeCount = pricing.filter((r) => String(r.status).toLowerCase() === 'active').length;
    return { total, tenantsPriced, avgBase, activeCount };
  }, [pricing]);

  const KPI_META = [
    { key: 'total', label: 'Total Pricing Rules', color: BRAND, icon: MdOutlineLocalOffer, value: stats.total },
    { key: 'tenants', label: 'Tenants Priced', color: '#0ea5e9', icon: MdOutlineGroups, value: stats.tenantsPriced },
    { key: 'avg', label: 'Avg Base Price', color: '#f59e0b', icon: MdOutlineAttachMoney, value: formatRupees(stats.avgBase) },
    { key: 'active', label: 'Active Rules', color: '#10b981', icon: MdOutlinePlace, value: stats.activeCount }
  ];

  const opentoast = (message, variant = 'error') => {
    enqueueSnackbar(message, { variant, anchorOrigin: { vertical: 'top', horizontal: 'right' }, autoHideDuration: 2000 });
  };

  const savePricingMutation = useMutation({
    mutationFn: (payload) => (payload.pricingid ? updateAdminPricing(payload.pricingid, payload.data) : createAdminPricing(payload.data)),
    onSuccess: (res) => {
      if (res.success) {
        opentoast(form.pricingid ? 'Pricing rule updated' : 'Pricing rule created', 'success');
        queryClient.invalidateQueries({ queryKey: ['getallpricing'] });
        setDialogOpen(false);
        setForm(emptyForm);
      } else {
        opentoast(res.message || 'Failed to save pricing rule');
      }
    },
    onError: (err) => opentoast(err.response?.data?.message || err.message || 'Failed to save pricing rule')
  });

  const deletePricingMutation = useMutation({
    mutationFn: (id) => deleteAdminPricing(id),
    onSuccess: (res) => {
      if (res.success) {
        opentoast('Pricing rule deleted', 'success');
        queryClient.invalidateQueries({ queryKey: ['getallpricing'] });
      } else {
        opentoast(res.message || 'Failed to delete pricing rule');
      }
    },
    onError: (err) => opentoast(err.response?.data?.message || err.message || 'Failed to delete pricing rule')
  });

  // POST /admin/pricing/simulate — request/response shape isn't documented
  // beyond the endpoint existing ("same handler as quote"). Rendered
  // defensively below rather than assuming a specific result field name.
  const quoteMutation = useMutation({
    mutationFn: (data) => simulatePricing(data),
    onError: (err) => opentoast(err.response?.data?.message || err.message || 'Failed to get quote')
  });

  const handleQuote = () => {
    if (!quoteForm.tenant?.tenantid || !quoteForm.distance) {
      opentoast('Choose Tenant and fill Distance');
      return;
    }
    quoteMutation.mutate({
      tenantid: quoteForm.tenant.tenantid,
      applocationid: quoteForm.location?.applocationid,
      vehicletype: quoteForm.vehicletype,
      weight: Number(quoteForm.weight) || 0,
      distance: Number(quoteForm.distance) || 0
    });
  };

  const openCreateDialog = () => {
    setForm(emptyForm);
    setDialogOpen(true);
  };

  const openEditDialog = (row) => {
    setForm({
      pricingid: row.pricingid,
      tenant: tenantMap.get(row.tenantid) || (row.tenantid ? { tenantid: row.tenantid, tenantname: tenantName(row) } : null),
      location: locationMap.get(row.applocationid) || null,
      vehicletype: row.vehicletype || 'Bike',
      baseprice: row.baseprice ?? '',
      baseweight: row.baseweight ?? '',
      priceperkg: row.priceperkg ?? '',
      basedistance: row.basedistance ?? '',
      priceperkm: row.priceperkm ?? '',
      handlingcharges: row.handlingcharges ?? '',
      priority: row.priority ?? 1,
      status: row.status || 'active'
    });
    setDialogOpen(true);
  };

  const handleDelete = (row) => {
    if (window.confirm(`Delete this pricing rule for ${tenantName(row)}?`)) {
      deletePricingMutation.mutate(row.pricingid);
    }
  };

  const handleSave = () => {
    if (!form.tenant?.tenantid) {
      opentoast('Choose Tenant');
      return;
    }
    if (!form.baseprice || !form.priceperkm) {
      opentoast('Fill Base Price and Price / KM');
      return;
    }
    // POST/PUT /admin/pricing body per express-console-api.md.
    const data = {
      tenantid: form.tenant.tenantid,
      applocationid: form.location?.applocationid,
      vehicletype: form.vehicletype,
      baseprice: Number(form.baseprice),
      baseweight: Number(form.baseweight) || 0,
      priceperkg: Number(form.priceperkg) || 0,
      basedistance: Number(form.basedistance) || 0,
      priceperkm: Number(form.priceperkm),
      handlingcharges: Number(form.handlingcharges) || 0,
      currency: 'INR',
      priority: Number(form.priority) || 1,
      status: form.status
    };
    savePricingMutation.mutate({ pricingid: form.pricingid, data });
  };

  return (
    <>
      {(isLoading || savePricingMutation.isPending || deletePricingMutation.isPending) && <Loader />}

      {/* ============================================= || Header || ============================================= */}
      <PageHeader
        title="Pricing"
        subtitle={`Live · ${locaName || 'All Zones'}`}
        live
        action={
          <Stack direction="row" spacing={1.25} alignItems="center">
            <LocationAutocomplete
              locaName={locaName}
              setAppId={setAppId}
              setLocoName={setLocoName}
              pill
              accentColor={BRAND}
              icon={<MdMyLocation size={14} />}
              placeholder="Select Zone"
              paperComponent={SoftPaper}
              sx={{ width: { xs: '100%', sm: 220 }, zIndex: 100 }}
            />
            <Button
              variant="outlined"
              startIcon={<MdCalculate size={16} />}
              onClick={() => setQuoteOpen(true)}
              sx={{ borderColor: BRAND, color: BRAND, whiteSpace: 'nowrap' }}
            >
              Quote Price
            </Button>
            <Button
              variant="contained"
              startIcon={<MdAdd size={16} />}
              onClick={openCreateDialog}
              sx={{ bgcolor: BRAND, whiteSpace: 'nowrap' }}
            >
              New Pricing Rule
            </Button>
          </Stack>
        }
      />

      {/* ============================================= || KPI Cards || ============================================= */}
      <Grid container spacing={{ xs: 2, md: 2.5 }} sx={{ mb: { xs: 1.5, md: 2 } }}>
        {KPI_META.map((item) => {
          const Icon = item.icon;
          return (
            <Grid item key={item.key} xs={6} sm={6} md={3}>
              <StatCard title={item.label} value={item.value} icon={<Icon size={20} />} color={item.color} />
            </Grid>
          );
        })}
      </Grid>

      {/* ============================================= || Search Header || ============================================= */}
      <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={{ xs: 'column', sm: 'row' }}
          alignItems={{ xs: 'stretch', sm: 'center' }}
          justifyContent="space-between"
          spacing={1.25}
        >
          <Stack direction="row" alignItems="center" spacing={1.25}>
            <AccentAvatar color={BRAND} size={32}>
              <MdLocalOffer size={18} />
            </AccentAvatar>
            <Stack>
              <Typography
                variant="caption"
                sx={{ fontWeight: 800, color: DT.textSecondary, letterSpacing: 0.6, textTransform: 'uppercase' }}
              >
                Pricing Catalog
              </Typography>
              <Typography variant="body2" sx={{ color: DT.textPrimary, fontWeight: 700 }}>
                {pricing.length} total · {rows.length} shown
              </Typography>
            </Stack>
          </Stack>
          <Box sx={{ width: { xs: '100%', sm: 280, lg: 340 }, flex: { xs: '1 1 100%', sm: '0 0 auto' } }}>
            <DebounceSearchBar
              value={searchword}
              onChange={setSearchword}
              onDebouncedChange={setDebouncedSearch}
              placeholder={`Search pricing (ctrl+k)`}
              sx={{
                m: 0,
                width: '100%',
                borderRadius: DT.radiusField + 'px',
                bgcolor: DT.surface,
                '& fieldset': { borderColor: DT.borderSubtle, borderWidth: 1 },
                '&:hover fieldset': { borderColor: DT.borderHover },
                '&.Mui-focused fieldset': { borderColor: BRAND, borderWidth: 1.5 },
                '&.Mui-focused': { boxShadow: `0 0 0 3px ${ring(BRAND)}` }
              }}
            />
          </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'
        }}
      >
        {isMobile ? (
          rows.length === 0 && !isLoading ? (
            <Stack alignItems="center" spacing={1.5} sx={{ py: 6, px: 2 }}>
              <Avatar sx={{ width: 64, height: 64, bgcolor: soft('#94a3b8'), color: DT.textMuted }}>
                <MdLocalOffer size={28} />
              </Avatar>
              <Typography variant="subtitle1" sx={{ fontWeight: 700, color: DT.textPrimary }}>
                No pricing to show
              </Typography>
              <Typography variant="caption" sx={{ color: DT.textSecondary, textAlign: 'center' }}>
                {searchword ? 'Try a different keyword.' : 'Create a pricing rule to get started.'}
              </Typography>
            </Stack>
          ) : (
            <MobileCardList scroll>
              {rows.map((row, index) => (
                <MobileCard
                  key={row.pricingid || `${row.tenantid}-${index}`}
                  accent={BRAND}
                  header={
                    <Stack direction="row" alignItems="center" justifyContent="space-between" spacing={1}>
                      <Stack direction="row" alignItems="center" spacing={1} sx={{ minWidth: 0 }}>
                        <AccentAvatar color={BRAND} size={36}>
                          <MdGroups size={18} />
                        </AccentAvatar>
                        <Stack sx={{ minWidth: 0 }}>
                          <Typography variant="subtitle2" sx={{ fontWeight: 700, color: DT.textPrimary }} noWrap>
                            {tenantName(row)}
                          </Typography>
                          <Typography variant="caption" sx={{ color: DT.textSecondary }}>
                            ID #{row.pricingid}
                          </Typography>
                        </Stack>
                      </Stack>
                      <Stack direction="row" spacing={0.5}>
                        <IconButton size="small" onClick={() => openEditDialog(row)} sx={{ color: BRAND }}>
                          <MdEdit size={14} />
                        </IconButton>
                        <IconButton size="small" onClick={() => handleDelete(row)} sx={{ color: '#ef4444' }}>
                          <MdDeleteOutline size={14} />
                        </IconButton>
                      </Stack>
                    </Stack>
                  }
                >
                  <Stack direction="row" spacing={0.75} sx={{ mt: 1, flexWrap: 'wrap', gap: 0.75 }}>
                    <Box
                      sx={{
                        display: 'inline-flex',
                        alignItems: 'center',
                        gap: 0.5,
                        px: 1,
                        py: 0.375,
                        borderRadius: 999,
                        bgcolor: tint('#10b981'),
                        border: `1px solid ${edge('#10b981')}`,
                        color: '#10b981',
                        fontSize: 11,
                        fontWeight: 800
                      }}
                    >
                      <MdPlace size={12} /> {zoneName(row)}
                    </Box>
                    <Box
                      sx={{
                        display: 'inline-flex',
                        alignItems: 'center',
                        gap: 0.5,
                        px: 1,
                        py: 0.375,
                        borderRadius: 999,
                        bgcolor: tint('#0ea5e9'),
                        border: `1px solid ${edge('#0ea5e9')}`,
                        color: '#0ea5e9',
                        fontSize: 11,
                        fontWeight: 800
                      }}
                    >
                      <MdSpeed size={12} /> {row.vehicletype || '—'}
                    </Box>
                  </Stack>

                  <MobileFieldGrid>
                    <MobileField label="Base Price">
                      <MetricPill label={formatRupees(row.baseprice)} />
                    </MobileField>
                    <MobileField label="Price / KM">
                      <MetricPill label={formatRupees(row.priceperkm)} />
                    </MobileField>
                    <MobileField label="Price / KG">
                      <MetricPill label={formatRupees(row.priceperkg)} />
                    </MobileField>
                    <MobileField label="Handling">
                      <MetricPill label={formatRupees(row.handlingcharges)} />
                    </MobileField>
                    <MobileField label="Status">
                      <Stack direction="row" alignItems="center" spacing={0.5}>
                        <MdReceiptLong size={14} color={DT.textMuted} />
                        <Typography variant="subtitle2" sx={{ fontWeight: 700, color: DT.textPrimary }}>
                          {row.status || '—'}
                        </Typography>
                      </Stack>
                    </MobileField>
                  </MobileFieldGrid>
                </MobileCard>
              ))}
            </MobileCardList>
          )
        ) : (
          <TableContainer
            ref={containerRef}
            sx={{
              maxHeight: { xs: 'calc(100vh - 220px)', md: 'calc(100vh - 190px)' },
              '&::-webkit-scrollbar': { width: 10, height: 10 },
              '&::-webkit-scrollbar-thumb': { backgroundColor: edge(BRAND), borderRadius: 8, '&:hover': { backgroundColor: BRAND } },
              '&::-webkit-scrollbar-track': { backgroundColor: DT.surfaceAlt }
            }}
          >
            <Table stickyHeader sx={{ minWidth: { xs: 860, md: 1180 } }}>
              <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>Tenant</TableCell>
                  <TableCell>Zone</TableCell>
                  <TableCell>Vehicle</TableCell>
                  <TableCell align="center">Base Price</TableCell>
                  <TableCell align="center">Price / KM</TableCell>
                  <TableCell align="center">Price / KG</TableCell>
                  <TableCell align="center">Handling</TableCell>
                  <TableCell align="center">Status</TableCell>
                  <TableCell align="right">Actions</TableCell>
                </TableRow>
              </TableHead>

              <TableBody>
                {isLoading && <OrdersTableSkeleton col={6} />}
                {rows.length === 0 && !isLoading ? (
                  <TableRow>
                    <TableCell colSpan={10} sx={{ py: 6 }}>
                      <Stack alignItems="center" spacing={1.5}>
                        <Avatar sx={{ width: 64, height: 64, bgcolor: soft('#94a3b8'), color: DT.textMuted }}>
                          <MdLocalOffer size={28} />
                        </Avatar>
                        <Typography variant="subtitle1" sx={{ fontWeight: 700, color: DT.textPrimary }}>
                          No pricing to show
                        </Typography>
                        <Typography variant="caption" sx={{ color: DT.textSecondary }}>
                          {searchword ? 'Try a different keyword.' : 'Create a pricing rule to get started.'}
                        </Typography>
                      </Stack>
                    </TableCell>
                  </TableRow>
                ) : (
                  rows.map((row, index) => (
                    <TableRow
                      key={row.pricingid || `${row.tenantid}-${index}`}
                      sx={{
                        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).padStart(2, '0')}
                        </Typography>
                      </TableCell>

                      <TableCell>
                        <Stack direction="row" alignItems="center" spacing={1}>
                          <AccentAvatar color={BRAND} size={36}>
                            <MdGroups size={18} />
                          </AccentAvatar>
                          <Stack>
                            <Typography variant="subtitle2" sx={{ fontWeight: 700, color: DT.textPrimary, whiteSpace: 'nowrap' }}>
                              {tenantName(row)}
                            </Typography>
                            <Typography variant="caption" sx={{ color: DT.textSecondary }}>
                              ID #{row.pricingid}
                            </Typography>
                          </Stack>
                        </Stack>
                      </TableCell>

                      <TableCell>
                        <CategoryChip icon={<MdPlace size={12} />} label={zoneName(row)} />
                      </TableCell>

                      <TableCell>
                        <CategoryChip icon={<MdSpeed size={12} />} label={row.vehicletype || '—'} />
                      </TableCell>

                      <TableCell align="center">
                        <MetricPill label={formatRupees(row.baseprice)} />
                      </TableCell>

                      <TableCell align="center">
                        <MetricPill label={formatRupees(row.priceperkm)} />
                      </TableCell>

                      <TableCell align="center">
                        <MetricPill label={formatRupees(row.priceperkg)} />
                      </TableCell>

                      <TableCell align="center">
                        <MetricPill label={formatRupees(row.handlingcharges)} />
                      </TableCell>

                      <TableCell align="center">
                        <CategoryChip icon={<MdPriceCheck size={12} />} label={row.status || '—'} />
                      </TableCell>

                      <TableCell align="right">
                        <Stack direction="row" spacing={0.5} justifyContent="flex-end">
                          <Tooltip title="Edit rule" placement="top">
                            <IconButton size="small" onClick={() => openEditDialog(row)} sx={{ color: BRAND }}>
                              <MdEdit size={16} />
                            </IconButton>
                          </Tooltip>
                          <Tooltip title="Delete rule" placement="top">
                            <IconButton size="small" onClick={() => handleDelete(row)} sx={{ color: '#ef4444' }}>
                              <MdDeleteOutline size={16} />
                            </IconButton>
                          </Tooltip>
                        </Stack>
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </TableContainer>
        )}
      </Paper>

      {/* ============================================= || Create / Edit dialog || ============================================= */}
      <Dialog open={dialogOpen} onClose={() => setDialogOpen(false)} maxWidth="sm" fullWidth>
        <DialogTitle sx={{ fontWeight: 700 }}>{form.pricingid ? 'Edit Pricing Rule' : 'New Pricing Rule'}</DialogTitle>
        <DialogContent>
          <Grid container spacing={2} sx={{ mt: 0.5 }}>
            <Grid item xs={12} sm={6}>
              <Stack spacing={1}>
                <InputLabel>Tenant</InputLabel>
                <Autocomplete
                  options={tenants || []}
                  getOptionLabel={(option) => option.tenantname || ''}
                  value={form.tenant}
                  onChange={(e, value) => setForm((f) => ({ ...f, tenant: value }))}
                  renderInput={(params) => <TextField {...params} placeholder="Choose tenant" />}
                />
              </Stack>
            </Grid>
            <Grid item xs={12} sm={6}>
              <Stack spacing={1}>
                <InputLabel>Zone (optional)</InputLabel>
                <Autocomplete
                  options={locationOptions}
                  getOptionLabel={(option) => option.locationname || ''}
                  value={form.location}
                  onChange={(e, value) => setForm((f) => ({ ...f, location: value }))}
                  renderInput={(params) => <TextField {...params} placeholder="Choose zone" />}
                />
              </Stack>
            </Grid>
            <Grid item xs={12} sm={6}>
              <Stack spacing={1}>
                <InputLabel>Vehicle Type</InputLabel>
                <Select fullWidth value={form.vehicletype} onChange={(e) => setForm((f) => ({ ...f, vehicletype: e.target.value }))}>
                  {VEHICLE_TYPES.map((v) => (
                    <MenuItem key={v} value={v}>
                      {v}
                    </MenuItem>
                  ))}
                </Select>
              </Stack>
            </Grid>
            <Grid item xs={12} sm={6}>
              <Stack spacing={1}>
                <InputLabel>Status</InputLabel>
                <Select fullWidth value={form.status} onChange={(e) => setForm((f) => ({ ...f, status: e.target.value }))}>
                  <MenuItem value="active">Active</MenuItem>
                  <MenuItem value="inactive">Inactive</MenuItem>
                </Select>
              </Stack>
            </Grid>
            <Grid item xs={12} sm={6}>
              <Stack spacing={1}>
                <InputLabel>Base Price</InputLabel>
                <TextField type="number" value={form.baseprice} onChange={(e) => setForm((f) => ({ ...f, baseprice: e.target.value }))} />
              </Stack>
            </Grid>
            <Grid item xs={12} sm={6}>
              <Stack spacing={1}>
                <InputLabel>Base Weight (kg)</InputLabel>
                <TextField type="number" value={form.baseweight} onChange={(e) => setForm((f) => ({ ...f, baseweight: e.target.value }))} />
              </Stack>
            </Grid>
            <Grid item xs={12} sm={6}>
              <Stack spacing={1}>
                <InputLabel>Price / KG</InputLabel>
                <TextField type="number" value={form.priceperkg} onChange={(e) => setForm((f) => ({ ...f, priceperkg: e.target.value }))} />
              </Stack>
            </Grid>
            <Grid item xs={12} sm={6}>
              <Stack spacing={1}>
                <InputLabel>Base Distance (km)</InputLabel>
                <TextField
                  type="number"
                  value={form.basedistance}
                  onChange={(e) => setForm((f) => ({ ...f, basedistance: e.target.value }))}
                />
              </Stack>
            </Grid>
            <Grid item xs={12} sm={6}>
              <Stack spacing={1}>
                <InputLabel>Price / KM</InputLabel>
                <TextField type="number" value={form.priceperkm} onChange={(e) => setForm((f) => ({ ...f, priceperkm: e.target.value }))} />
              </Stack>
            </Grid>
            <Grid item xs={12} sm={6}>
              <Stack spacing={1}>
                <InputLabel>Handling Charges</InputLabel>
                <TextField
                  type="number"
                  value={form.handlingcharges}
                  onChange={(e) => setForm((f) => ({ ...f, handlingcharges: e.target.value }))}
                />
              </Stack>
            </Grid>
            <Grid item xs={12} sm={6}>
              <Stack spacing={1}>
                <InputLabel>Priority</InputLabel>
                <TextField type="number" value={form.priority} onChange={(e) => setForm((f) => ({ ...f, priority: e.target.value }))} />
              </Stack>
            </Grid>
          </Grid>
        </DialogContent>
        <DialogActions sx={{ px: 3, pb: 2 }}>
          <Button onClick={() => setDialogOpen(false)}>Cancel</Button>
          <Button variant="contained" onClick={handleSave} sx={{ bgcolor: BRAND }}>
            {form.pricingid ? 'Save Changes' : 'Create'}
          </Button>
        </DialogActions>
      </Dialog>

      {/* ============================================= || Quote price dialog || ============================================= */}
      <Dialog open={quoteOpen} onClose={() => setQuoteOpen(false)} maxWidth="xs" fullWidth>
        <DialogTitle sx={{ fontWeight: 700 }}>Quote Price</DialogTitle>
        <DialogContent>
          <Grid container spacing={2} sx={{ mt: 0.5 }}>
            <Grid item xs={12}>
              <Stack spacing={1}>
                <InputLabel>Tenant</InputLabel>
                <Autocomplete
                  options={tenants || []}
                  getOptionLabel={(option) => option.tenantname || ''}
                  value={quoteForm.tenant}
                  onChange={(e, value) => setQuoteForm((f) => ({ ...f, tenant: value }))}
                  renderInput={(params) => <TextField {...params} placeholder="Choose tenant" />}
                />
              </Stack>
            </Grid>
            <Grid item xs={12}>
              <Stack spacing={1}>
                <InputLabel>Zone (optional)</InputLabel>
                <Autocomplete
                  options={locationOptions}
                  getOptionLabel={(option) => option.locationname || ''}
                  value={quoteForm.location}
                  onChange={(e, value) => setQuoteForm((f) => ({ ...f, location: value }))}
                  renderInput={(params) => <TextField {...params} placeholder="Choose zone" />}
                />
              </Stack>
            </Grid>
            <Grid item xs={12} sm={6}>
              <Stack spacing={1}>
                <InputLabel>Vehicle Type</InputLabel>
                <Select
                  fullWidth
                  value={quoteForm.vehicletype}
                  onChange={(e) => setQuoteForm((f) => ({ ...f, vehicletype: e.target.value }))}
                >
                  {VEHICLE_TYPES.map((v) => (
                    <MenuItem key={v} value={v}>
                      {v}
                    </MenuItem>
                  ))}
                </Select>
              </Stack>
            </Grid>
            <Grid item xs={12} sm={6}>
              <Stack spacing={1}>
                <InputLabel>Weight (kg)</InputLabel>
                <TextField
                  type="number"
                  value={quoteForm.weight}
                  onChange={(e) => setQuoteForm((f) => ({ ...f, weight: e.target.value }))}
                />
              </Stack>
            </Grid>
            <Grid item xs={12}>
              <Stack spacing={1}>
                <InputLabel>Distance (km)</InputLabel>
                <TextField
                  type="number"
                  value={quoteForm.distance}
                  onChange={(e) => setQuoteForm((f) => ({ ...f, distance: e.target.value }))}
                />
              </Stack>
            </Grid>

            {quoteMutation.isPending && (
              <Grid item xs={12}>
                <Typography variant="body2" sx={{ color: DT.textSecondary }}>
                  Calculating…
                </Typography>
              </Grid>
            )}

            {quoteMutation.data && (
              <Grid item xs={12}>
                <Paper variant="outlined" sx={{ p: 1.5, borderRadius: 2, bgcolor: DT.surfaceAlt }}>
                  {quoteMutation.data.success === false ? (
                    <Typography variant="body2" sx={{ color: '#ef4444' }}>
                      {quoteMutation.data.message || 'No quote available'}
                    </Typography>
                  ) : (
                    <Stack spacing={0.75}>
                      {Object.entries(quoteMutation.data.data || quoteMutation.data).map(([key, value]) => (
                        <Stack key={key} direction="row" justifyContent="space-between">
                          <Typography variant="caption" sx={{ color: DT.textMuted, textTransform: 'uppercase', fontWeight: 700 }}>
                            {key}
                          </Typography>
                          <Typography variant="body2" sx={{ fontWeight: 700 }}>
                            {typeof value === 'object' ? JSON.stringify(value) : String(value ?? '—')}
                          </Typography>
                        </Stack>
                      ))}
                    </Stack>
                  )}
                </Paper>
              </Grid>
            )}
          </Grid>
        </DialogContent>
        <DialogActions sx={{ px: 3, pb: 2 }}>
          <Button
            onClick={() => {
              setQuoteOpen(false);
              quoteMutation.reset();
              setQuoteForm({ tenant: null, location: null, vehicletype: 'Bike', weight: '', distance: '' });
            }}
          >
            Close
          </Button>
          <Button variant="contained" onClick={handleQuote} disabled={quoteMutation.isPending} sx={{ bgcolor: BRAND }}>
            Get Quote
          </Button>
        </DialogActions>
      </Dialog>
    </>
  );
};

export default ClientsPricing;
