import {
	Table,
	TableBody,
	TableCell,
	TableContainer,
	TableHead,
	TableRow,
	Paper,
	IconButton,
	Chip,
	Typography,
	Box,
	Switch,
} from '@mui/material';
import EditIcon from '@mui/icons-material/Edit';
import DeleteIcon from '@mui/icons-material/Delete';
import { RULE_TYPES } from '../redux/features/shippingRules/shippingRulesSlice';

const APPLY_TO_LABELS = {
	cart: 'Cart',
	shipment: 'Shipment',
	product_tag: 'Product tag',
	ltl: 'LTL providers',
	parcel: 'Parcel providers',
	shipmentTypeBoth: 'LTL and parcel providers',
	cheapestParcelOrLTL: 'Cheapest LTL or parcel',
};

const ShippingRulesTable = ({ rules, onEdit, onDelete, onToggleStatus, isLoading, togglingUuid }) => {
	if (isLoading) {
		return (
			<Box sx={{ p: 3, textAlign: 'center' }}>
				<Typography>Loading shipping rules...</Typography>
			</Box>
		);
	}

	if (!rules || rules.length === 0) {
		return (
			<Box sx={{ p: 3, textAlign: 'center' }}>
				<Typography color='textSecondary'>
					No shipping rules defined yet. Click "Add Rule" to create one.
				</Typography>
			</Box>
		);
	}

	const ruleTypeLabel = value => RULE_TYPES.find(type => type.value === value)?.label || value;

	return (
		<TableContainer component={Paper} sx={{ mt: 3 }}>
			<Table>
				<TableHead>
					<TableRow sx={{ backgroundColor: '#f5f5f5' }}>
						<TableCell>
							<strong>Rule Name</strong>
						</TableCell>
						<TableCell>
							<strong>Type</strong>
						</TableCell>
						<TableCell>
							<strong>Applies To</strong>
						</TableCell>
						<TableCell>
							<strong>Available</strong>
						</TableCell>
						<TableCell align='center'>
							<strong>Action</strong>
						</TableCell>
					</TableRow>
				</TableHead>
				<TableBody>
					{rules.map(rule => (
						<TableRow key={rule.uuid} hover>
							<TableCell>{rule.rule_name}</TableCell>
							<TableCell>
								<Chip label={ruleTypeLabel(rule.rule_type)} size='small' />
							</TableCell>
							<TableCell>{APPLY_TO_LABELS[rule.apply_to] || '—'}</TableCell>
							<TableCell>
								<Switch
									checked={Boolean(Number(rule.is_available))}
									onChange={() => onToggleStatus(rule)}
									disabled={togglingUuid === rule.uuid}
									size='small'
								/>
							</TableCell>
							<TableCell align='center'>
								<IconButton onClick={() => onEdit(rule)} size='small' title='Edit'>
									<EditIcon fontSize='small' />
								</IconButton>
								<IconButton
									onClick={() => onDelete(rule)}
									size='small'
									color='error'
									title='Delete'>
									<DeleteIcon fontSize='small' />
								</IconButton>
							</TableCell>
						</TableRow>
					))}
				</TableBody>
			</Table>
		</TableContainer>
	);
};

export default ShippingRulesTable;
