import React from 'react';
import Box from '@mui/material/Box';
import type { SxProps, Theme } from '@mui/material/styles';
import { Card } from '../../atoms/Card';
import { Typography } from '../../atoms/Typography';
import { Link } from '../../atoms/Link';

// ─── Types ───────────────────────────────────────────────────────────────────

/** Props for the FA ServiceOption molecule */
export interface ServiceOptionProps {
  /** Option name/heading */
  name: string;
  /** Description text explaining the option */
  description?: string;
  /** Price in dollars — shown to the right of the heading */
  price?: number;
  /** Whether this option is currently selected */
  selected?: boolean;
  /** Whether this option is disabled/unavailable */
  disabled?: boolean;
  /** Click handler — toggles selection */
  onClick?: () => void;
  /** Max visible lines for description before "View more" toggle. Omit for no limit. */
  maxDescriptionLines?: number;
  /** MUI sx prop for style overrides */
  sx?: SxProps<Theme>;
}

// ─── Component ───────────────────────────────────────────────────────────────

/**
 * Selectable service option for the FA design system.
 *
 * Used in the arrangement flow for choosing between mutually exclusive
 * options — coffin type, service style, transport method, etc.
 * Users click to select; only one option is active at a time within
 * a group (managed by parent).
 *
 * Composes Card (interactive, selected) + Typography. Maps to the
 * Figma "ListItemPurchaseOption" component (4 states × 2 viewports).
 *
 * For add-on toggles (multi-select with Switch), use a future
 * AddOnOption molecule or compose Card + Switch directly.
 *
 * Usage:
 * ```tsx
 * <ServiceOption
 *   name="Traditional Burial"
 *   description="Full service with chapel ceremony and graveside committal."
 *   price={4200}
 *   selected={selected === 'burial'}
 *   onClick={() => setSelected('burial')}
 * />
 * ```
 */
export const ServiceOption = React.forwardRef<HTMLDivElement, ServiceOptionProps>(
  (
    {
      name,
      description,
      price,
      selected = false,
      disabled = false,
      onClick,
      maxDescriptionLines,
      sx,
    },
    ref,
  ) => {
    const [expanded, setExpanded] = React.useState(false);
    const [isClamped, setIsClamped] = React.useState(false);
    const descRef = React.useRef<HTMLElement>(null);

    // Detect whether the description is actually truncated
    React.useEffect(() => {
      const el = descRef.current;
      if (el && maxDescriptionLines) {
        setIsClamped(el.scrollHeight > el.clientHeight + 1);
      }
    }, [description, maxDescriptionLines]);

    return (
      <Card
        ref={ref}
        interactive={!disabled}
        selected={selected}
        padding="none"
        onClick={disabled ? undefined : onClick}
        role="radio"
        aria-checked={selected}
        aria-disabled={disabled || undefined}
        sx={[
          {
            p: 'var(--fa-card-padding-compact)',
            ...(disabled && {
              opacity: 'var(--fa-opacity-disabled)',
              cursor: 'not-allowed',
              pointerEvents: 'none' as const,
            }),
          },
          ...(Array.isArray(sx) ? sx : [sx]),
        ]}
      >
        {/* Heading row: name + optional price */}
        <Box
          sx={{
            display: 'flex',
            alignItems: 'flex-start',
            justifyContent: 'space-between',
            gap: 2,
          }}
        >
          <Typography variant="h6" component="span">
            {name}
          </Typography>
          {price != null && (
            <Typography
              variant="labelLg"
              component="span"
              color="primary"
              sx={{ whiteSpace: 'nowrap' }}
            >
              ${price.toLocaleString('en-AU')}
            </Typography>
          )}
        </Box>

        {/* Description with optional line clamping */}
        {description && (
          <>
            <Typography
              ref={descRef}
              variant="body2"
              color="text.secondary"
              sx={{
                mt: 0.5,
                ...(maxDescriptionLines &&
                  !expanded && {
                    display: '-webkit-box',
                    WebkitLineClamp: maxDescriptionLines,
                    WebkitBoxOrient: 'vertical',
                    overflow: 'hidden',
                  }),
              }}
            >
              {description}
            </Typography>
            {maxDescriptionLines && isClamped && (
              <Link
                component="button"
                variant="caption"
                onClick={(e: React.MouseEvent) => {
                  e.stopPropagation();
                  setExpanded((prev) => !prev);
                }}
                sx={{ mt: 0.5, color: 'text.secondary', fontWeight: 400 }}
              >
                {expanded ? 'View less' : 'View more'}
              </Link>
            )}
          </>
        )}
      </Card>
    );
  },
);

ServiceOption.displayName = 'ServiceOption';
export default ServiceOption;
