import { FunctionComponent, memo } from 'react';
import { useLocale, useTranslations } from 'next-intl';
import { Avatar, Box, Paper, Skeleton, Stack, Typography } from '@mui/material';
import AppIcon from '../common/AppIcon';
import TrustBadge from '../TrustBadge';
import PriceDisplay from '../PriceDisplay';
import { formatNumber } from '@/utils';
import type { NurseSearchResult } from '@/services/search/types';

export interface NurseResultCardProps {
  /** One search-result row (a bookable variant in a covered area). */
  nurse: NurseSearchResult;
  /** Tapping the card opens the nurse profile (C3), carrying the row (nurse + variant + gender intent). */
  onSelect: (nurse: NurseSearchResult) => void;
}

function ratingText(rating: number, locale: string): string {
  return formatNumber(rating, locale, { minimumFractionDigits: 1, maximumFractionDigits: 1 });
}

/**
 * The C2 result card: avatar, name, the reused ✓ تاییدشده verified badge, rating + review count, an
 * optional distance chip (only when `distanceKm` is present), and the "from X تومان/ساعت" rate (via the
 * shared `PriceDisplay` money util). Presentational + memoized so a list of N cards doesn't re-render on
 * unrelated state — pass a stable `onSelect` (e.g. `useCallback`). Every returned row is verified by the
 * search-index invariant, so the badge is always shown.
 * @component NurseResultCard
 */
const NurseResultCard = ({ nurse, onSelect }: NurseResultCardProps) => {
  const t = useTranslations('search');
  const locale = useLocale();

  const name = nurse.nurseName.trim() || t('unnamed_nurse');
  const initial = name.charAt(0);
  const distance =
    nurse.distanceKm != null ? formatNumber(nurse.distanceKm, locale, { maximumFractionDigits: 1 }) : null;

  return (
    <Paper
      elevation={0}
      onClick={() => onSelect(nurse)}
      role="button"
      tabIndex={0}
      onKeyDown={(event) => {
        if (event.key === 'Enter' || event.key === ' ') {
          event.preventDefault();
          onSelect(nurse);
        }
      }}
      sx={{
        p: 2,
        display: 'flex',
        gap: 2,
        alignItems: 'flex-start',
        border: '1px solid',
        borderColor: 'divider',
        borderRadius: 2,
        cursor: 'pointer',
        transition: 'border-color 120ms ease',
        '&:hover': { borderColor: 'var(--bal-primary)' },
        '&:focus-visible': { outline: '2px solid var(--bal-primary)', outlineOffset: 2 },
      }}
    >
      <Avatar
        src={nurse.avatarUrl ?? undefined}
        sx={{ width: 56, height: 56, bgcolor: 'var(--bal-primary-soft)', color: 'var(--bal-primary)', fontWeight: 700 }}
      >
        {initial}
      </Avatar>

      <Stack sx={{ gap: 0.75, flexGrow: 1, minWidth: 0 }}>
        <Stack direction="row" sx={{ gap: 1, alignItems: 'center', flexWrap: 'wrap' }}>
          <Typography variant="subtitle1" sx={{ fontWeight: 700 }}>
            {name}
          </Typography>
          <TrustBadge state="verified" />
        </Stack>

        <Stack direction="row" sx={{ gap: 1.5, alignItems: 'center', flexWrap: 'wrap' }}>
          <Stack direction="row" sx={{ gap: 0.5, alignItems: 'center' }}>
            <AppIcon icon="star" size={16} color="var(--bal-rating)" />
            <Typography variant="body2" sx={{ fontWeight: 700 }}>
              {ratingText(nurse.averageRating, locale)}
            </Typography>
            <Typography variant="body2" sx={{ color: 'text.secondary' }}>
              {t('reviews_count', { count: nurse.totalReviews })}
            </Typography>
          </Stack>

          {distance != null ? (
            <Stack direction="row" sx={{ gap: 0.25, alignItems: 'center' }}>
              <AppIcon icon="location" size={16} color="var(--bal-text-secondary)" />
              <Typography variant="body2" sx={{ color: 'text.secondary' }}>
                {t('distance_km', { km: distance })}
              </Typography>
            </Stack>
          ) : null}
        </Stack>

        <Box sx={{ display: 'flex', alignItems: 'baseline', gap: 0.5, flexWrap: 'wrap' }}>
          <Typography variant="body2" sx={{ color: 'text.secondary' }}>
            {t('price_from')}
          </Typography>
          <PriceDisplay price={nurse.priceFromIrr} priceUnit={nurse.priceUnit} align="start" />
        </Box>
      </Stack>
    </Paper>
  );
};

/** Matches the real card's anatomy (avatar disc, name/badge row, rating row, price row) so a loading list
 * doesn't jump when data lands. */
const NurseResultCardSkeleton: FunctionComponent = () => (
  <Paper elevation={0} sx={{ p: 2, display: 'flex', gap: 2, alignItems: 'flex-start', border: '1px solid', borderColor: 'divider', borderRadius: 2 }}>
    <Skeleton variant="circular" width={56} height={56} />
    <Stack sx={{ gap: 0.75, flexGrow: 1 }}>
      <Skeleton variant="text" width="55%" height={28} />
      <Skeleton variant="text" width="40%" height={20} />
      <Skeleton variant="text" width="30%" height={20} />
    </Stack>
  </Paper>
);

export default Object.assign(memo(NurseResultCard), { Skeleton: NurseResultCardSkeleton });
