import React from 'react';
import Box from '@mui/material/Box';
import type { SxProps, Theme } from '@mui/material/styles';

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

/** Props for the FA MapPin atom */
export interface MapPinProps {
  /** Provider or venue name (required — shown as line 1) */
  name: string;
  /** Starting package price in dollars — shown as "From $X" on line 2 */
  price?: number;
  /** Custom price label (e.g. "POA") — overrides formatted price */
  priceLabel?: string;
  /** Whether this provider/venue is verified (brand palette vs neutral palette) */
  verified?: boolean;
  /** Click handler */
  onClick?: (e: React.MouseEvent) => void;
  /** MUI sx prop for the root element */
  sx?: SxProps<Theme>;
}

// ─── Constants ──────────────────────────────────────────────────────────────

const PIN_PX = 'var(--fa-map-pin-padding-x)';
const PIN_RADIUS = 'var(--fa-map-pin-border-radius)';
const NUB_SIZE = 'var(--fa-map-pin-nub-size)';
const MAX_WIDTH = 180;

// ─── Colour sets ────────────────────────────────────────────────────────────

const colours = {
  verified: {
    bg: 'var(--fa-color-brand-700)',
    name: 'var(--fa-color-white)',
    price: 'var(--fa-color-brand-200)',
    nub: 'var(--fa-color-brand-700)',
    border: 'var(--fa-color-brand-700)',
  },
  unverified: {
    bg: 'var(--fa-color-neutral-100)',
    name: 'var(--fa-color-neutral-800)',
    price: 'var(--fa-color-neutral-500)',
    nub: 'var(--fa-color-neutral-100)',
    border: 'var(--fa-color-neutral-300)',
  },
} as const;

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

/**
 * Map marker pin for the FA design system.
 *
 * Two-line label marker showing provider name and starting package
 * price. Renders as a rounded pill with a downward nub pointing to
 * the exact map location.
 *
 * - **Line 1**: Provider name (bold, truncated)
 * - **Line 2**: "From $X" (smaller, secondary colour)
 *
 * Visual distinction:
 * - **Verified** providers: warm brand palette (dark copper bg, white text)
 * - **Unverified** providers: neutral grey palette
 *
 * Designed for use as custom HTML markers in Google Maps. Pure CSS — no
 * canvas, no SVG dependency. Selection/popup behaviour is handled at the
 * organism level (ProviderMap swaps pin → popup on click).
 *
 * Usage:
 * ```tsx
 * <MapPin name="H.Parsons" price={900} verified onClick={...} />
 * <MapPin name="Smith & Sons" price={1200} />
 * <MapPin name="Botanical" priceLabel="POA" verified />
 * ```
 */
export const MapPin = React.forwardRef<HTMLDivElement, MapPinProps>(
  ({ name, price, priceLabel, verified = false, onClick, sx }, ref) => {
    const palette = verified ? colours.verified : colours.unverified;
    const hasPrice = price != null || priceLabel != null;

    const priceText =
      priceLabel ?? (price != null ? `From $${price.toLocaleString('en-AU')}` : undefined);

    const handleKeyDown = (e: React.KeyboardEvent) => {
      if ((e.key === 'Enter' || e.key === ' ') && onClick) {
        e.preventDefault();
        onClick(e as unknown as React.MouseEvent);
      }
    };

    return (
      <Box
        ref={ref}
        role="button"
        tabIndex={0}
        aria-label={`${name}${hasPrice ? `, packages from ${priceLabel ?? `$${price?.toLocaleString('en-AU')}`}` : ''}${verified ? ', verified' : ''}`}
        onClick={onClick}
        onKeyDown={handleKeyDown}
        sx={[
          {
            display: 'inline-flex',
            flexDirection: 'column',
            alignItems: 'center',
            cursor: 'pointer',
            transition: 'transform 150ms ease-in-out',
            // Fade in on mount — matches the popup's exit timing so the pin
            // reappears smoothly when a popup closes.
            '@keyframes mapPinIn': {
              from: { opacity: 0 },
              to: { opacity: 1 },
            },
            animation: 'mapPinIn 180ms ease-out',
            '&:hover': {
              transform: 'scale(1.08)',
            },
            '&:focus-visible': {
              outline: 'none',
              '& > .MapPin-label': {
                outline: '2px solid var(--fa-color-interactive-focus)',
                outlineOffset: '2px',
              },
            },
          },
          ...(Array.isArray(sx) ? sx : [sx]),
        ]}
      >
        {/* Label pill */}
        <Box
          className="MapPin-label"
          sx={{
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            maxWidth: MAX_WIDTH,
            py: 0.5,
            px: PIN_PX,
            borderRadius: PIN_RADIUS,
            backgroundColor: palette.bg,
            border: '1px solid',
            borderColor: palette.border,
            boxShadow: 'var(--fa-shadow-sm)',
          }}
        >
          {/* Name */}
          <Box
            component="span"
            sx={{
              fontSize: 12,
              fontWeight: 700,
              fontFamily: 'var(--fa-font-family-body)',
              lineHeight: 1.3,
              color: palette.name,
              whiteSpace: 'nowrap',
              overflow: 'hidden',
              textOverflow: 'ellipsis',
              maxWidth: '100%',
            }}
          >
            {name}
          </Box>

          {/* Price line */}
          {hasPrice && (
            <Box
              component="span"
              sx={{
                fontSize: 11,
                fontWeight: 600,
                fontFamily: 'var(--fa-font-family-body)',
                lineHeight: 1.2,
                color: palette.price,
                whiteSpace: 'nowrap',
              }}
            >
              {priceText}
            </Box>
          )}
        </Box>

        {/* Nub — downward pointer. Two SVG paths:
              • fill is an extended pentagon that overhangs 3 units *into* the
                pill's bg so sub-pixel scaling artifacts (hover transform) can't
                expose the pill's bottom border through the seam;
              • stroke is a separate open path on the two slanted sides only,
                so the nub outline is continuous with the pill's border.
            overflow: visible lets the fill render above the viewBox. */}
        <svg
          aria-hidden
          viewBox="0 0 16 8"
          style={{
            display: 'block',
            width: `calc(2 * ${NUB_SIZE})`,
            height: NUB_SIZE,
            marginTop: '-1px',
            overflow: 'visible',
          }}
        >
          <path d="M 0 -3 L 16 -3 L 16 0 L 8 8 L 0 0 Z" fill={palette.bg} />
          <path
            d="M 0 0 L 8 8 L 16 0"
            fill="none"
            stroke={palette.border}
            strokeWidth={1}
            strokeLinejoin="round"
          />
        </svg>
      </Box>
    );
  },
);

MapPin.displayName = 'MapPin';
export default MapPin;
