import { useState, useEffect } from 'react';
import {
  Card, Box, Table, TableBody, TableCell, TableContainer, TableHead, TableRow,
  Typography, TextField, InputAdornment, CircularProgress, MenuItem,
  Select, FormControl, OutlinedInput, alpha, Avatar, Chip, Stack, Collapse, Button,
  Dialog, DialogTitle, DialogContent, DialogActions, IconButton, Grid, Tooltip, Alert, Snackbar
} from '@mui/material';
import AddIcon from '@mui/icons-material/Add';
import EditOutlinedIcon from '@mui/icons-material/EditOutlined';
import AddCircleOutlineIcon from '@mui/icons-material/AddCircleOutline';
import CloseIcon from '@mui/icons-material/Close';
import SearchIcon from '@mui/icons-material/Search';
import StorefrontOutlinedIcon from '@mui/icons-material/StorefrontOutlined';
import LocalShippingOutlinedIcon from '@mui/icons-material/LocalShippingOutlined';
import PlaceOutlinedIcon from '@mui/icons-material/PlaceOutlined';
import KeyboardArrowDownIcon from '@mui/icons-material/KeyboardArrowDown';
import KeyboardArrowUpIcon from '@mui/icons-material/KeyboardArrowUp';
import PageHeader from '@/components/PageHeader';
import { fetchUsers } from '@/utils/apiClient';

const API_BASE = import.meta.env.VITE_API_BASE || 'https://api.doormile.com/api/v1';

const getHeaders = () => {
  const token = localStorage.getItem('auth_token');
  return {
    'Content-Type': 'application/json',
    ...(token ? { Authorization: `Bearer ${token}` } : {}),
  };
};

async function apiFetchPricing() {
  const res = await fetch(`${API_BASE}/admin/carrier-pricing?limit=1000`, { headers: getHeaders() });
  if (!res.ok) throw new Error('Failed to fetch pricing');
  const json = await res.json();
  return Array.isArray(json) ? { data: json } : json;
}

async function apiSavePricing(data) {
  const isUpdate = !!data.id;
  const url = isUpdate ? `${API_BASE}/admin/carrier-pricing/${data.id}` : `${API_BASE}/admin/carrier-pricing`;
  const method = isUpdate ? 'PUT' : 'POST';
  const res = await fetch(url, {
    method,
    headers: getHeaders(),
    body: JSON.stringify({
      company: data.company,
      weight_slab: data.weight_slab,
      zone: data.zone || '',
      service_type: data.service_type || '',
      rate: String(data.rate)
    })
  });
  if (!res.ok) {
    const err = await res.json().catch(() => ({}));
    throw new Error(err.error || err.message || 'Failed to save pricing');
  }
  return res.status === 204 ? {} : res.json().catch(() => ({}));
}

const ZONES = ['Local / Same', 'Within Tamilnadu', 'Interstate India'];
const WEIGHT_SLABS = ['< 500g', '500g - 1kg', '1kg - 2kg', '2kg - 5kg', '> 5kg'];

// isCell=true → editing a specific cell (company/slab/zone locked, only rate editable)
// isCell=false → "Add Rate" button (all fields editable)
function PricingFormDialog({ open, onClose, onSave, initialData, isCell = false, pricingList = [], providerColumns = [], providerUsesServiceType = false }) {
  const [formData, setFormData] = useState({});
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState(null);

  useEffect(() => {
    if (open) {
      setFormData(initialData || { company: '', weight_slab: '', zone: '', rate: '' });
      setError(null);
    }
  }, [open, initialData]);

  const set = (field) => (e) => setFormData(prev => ({ ...prev, [field]: e.target.value }));

  // Column key: zone if available, otherwise service_type (e.g. DTDC)
  const colKey = (p) => ((p.zone || '').trim() || (p.service_type || '').trim());

  const findExistingRecord = (data) => {
    const company = (data.company || '').trim();
    const slab = (data.weight_slab || '').trim();
    const col = (data.zone || data.service_type || '').trim();
    return pricingList.find(p =>
      (p.company || '').trim() === company &&
      (p.weight_slab || '').trim() === slab &&
      colKey(p) === col
    ) || null;
  };

  const handleSave = async () => {
    const colValue = (formData.zone || formData.service_type || '').trim();
    if (!isCell) {
      if (!formData.company?.trim()) { setError('Company is required.'); return; }
      if (!formData.weight_slab?.trim()) { setError('Weight slab is required.'); return; }
      if (!colValue) { setError('Zone / Service Type is required.'); return; }
    }
    if (!String(formData.rate ?? '').trim()) { setError('Rate is required.'); return; }

    setSaving(true);
    setError(null);
    try {
      let dataToSave = { ...formData };
      // Route the column value to the right field based on provider type
      if (!isCell) {
        dataToSave = {
          ...dataToSave,
          zone: providerUsesServiceType ? '' : colValue,
          service_type: providerUsesServiceType ? colValue : (dataToSave.service_type || ''),
        };
      }
      if (!dataToSave.id) {
        const existing = findExistingRecord(dataToSave);
        if (existing) dataToSave = { ...dataToSave, id: existing.id };
      }
      await apiSavePricing(dataToSave);
      onSave();
      onClose();
    } catch (err) {
      console.error(err);
      setError(err.message || 'Failed to save. Please try again.');
    } finally {
      setSaving(false);
    }
  };

  return (
    <>
      <Snackbar
        open={!!error}
        autoHideDuration={6000}
        onClose={() => setError(null)}
        anchorOrigin={{ vertical: 'top', horizontal: 'right' }}
        sx={{ zIndex: 9999 }}
      >
        <Alert onClose={() => setError(null)} severity="error" variant="filled" sx={{ width: '100%', boxShadow: 3 }}>
          {error}
        </Alert>
      </Snackbar>

      <Dialog open={open} onClose={saving ? undefined : onClose} maxWidth="xs" fullWidth>
        <DialogTitle sx={{ fontWeight: 800, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          {isCell ? (initialData?.id ? 'Edit Rate' : 'Add Rate') : (initialData?.id ? 'Edit Rate' : 'Add New Rate')}
          <IconButton size="small" onClick={onClose} disabled={saving}><CloseIcon fontSize="small" /></IconButton>
        </DialogTitle>
        <DialogContent dividers>
          <Grid container spacing={2}>
          {isCell ? (
            <Grid item xs={12}>
              <Box sx={{ p: 1.5, borderRadius: 2, bgcolor: alpha('#c01227', 0.04), border: '1px solid', borderColor: alpha('#c01227', 0.15), mb: 0.5 }}>
                <Typography variant="caption" sx={{ fontWeight: 700, color: 'grey.500', letterSpacing: 0.5, display: 'block', mb: 0.5 }}>UPDATING RATE FOR</Typography>
                <Typography variant="subtitle2" sx={{ fontWeight: 700, color: 'grey.900' }}>{formData.company}</Typography>
                <Typography variant="body2" sx={{ color: 'grey.600', mt: 0.25 }}>{formData.weight_slab} · {formData.zone || formData.service_type}</Typography>
              </Box>
            </Grid>
          ) : (
            <>
              <Grid item xs={12}>
                <TextField fullWidth label="Company *" value={formData.company || ''} onChange={set('company')} size="small" />
              </Grid>
              <Grid item xs={12}>
                <TextField select fullWidth label="Weight Slab *" value={formData.weight_slab || ''} onChange={set('weight_slab')} size="small">
                  {WEIGHT_SLABS.map(s => <MenuItem key={s} value={s}>{s}</MenuItem>)}
                </TextField>
              </Grid>
              <Grid item xs={12}>
                <TextField
                  select fullWidth
                  label={providerUsesServiceType ? 'Service Type *' : 'Zone / Service Type *'}
                  value={formData.zone || formData.service_type || ''}
                  onChange={(e) => setFormData(prev => ({
                    ...prev,
                    zone: providerUsesServiceType ? '' : e.target.value,
                    service_type: providerUsesServiceType ? e.target.value : ''
                  }))}
                  size="small"
                >
                  {(providerColumns.length > 0 ? providerColumns : ZONES).map(z => (
                    <MenuItem key={z} value={z}>{z}</MenuItem>
                  ))}
                </TextField>
              </Grid>
            </>
          )}
          <Grid item xs={12}>
            <TextField
              fullWidth
              label="Rate (₹) *"
              value={formData.rate || ''}
              onChange={set('rate')}
              size="small"
              placeholder="e.g. 25 or 25-35"
              autoFocus
            />
          </Grid>
        </Grid>
      </DialogContent>
      <DialogActions sx={{ p: 2, bgcolor: 'grey.50' }}>
        <Button onClick={onClose} disabled={saving} color="inherit">Cancel</Button>
        <Button onClick={handleSave} disabled={saving} variant="contained" sx={{ bgcolor: '#c01227', '&:hover': { bgcolor: '#a00f20' }, borderRadius: 2 }}>
          {saving ? 'Saving...' : 'Save Rate'}
        </Button>
      </DialogActions>
    </Dialog>
    </>
  );
}

async function apiFetchSurveys() {
  const res = await fetch(`${API_BASE}/admin/competitor-branches?limit=1000`, { headers: getHeaders() });
  if (!res.ok) throw new Error('Failed to fetch surveys');
  const json = await res.json();
  const data = Array.isArray(json) ? json : (json.data || []);
  return { data, total: data.length };
}

export default function Pricing() {
  const [pricingList, setPricingList] = useState([]);
  const [surveysList, setSurveysList] = useState([]);
  const [loading, setLoading] = useState(true);
  const [selectedProvider, setSelectedProvider] = useState('');
  const [searchQuery, setSearchQuery] = useState('');
  const [locationsOpen, setLocationsOpen] = useState(false);
  const [formOpen, setFormOpen] = useState(false);
  const [editingRecord, setEditingRecord] = useState(null);
  const [isEditMode, setIsEditMode] = useState(false);
  const [isCellEdit, setIsCellEdit] = useState(false);
  const [users, setUsers] = useState([]);

  const loadData = () => {
    let cancelled = false;
    setLoading(true);
    Promise.all([
      apiFetchPricing().catch(() => ({ data: [] })),
      apiFetchSurveys().catch(() => ({ data: [] })),
      fetchUsers().catch(() => [])
    ]).then(([pRes, sRes, userRes]) => {
      if (!cancelled) {
        setPricingList(Array.isArray(pRes) ? pRes : (pRes.data || []));
        setSurveysList(sRes.data || sRes || []);
        setUsers(Array.isArray(userRes) ? userRes : (userRes.data || []));
      }
    }).catch(err => console.error("Failed to fetch data", err))
    .finally(() => {
      if (!cancelled) setLoading(false);
    });
    return () => { cancelled = true; };
  };

  useEffect(() => {
    return loadData();
  }, []);

  // Ensure absolutely unique companies and default selection
  const companies = [...new Set(pricingList.map(p => p.company).filter(Boolean))];
  useEffect(() => {
    if (!selectedProvider && companies.length > 0) {
      setSelectedProvider(companies[0]);
    }
  }, [companies, selectedProvider]);

  const providerRates = pricingList.filter(p => p.company === selectedProvider);
  // Normalize: lowercase, trim edges, collapse internal spaces
  const normCompany = (s) => (s || '').toLowerCase().trim().replace(/\s+/g, ' ');
  const normProvider = normCompany(selectedProvider);
  const providerSurveys = surveysList.filter(p => {
    const pn = normCompany(p.company);
    // Exact after normalising, or one name starts with the other (handles "Pvt Ltd" suffixes)
    return pn === normProvider || pn.startsWith(normProvider) || normProvider.startsWith(pn);
  });

  // Sort by ID desc so most recent record wins when duplicates exist
  const sortedProviderRates = [...providerRates].sort((a, b) => (b.id || 0) - (a.id || 0));

  // Extract numeric weight from a slab string for sorting rows logically
  const slabSortWeight = (slab) => {
    const s = (slab || '').toLowerCase().replace(/\s+/g, '');
    const nums = s.match(/[\d.]+/g);
    if (!nums) return 9999;
    const first = parseFloat(nums[0]);
    const grams = s.includes('kg') ? first * 1000 : first;
    if (s.startsWith('<') || s.startsWith('upto')) return grams - 0.5;
    if (s.startsWith('>') || s.includes('above') || s.endsWith('+')) return grams + 0.5;
    return grams;
  };

  // Use zone if available, fall back to service_type (e.g. DTDC has service_type instead of zone)
  const getColKey = (r) => ((r.zone || '').trim() || (r.service_type || '').trim());
  const providerUsesServiceType = sortedProviderRates.length > 0 &&
    sortedProviderRates.every(r => !(r.zone || '').trim());

  // Dynamic columns — whichever field the provider uses for differentiation
  const providerZones = [...new Set(sortedProviderRates.map(getColKey).filter(Boolean))].sort();

  // Dynamic rows: every unique weight slab, sorted by actual weight
  const allProviderSlabs = [...new Set(sortedProviderRates.map(r => (r.weight_slab || '').trim()).filter(Boolean))]
    .sort((a, b) => slabSortWeight(a) - slabSortWeight(b));

  const displaySlabs = searchQuery
    ? allProviderSlabs.filter(s => s.toLowerCase().includes(searchQuery.toLowerCase()))
    : allProviderSlabs;

  return (
    <Box sx={{ pb: 6, minHeight: '80vh', bgcolor: '#f8fafc', px: { xs: 2, md: 4 }, pt: 3 }}>
      <PageHeader
        title="Logistics Pricing Board"
        breadcrumbs={[{ label: 'Pricing Overview' }]}
      />

      <Box sx={{ display: 'flex', flexDirection: 'column', gap: 4, mt: 3, maxWidth: 1200, mx: 'auto' }}>
        
        {/* Modern Premium Control Panel */}
        <Card 
          sx={{ 
            p: 3, 
            borderRadius: 4, 
            bgcolor: '#ffffff', 
            boxShadow: '0 20px 40px -10px rgba(0,0,0,0.03)',
            border: '1px solid',
            borderColor: 'grey.100',
            display: 'flex', 
            flexDirection: { xs: 'column', md: 'row' },
            alignItems: 'center', 
            justifyContent: 'space-between',
            gap: 3
          }}
        >
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 2, width: { xs: '100%', md: 'auto' } }}>
            <Box sx={{ width: 48, height: 48, borderRadius: 3, bgcolor: 'primary.lighter', color: 'primary.main', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <LocalShippingOutlinedIcon />
            </Box>
            <Box>
              <Typography variant="caption" sx={{ fontWeight: 700, color: 'text.secondary', letterSpacing: 0.8, textTransform: 'uppercase' }}>
                Active Logistics Provider
              </Typography>
              <FormControl sx={{ mt: 0.5, minWidth: 260, display: 'block' }}>
                <Select
                  value={selectedProvider || ''}
                  onChange={(e) => setSelectedProvider(e.target.value)}
                  displayEmpty
                  IconComponent={StorefrontOutlinedIcon}
                  input={<OutlinedInput sx={{ 
                    borderRadius: 3, 
                    fontWeight: 700, 
                    fontSize: '1.1rem',
                    bgcolor: alpha('#e2e8f0', 0.4),
                    '& fieldset': { border: 'none' },
                    '&:hover': { bgcolor: alpha('#e2e8f0', 0.6) },
                    '&.Mui-focused': { bgcolor: '#fff', '& fieldset': { border: '2px solid', borderColor: 'primary.main' } }
                  }} />}
                  MenuProps={{ PaperProps: { sx: { borderRadius: 3, mt: 1, boxShadow: '0 12px 24px rgba(0,0,0,0.1)' } } }}
                >
                  {companies.length === 0 ? (
                    <MenuItem value="" disabled>Loading Providers...</MenuItem>
                  ) : (
                    companies.map(c => (
                      <MenuItem key={c} value={c} sx={{ fontWeight: 600, py: 1.5, borderRadius: 1, mx: 1 }}>{c}</MenuItem>
                    ))
                  )}
                </Select>
              </FormControl>
            </Box>
          </Box>

          <Box sx={{ display: 'flex', gap: 2, alignItems: 'center' }}>
            <TextField
              placeholder="Search weight slabs..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              InputProps={{
                startAdornment: <InputAdornment position="start"><SearchIcon color="primary" /></InputAdornment>,
                sx: { 
                  borderRadius: 50, 
                  bgcolor: alpha('#e2e8f0', 0.3),
                  '& fieldset': { border: 'none' },
                  '&:hover': { bgcolor: alpha('#e2e8f0', 0.5) },
                  '&.Mui-focused': { bgcolor: '#fff', '& fieldset': { border: '2px solid', borderColor: 'primary.main' } }
                }
              }}
            />
            <Button variant="contained" startIcon={<AddIcon />} onClick={() => { setEditingRecord({ company: selectedProvider, weight_slab: '', zone: '', rate: '' }); setIsCellEdit(false); setFormOpen(true); }} sx={{ bgcolor: '#c01227', '&:hover': { bgcolor: '#a00f20' }, borderRadius: 2, py: 1.2, fontWeight: 700, whiteSpace: 'nowrap' }}>
              Add Rate
            </Button>
            <Button 
              variant={isEditMode ? "contained" : "outlined"} 
              startIcon={<EditOutlinedIcon />} 
              onClick={() => setIsEditMode(!isEditMode)} 
              sx={{ 
                borderRadius: 2, py: 1.2, fontWeight: 700, whiteSpace: 'nowrap',
                color: isEditMode ? 'white' : 'grey.700',
                borderColor: isEditMode ? 'transparent' : 'grey.300',
                bgcolor: isEditMode ? 'grey.800' : 'transparent',
                '&:hover': { bgcolor: isEditMode ? 'grey.900' : alpha('#000', 0.05), borderColor: isEditMode ? 'transparent' : 'grey.400' }
              }}
            >
              {isEditMode ? 'Done' : 'Edit'}
            </Button>
          </Box>
        </Card>

        {/* Minimalist Collapsible Provider Profile Widget */}
        {selectedProvider && providerSurveys.length > 0 && (
          <Card 
            elevation={0}
            sx={{ 
              borderRadius: 4, 
              border: '1px solid', 
              borderColor: locationsOpen ? '#c01227' : 'grey.200',
              bgcolor: 'white',
              transition: 'border-color 0.3s ease, box-shadow 0.3s ease',
              '&:hover': {
                borderColor: '#c01227',
                boxShadow: '0 8px 30px rgba(192, 18, 39, 0.08)',
              }
            }}
          >
            <Stack 
              direction={{ xs: 'column', md: 'row' }} spacing={4} sx={{ p: { xs: 3, md: 3.5 }, cursor: 'pointer', userSelect: 'none' }} 
              alignItems={{ xs: 'flex-start', md: 'center' }} justifyContent="space-between"
              onClick={() => setLocationsOpen(!locationsOpen)}
            >
              
              {/* Avatar & Title */}
              <Stack direction="row" spacing={3} alignItems="center" sx={{ minWidth: 260 }}>
                <Avatar sx={{ width: 68, height: 68, bgcolor: alpha('#c01227', 0.08), color: '#c01227', fontWeight: 800, fontSize: '1.8rem', borderRadius: 3 }}>
                  {(selectedProvider || 'A')[0].toUpperCase()}
                </Avatar>
                <Box>
                  <Typography variant="overline" sx={{ color: 'grey.500', fontWeight: 700, letterSpacing: 1.2 }}>LOGISTICS PARTNER</Typography>
                  <Typography variant="h5" sx={{ fontWeight: 800, color: 'grey.900', lineHeight: 1.1, mt: 0.25 }}>{selectedProvider}</Typography>
                  <Typography variant="body2" sx={{ color: 'grey.600', mt: 1, fontWeight: 500, display: 'flex', alignItems: 'center' }}>
                    <PlaceOutlinedIcon sx={{ fontSize: 16, mr: 0.5, color: '#c01227' }} />
                    {providerSurveys.length} Registered Location{providerSurveys.length !== 1 && 's'}
                  </Typography>
                </Box>
              </Stack>
              
              {/* Badges & Action */}
              <Stack direction="row" spacing={3} alignItems="center">
                <Stack direction="row" spacing={1} sx={{ display: { xs: 'none', md: 'flex' } }}>
                  <Chip size="small" label="First Mile" sx={{ bgcolor: alpha('#c01227', 0.08), color: '#c01227', fontWeight: 700, borderRadius: 1.5 }} />
                  <Chip size="small" label="Mid Mile" sx={{ bgcolor: alpha('#c01227', 0.08), color: '#c01227', fontWeight: 700, borderRadius: 1.5 }} />
                  <Chip size="small" label="Last Mile" sx={{ bgcolor: alpha('#c01227', 0.08), color: '#c01227', fontWeight: 700, borderRadius: 1.5 }} />
                </Stack>
                <Button 
                  onClick={(e) => { e.stopPropagation(); setLocationsOpen(!locationsOpen); }} 
                  sx={{ 
                    borderRadius: 2, py: 1, px: 3, fontWeight: 700,
                    color: locationsOpen ? '#c01227' : 'grey.700', 
                    bgcolor: locationsOpen ? alpha('#c01227', 0.1) : 'grey.100',
                    '&:hover': { bgcolor: alpha('#c01227', 0.15), color: '#c01227' } 
                  }}
                  endIcon={locationsOpen ? <KeyboardArrowUpIcon /> : <KeyboardArrowDownIcon />}
                >
                  {locationsOpen ? 'Hide Coverage' : 'View Coverage Map'}
                </Button>
              </Stack>

            </Stack>

            <Collapse in={locationsOpen} timeout="auto" unmountOnExit>
              <Box sx={{ p: 3, pt: 0, borderTop: '1px dashed', borderColor: 'grey.200', bgcolor: 'grey.50', borderBottomLeftRadius: 16, borderBottomRightRadius: 16 }}>
                <Box sx={{ display: 'flex', alignItems: 'center', mb: 2, mt: 3 }}>
                  <PlaceOutlinedIcon sx={{ color: '#c01227', fontSize: 20, mr: 1 }} />
                  <Typography variant="caption" sx={{ color: 'grey.600', fontWeight: 700, letterSpacing: 1 }}>ALL SERVICED AREAS:</Typography>
                </Box>
                <Box sx={{ display: 'flex', gap: 1.5, flexWrap: 'wrap' }}>
                 {providerSurveys.map((s, idx) => (
                    <Chip
                      key={s.id ?? idx}
                      label={s.area || s.address} 
                      sx={{ 
                        borderRadius: 2, fontWeight: 600, px: 1, py: 2.5,
                        bgcolor: 'white', color: 'grey.800', border: '1px solid', borderColor: 'grey.300', boxShadow: '0 2px 8px rgba(0,0,0,0.02)',
                        '&:hover': { borderColor: '#c01227', color: '#c01227', bgcolor: alpha('#c01227', 0.05), boxShadow: '0 4px 12px rgba(192,18,39,0.08)' },
                        transition: 'border-color 0.2s ease, color 0.2s ease, background-color 0.2s ease, box-shadow 0.2s ease'
                      }} 
                    />
                 ))}
                </Box>
              </Box>
            </Collapse>
          </Card>
        )}

        {/* Pricing Data Grid */}
        <Card 
          sx={{ 
            borderRadius: 4, 
            boxShadow: '0 24px 48px -12px rgba(0,0,0,0.05)', 
            border: '1px solid', 
            borderColor: 'grey.200',
            overflow: 'hidden',
            bgcolor: '#fff'
          }}
        >
          {loading ? (
            <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', py: 10 }}>
              <CircularProgress size={48} thickness={4} sx={{ color: 'primary.light' }} />
            </Box>
          ) : (
            <TableContainer>
              <Table sx={{ minWidth: 700 }}>
                <TableHead>
                  <TableRow sx={{ bgcolor: alpha('#f8fafc', 0.8) }}>
                    <TableCell sx={{ py: 2, px: 4, fontWeight: 700, color: 'grey.500', fontSize: '0.75rem', letterSpacing: 1.2, textTransform: 'uppercase', borderBottom: '2px solid', borderColor: 'grey.100' }}>Weight Slab</TableCell>
                    {providerZones.map(zone => (
                      <TableCell key={zone} align="center" sx={{ py: 2, fontWeight: 700, color: 'grey.500', fontSize: '0.75rem', letterSpacing: 1.2, textTransform: 'uppercase', borderBottom: '2px solid', borderColor: 'grey.100' }}>
                        {zone}
                      </TableCell>
                    ))}
                  </TableRow>
                </TableHead>
                <TableBody>
                  {providerZones.length === 0 ? (
                    <TableRow>
                      <TableCell colSpan={2} align="center" sx={{ py: 8 }}>
                        <Typography variant="body1" color="text.secondary" sx={{ fontWeight: 500 }}>
                          No pricing data for this provider yet.
                        </Typography>
                      </TableCell>
                    </TableRow>
                  ) : displaySlabs.length === 0 ? (
                    <TableRow>
                      <TableCell colSpan={providerZones.length + 1} align="center" sx={{ py: 8 }}>
                        <Typography variant="body1" color="text.secondary" sx={{ fontWeight: 500 }}>
                          No weight slabs match your search.
                        </Typography>
                      </TableCell>
                    </TableRow>
                  ) : (
                    displaySlabs.map((slab) => (
                      <TableRow
                        key={slab}
                        sx={{
                          transition: 'background-color 0.15s',
                          '&:hover': { bgcolor: alpha('#f1f5f9', 0.5) },
                          '&:last-child td': { borderBottom: 0 }
                        }}
                      >
                        <TableCell sx={{ px: 4, py: 2, fontWeight: 600, color: 'grey.800', fontSize: '0.9rem', borderBottom: '1px solid', borderColor: 'grey.100' }}>
                          {slab}
                        </TableCell>
                        {providerZones.map(zone => {
                          // Exact match — use getColKey so DTDC service_type columns work too
                          const match = sortedProviderRates.find(r => (r.weight_slab || '').trim() === slab && getColKey(r) === zone);
                          const hasRate = !!match;
                          const rateStr = match ? `₹${match.rate}` : '—';

                          let tooltipText = '';
                          if (match && match.updated_by) {
                            const updater = users.find(u => u.id === match.updated_by);
                            tooltipText = `Last updated by: ${updater ? updater.first_name : 'ID ' + match.updated_by}`;
                          }

                          const openCellEdit = () => {
                            setEditingRecord({
                              id: match ? match.id : undefined,
                              company: selectedProvider,
                              weight_slab: slab,
                              zone: providerUsesServiceType ? '' : zone,
                              service_type: providerUsesServiceType ? zone : (match?.service_type || ''),
                              rate: match ? String(match.rate) : ''
                            });
                            setIsCellEdit(true);
                            setFormOpen(true);
                          };

                          return (
                            <TableCell
                              key={zone}
                              align="center"
                              sx={{
                                py: 1.5,
                                borderBottom: '1px solid',
                                borderColor: 'grey.100',
                                cursor: isEditMode ? 'pointer' : 'default',
                                transition: 'background 0.15s',
                                '&:hover': isEditMode ? { bgcolor: alpha('#c01227', 0.04) } : {},
                              }}
                              onClick={isEditMode ? openCellEdit : undefined}
                            >
                              <Tooltip title={isEditMode ? (hasRate ? 'Click to edit rate' : 'Click to add rate') : tooltipText} placement="top" arrow disableHoverListener={!isEditMode && !tooltipText}>
                                <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 1 }}>
                                  <Typography
                                    sx={{
                                      display: 'inline-block',
                                      fontWeight: hasRate ? 700 : 400,
                                      color: hasRate ? 'success.dark' : (isEditMode ? alpha('#c01227', 0.4) : 'grey.300'),
                                      fontSize: hasRate ? '0.95rem' : '0.85rem',
                                      bgcolor: hasRate ? alpha('#10b981', 0.08) : 'transparent',
                                      px: hasRate ? 1.5 : 0,
                                      py: hasRate ? 0.5 : 0,
                                      borderRadius: 2,
                                    }}
                                  >
                                    {rateStr}
                                  </Typography>
                                  {isEditMode && (
                                    hasRate
                                      ? <EditOutlinedIcon sx={{ fontSize: 13, color: 'grey.400' }} />
                                      : <AddCircleOutlineIcon sx={{ fontSize: 13, color: alpha('#c01227', 0.4) }} />
                                  )}
                                </Box>
                              </Tooltip>
                            </TableCell>
                          );
                        })}
                      </TableRow>
                    ))
                  )}
                </TableBody>
              </Table>
            </TableContainer>
          )}
        </Card>
      </Box>

      <PricingFormDialog
        open={formOpen}
        onClose={() => setFormOpen(false)}
        onSave={() => loadData()}
        initialData={editingRecord}
        isCell={isCellEdit}
        pricingList={pricingList}
        providerColumns={providerZones}
        providerUsesServiceType={providerUsesServiceType}
      />
    </Box>
  );
}
