import { FunctionComponent } from 'react';
import { Box, ButtonBase, Typography } from '@mui/material';
import AppIcon from '../common/AppIcon';

/**
 * Service-category `iconKey`s we render with a dedicated icon. Any other key (or a missing one from
 * real data whose icons we don't control) falls back to the generic `category` icon, so the tile is
 * robust regardless of what the backend seeds — never an AppIcon "not found" warning.
 */
const KNOWN_CATEGORY_ICONS = new Set(['elderly', 'post_surgery', 'infant', 'chronic', 'companionship']);

function resolveIcon(iconKey?: string | null): string {
  return iconKey && KNOWN_CATEGORY_ICONS.has(iconKey) ? iconKey : 'category';
}

export interface CategoryTileProps {
  /** Category name, already localised by the caller (`nameFa`/`nameEn` picked by locale). */
  label: string;
  /** Optional backend icon hint; unknown/missing keys fall back to a generic category icon. */
  iconKey?: string | null;
  /** Tapping the tile carries the category into the (future f6) search flow, or selects it in the builder. */
  onClick?: () => void;
  /** Selected state (the nurse builder's category step); the Home grid leaves it unset. */
  selected?: boolean;
}

/**
 * A tappable tile for one service category — the customer Home grid (data-driven, one per
 * `service_category`) and the nurse builder's category step (with `selected`). Icon in a soft-teal
 * disc over the localised label; the whole tile is a button so it's keyboard- and screen-reader-
 * accessible. RTL-safe (no directional hard-coding).
 * @component CategoryTile
 */
const CategoryTile: FunctionComponent<CategoryTileProps> = ({ label, iconKey, onClick, selected = false }) => (
  <ButtonBase
    focusRipple
    onClick={onClick}
    aria-pressed={selected}
    data-selected={selected}
    data-category-icon={resolveIcon(iconKey)}
    sx={{
      width: '100%',
      height: '100%',
      minHeight: 116,
      p: 2,
      borderRadius: 2,
      border: '1px solid',
      borderColor: selected ? 'var(--bal-primary)' : 'divider',
      bgcolor: selected ? 'var(--bal-primary-soft)' : 'background.paper',
      display: 'flex',
      flexDirection: 'column',
      alignItems: 'center',
      justifyContent: 'center',
      gap: 1,
      textAlign: 'center',
      transition: 'border-color 120ms ease, transform 120ms ease',
      '&:hover': { borderColor: 'var(--bal-primary)' },
      '&:active': { transform: 'scale(0.98)' },
    }}
  >
    <Box
      sx={{
        width: 48,
        height: 48,
        borderRadius: '50%',
        bgcolor: 'var(--bal-primary-soft)',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
      }}
    >
      <AppIcon icon={resolveIcon(iconKey)} size={28} color="var(--bal-primary)" />
    </Box>
    <Typography variant="subtitle2" sx={{ fontWeight: 700, lineHeight: 1.3 }}>
      {label}
    </Typography>
  </ButtonBase>
);

export default CategoryTile;
