import React from 'react';
import Box from '@mui/material/Box';
import Tooltip from '@mui/material/Tooltip';
import type { SxProps, Theme } from '@mui/material/styles';
import LocationOnOutlinedIcon from '@mui/icons-material/LocationOnOutlined';
import StarRoundedIcon from '@mui/icons-material/StarRounded';
import PeopleOutlinedIcon from '@mui/icons-material/PeopleOutlined';
import VerifiedOutlinedIcon from '@mui/icons-material/VerifiedOutlined';
import { Card } from '../../atoms/Card';
import { Typography } from '../../atoms/Typography';
import { Badge } from '../../atoms/Badge';
import type { BadgeProps } from '../../atoms/Badge/Badge';

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

/** A badge to render inside the MiniCard content area */
export interface MiniCardBadge {
  /** Label text */
  label: string;
  /** Badge colour intent */
  color?: BadgeProps['color'];
  /** Badge variant */
  variant?: BadgeProps['variant'];
  /** Optional leading icon */
  icon?: React.ReactNode;
}

/** Props for the FA MiniCard molecule */
export interface MiniCardProps {
  /** Card title — provider name, venue name, package name, etc. */
  title: string;
  /** Hero image URL */
  imageUrl: string;
  /** Alt text for the image — defaults to title */
  imageAlt?: string;
  /** Whether this provider/venue is verified — shows icon badge in image */
  verified?: boolean;
  /** Price in dollars — shown as "From $X" */
  price?: number;
  /** Custom price label (e.g. "POA", "Included") — overrides formatted price */
  priceLabel?: string;
  /** Location text (suburb, city) */
  location?: string;
  /** Average rating (e.g. 4.8) */
  rating?: number;
  /** Venue capacity (e.g. 120) */
  capacity?: number;
  /** Badge items rendered after the price row */
  badges?: MiniCardBadge[];
  /** Chip labels rendered as small soft badges (after badges) */
  chips?: string[];
  /** Whether this card is currently selected */
  selected?: boolean;
  /** Click handler — entire card is clickable */
  onClick?: () => void;
  /** MUI sx prop for style overrides */
  sx?: SxProps<Theme>;
}

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

const IMAGE_HEIGHT = 'var(--fa-mini-card-image-height)';
const CONTENT_PADDING = 'var(--fa-mini-card-content-padding)';
const CONTENT_GAP = 'var(--fa-mini-card-content-gap)';

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

/**
 * Compact vertical card for the FA design system.
 *
 * A smaller, flexible card for displaying providers, venues, or packages
 * in grids, recommendation rows, and map popups. Shows an image with
 * a title and optional meta, price, badges, and chips.
 *
 * Content hierarchy: **title → meta → price → chips/badges**.
 *
 * Verified providers show a small icon-only badge floating in the
 * image (top-right). Truncated titles show a tooltip on hover with
 * the full text.
 *
 * Composes: Card + Typography + Badge + Tooltip.
 *
 * Usage:
 * ```tsx
 * <MiniCard
 *   title="H.Parsons Funeral Directors"
 *   imageUrl="/images/parsons.jpg"
 *   verified
 *   price={900}
 *   location="Wollongong"
 *   rating={4.8}
 *   onClick={() => navigate('/providers/parsons')}
 * />
 * ```
 */
export const MiniCard = React.forwardRef<HTMLDivElement, MiniCardProps>(
  (
    {
      title,
      imageUrl,
      imageAlt,
      verified = false,
      price,
      priceLabel,
      location,
      rating,
      capacity,
      badges,
      chips,
      selected = false,
      onClick,
      sx,
    },
    ref,
  ) => {
    const hasMeta = location != null || rating != null || capacity != null;
    const hasPrice = price != null || priceLabel != null;

    // Detect title truncation for tooltip
    const titleRef = React.useRef<HTMLElement>(null);
    const [isTruncated, setIsTruncated] = React.useState(false);

    React.useEffect(() => {
      const el = titleRef.current;
      if (el) {
        setIsTruncated(el.scrollHeight > el.clientHeight + 1);
      }
    }, [title]);

    return (
      <Card
        ref={ref}
        interactive={!!onClick}
        selected={selected}
        padding="none"
        onClick={onClick}
        sx={[
          {
            overflow: 'hidden',
            '&:hover': {
              backgroundColor: 'background.paper',
            },
          },
          ...(Array.isArray(sx) ? sx : [sx]),
        ]}
      >
        {/* ── Image ── */}
        <Box
          role="img"
          aria-label={imageAlt ?? title}
          sx={{
            position: 'relative',
            height: IMAGE_HEIGHT,
            backgroundImage: `url(${imageUrl})`,
            backgroundSize: 'cover',
            backgroundPosition: 'center',
            backgroundColor: 'var(--fa-color-neutral-100)',
          }}
        >
          {/* Verified icon badge — floating top-right */}
          {verified && (
            <Tooltip title="Verified provider" arrow placement="top">
              <Box
                sx={{
                  position: 'absolute',
                  top: 8,
                  right: 8,
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  width: 28,
                  height: 28,
                  borderRadius: '50%',
                  backgroundColor: 'var(--fa-color-brand-600)',
                  color: 'var(--fa-color-white)',
                  boxShadow: 'var(--fa-shadow-sm)',
                }}
              >
                <VerifiedOutlinedIcon sx={{ fontSize: 16 }} />
              </Box>
            </Tooltip>
          )}
        </Box>

        {/* ── Content ── */}
        <Box
          sx={{
            display: 'flex',
            flexDirection: 'column',
            gap: CONTENT_GAP,
            p: CONTENT_PADDING,
          }}
        >
          {/* 1. Title — with tooltip when truncated */}
          <Tooltip
            title={isTruncated ? title : ''}
            arrow
            placement="top"
            enterDelay={300}
            disableHoverListener={!isTruncated}
          >
            <Typography ref={titleRef} variant="h6" maxLines={2}>
              {title}
            </Typography>
          </Tooltip>

          {/* 2. Meta row: location / rating / capacity */}
          {hasMeta && (
            <Box
              sx={{
                display: 'flex',
                alignItems: 'center',
                gap: 1.5,
                flexWrap: 'wrap',
              }}
            >
              {location && (
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
                  <LocationOnOutlinedIcon
                    sx={{ fontSize: 14, color: 'text.secondary' }}
                    aria-hidden
                  />
                  <Typography variant="caption" color="text.secondary">
                    {location}
                  </Typography>
                </Box>
              )}

              {rating != null && (
                <Box
                  sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}
                  aria-label={`Rated ${rating} out of 5`}
                >
                  <StarRoundedIcon sx={{ fontSize: 14, color: 'warning.main' }} aria-hidden />
                  <Typography variant="caption" color="text.secondary">
                    {rating}
                  </Typography>
                </Box>
              )}

              {capacity != null && (
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
                  <PeopleOutlinedIcon sx={{ fontSize: 14, color: 'text.secondary' }} aria-hidden />
                  <Typography variant="caption" color="text.secondary">
                    {capacity} guests
                  </Typography>
                </Box>
              )}
            </Box>
          )}

          {/* 3. Price */}
          {hasPrice && (
            <Box sx={{ display: 'flex', alignItems: 'baseline', gap: 0.5 }}>
              {priceLabel ? (
                <Typography variant="body2" color="primary" sx={{ fontStyle: 'italic' }}>
                  {priceLabel}
                </Typography>
              ) : (
                <>
                  <Typography variant="caption" color="text.secondary">
                    From
                  </Typography>
                  <Typography
                    variant="body2"
                    component="span"
                    color="primary"
                    sx={{ fontWeight: 600 }}
                  >
                    ${price!.toLocaleString('en-AU')}
                  </Typography>
                </>
              )}
            </Box>
          )}

          {/* 4. Badges */}
          {badges && badges.length > 0 && (
            <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.5 }}>
              {badges.map((badge) => (
                <Badge
                  key={badge.label}
                  color={badge.color}
                  variant={badge.variant}
                  size="small"
                  icon={badge.icon}
                >
                  {badge.label}
                </Badge>
              ))}
            </Box>
          )}

          {/* 5. Chips */}
          {chips && chips.length > 0 && (
            <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.5 }}>
              {chips.map((chip) => (
                <Badge key={chip} color="default" variant="soft" size="small">
                  {chip}
                </Badge>
              ))}
            </Box>
          )}
        </Box>
      </Card>
    );
  },
);

MiniCard.displayName = 'MiniCard';
export default MiniCard;
