/**
 * CardsPersonas: vista en cards de personas (base clonada desde CardsEmpresas).
 * Nota: se mantiene el formato de items por compatibilidad inicial; luego se ajustará al modelo de Persona.
 *
 * **Ver (botón outline):** pasá `onViewClick` para que el consumidor navegue o ejecute otra acción; el DS no enruta.
 * Firma `(item, index, event) => void` — mismo criterio que `ListaPersonas` al usar esta vista.
 */
import { useState } from 'react';
import { Card } from '../../DataDisplay/Card/Card';
import { Typography } from '../../Atoms/Typography/Typography';
import { Icon } from '../../Atoms/Icon/Icon';
import { PrimaryActionButton } from '../../Atoms/PrimaryActionButton/PrimaryActionButton';
import { FONT_FAMILY_SANS } from '../../../designTokens';
import { buildPersonaDocumentoLabel } from '../ListaPersonas/buildPersonaDocumentoLabel';
 
const COLOR_SECONDARY = 'var(--color-gray-600, #4b5563)';
/** Espacio entre el cuerpo (avatar / nombre) y los botones Ver / Editar. */
const CARD_ACTIONS_MARGIN_TOP = 14;
/** Altura total card: cabe footer con PrimaryActionButton (48px) + margen superior de acciones. */
const CARD_HEIGHT = 216 + CARD_ACTIONS_MARGIN_TOP;
const CARD_AVATAR_SIZE = 60;

/**
 * Cuadrícula responsive: 1 col (estrecho), 2 cols (tablet), 3 cols (desktop).
 * Si pasas `gridTemplateColumns` en `gridStyle`, anula estas reglas (inline gana al CSS).
 */
const CARDS_GRID_RESPONSIVE_CSS = `
.anima-cardspersonas__grid {
  display: grid;
  width: 100%;
  box-sizing: border-box;
  gap: 16px;
  grid-template-columns: minmax(0, 1fr);
}
@media (min-width: 600px) {
  .anima-cardspersonas__grid {
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }
}
@media (min-width: 992px) {
  .anima-cardspersonas__grid {
    grid-template-columns: repeat(3, minmax(0, 1fr));
  }
}
`;

const CardsPersonasGridStyles = () => <style>{CARDS_GRID_RESPONSIVE_CSS}</style>;
 
const DEFAULT_STATUS_VARIANT = {
  Activa: 'success',
  Archivada: 'inactive',
};
 
const getNombrePersona = (item) => item.nombreComercial ?? item.nombreFantasia ?? '';
/** Subtítulo bajo el nombre: correo electrónico (mismas variantes de campo que suelen traer los ítems). */
const getSubtitulo = (item) =>
  item?.email
  ?? item?.correo
  ?? item?.mail
  ?? item?.correoElectronico
  ?? '';

/** Encabezado superior izquierdo de la card: mismo criterio que la columna Documento de la tabla. */
const getCardTitleDocumento = (item) => {
  const label = buildPersonaDocumentoLabel(item, item?.documento);
  return label?.trim() ? label : '—';
};

const truncateWithEllipsis = (value, maxChars) => {
  const text = String(value ?? '').trim();
  if (!text) return '—';
  const parsedMax = Number(maxChars);
  if (!Number.isFinite(parsedMax) || parsedMax <= 0) return text;
  if (text.length <= parsedMax) return text;
  if (parsedMax === 1) return '…';
  return `${text.slice(0, parsedMax - 1)}…`;
};
const getInitials = (value) => {
  const text = (value || '').trim();
  if (!text) return '';
  const words = text.split(/\s+/).filter(Boolean);
  if (words.length >= 2) return `${words[0][0] ?? ''}${words[1][0] ?? ''}`.toUpperCase();
  return `${words[0][0] ?? ''}`.toUpperCase();
};

/** Misma lógica que `PersonaAvatar` en ListaPersonas: círculo, foto o iniciales. */
function PersonaCardAvatar({ item, initials }) {
  const [imgFailed, setImgFailed] = useState(false);
  const photoSrc =
    item?.foto
    ?? item?.photo
    ?? item?.photoUrl
    ?? item?.avatarUrl
    ?? item?.imageUrl
    ?? item?.imagen
    ?? item?.profilePicture
    ?? item?.profilePictureUrl
    ?? item?.picture
    ?? '';
  const src = typeof photoSrc === 'string' ? photoSrc.trim() : '';
  const shouldShowImg = !!src && !imgFailed;
  const size = CARD_AVATAR_SIZE;

  return (
    <div
      style={{
        width: size,
        height: size,
        minWidth: size,
        minHeight: size,
        borderRadius: '999px',
        border: '1px solid var(--color-main-700, #38656D)',
        background: 'var(--color-neutrals-white, #FFFFFF)',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        boxSizing: 'border-box',
        overflow: 'hidden',
        flexShrink: 0,
      }}
    >
      {shouldShowImg ? (
        <img
          src={src}
          alt=""
          onError={() => setImgFailed(true)}
          style={{
            width: '100%',
            height: '100%',
            objectFit: 'cover',
            display: 'block',
          }}
        />
      ) : (
        <Typography
          component="span"
          style={{
            fontFamily: FONT_FAMILY_SANS,
            fontWeight: 500,
            fontStyle: 'normal',
            fontSize: '21px',
            lineHeight: '100%',
            letterSpacing: '0px',
            color: 'var(--color-main-700, #38656D)',
            margin: 0,
          }}
        >
          {initials}
        </Typography>
      )}
    </div>
  );
}
 
/** Items: { id, nombreComercial?|nombreFantasia?, email?, estado?|status?, ... } */
export const CardsPersonas = ({
  items = [],
  /** Si true, muestra skeleton de carga en lugar de las cards */
  loading = false,
  /** Clic en la card (no en botones): (item, index, event). En ListaPersonas la vista tarjetas no usa selección; este callback es opcional (p. ej. abrir detalle). */
  onItemClick,
  /** Si se define, fondo de “seleccionado” (p. ej. uso fuera de ListaPersonas). ListaPersonas no lo pasa en vista tarjetas. */
  isItemSelected,
  actionButtonText = '',
  onActionClick,
  viewActionText = 'Ver',
  /** Navegación / detalle / modal: lo define el consumidor; `(item, index, event) => void`. */
  onViewClick,
  showViewCardButton = true,
  shouldShowViewCardButton,
  showEditButton = true,
  shouldShowEditButton,
  documentoMaxChars,
  emptyMessage = 'No hay personas cargadas.',
  className = '',
  style = {},
  gridStyle = {},
  ...props
}) => {
  const getStatusVariant = (item) => {
    if (item.statusVariant) return item.statusVariant;
    return DEFAULT_STATUS_VARIANT[item.estado ?? item.status] || DEFAULT_STATUS_VARIANT[item.status] || 'default';
  };
 
  if (loading) {
    const skeletonCount = 6;
    return (
      <div
        className={`anima-cardspersonas anima-cardspersonas--loading ${className}`}
        style={{
          width: '100%',
          boxSizing: 'border-box',
          ...style,
        }}
        {...props}
      >
        <CardsPersonasGridStyles />
        <div
          className="anima-cardspersonas__grid"
          style={{
            boxSizing: 'border-box',
            ...gridStyle,
          }}
        >
          {Array.from({ length: skeletonCount }).map((_, index) => (
            <Card
              key={index}
              loading={true}
              height={CARD_HEIGHT}
              width="100%"
            />
          ))}
        </div>
      </div>
    );
  }
 
  if (items.length === 0) {
    return (
      <div
        className={`anima-cardspersonas anima-cardspersonas--empty ${className}`}
        style={{
          width: '100%',
          padding: 32,
          textAlign: 'center',
          fontFamily: FONT_FAMILY_SANS,
          fontSize: '16px',
          lineHeight: '24px',
          color: COLOR_SECONDARY,
          boxSizing: 'border-box',
          ...style,
        }}
        {...props}
      >
        {emptyMessage}
      </div>
    );
  }
 
  return (
    <div
      className={`anima-cardspersonas ${className}`}
      style={{
        width: '100%',
        boxSizing: 'border-box',
        ...style,
      }}
      {...props}
    >
      <CardsPersonasGridStyles />
      <div
        className="anima-cardspersonas__grid"
        style={{
          boxSizing: 'border-box',
          ...gridStyle,
        }}
      >
        {items.map((item, index) => {
          const isViewVisible = typeof shouldShowViewCardButton === 'function'
            ? !!shouldShowViewCardButton(item, index)
            : showViewCardButton;
          const isEditVisible = typeof shouldShowEditButton === 'function'
            ? !!shouldShowEditButton(item, index)
            : showEditButton;

          const hasView = isViewVisible && !!String(viewActionText ?? '').trim();
          const hasEdit = isEditVisible && !!String(actionButtonText ?? '').trim();

          const cardBody = (
            <div
              style={{
                width: '100%',
                maxWidth: '100%',
                height: CARD_AVATAR_SIZE,
                gap: 16,
                paddingRight: 4,
                paddingLeft: 4,
                boxSizing: 'border-box',
                display: 'flex',
                alignItems: 'center',
                minWidth: 0,
              }}
            >
              <PersonaCardAvatar
                item={item}
                initials={getInitials(getNombrePersona(item))}
              />
              <div
                style={{
                  flex: '1 1 auto',
                  height: 51,
                  opacity: 1,
                  minWidth: 0,
                  display: 'flex',
                  flexDirection: 'column',
                  justifyContent: 'center',
                }}
              >
                <Typography
                  component="span"
                  style={{
                    fontFamily: FONT_FAMILY_SANS,
                    fontWeight: 500,
                    fontStyle: 'normal',
                    fontSize: '20px',
                    lineHeight: '30px',
                    letterSpacing: '0%',
                    verticalAlign: 'middle',
                    color: '#29474C',
                    margin: 0,
                    whiteSpace: 'nowrap',
                    overflow: 'hidden',
                    textOverflow: 'ellipsis',
                  }}
                >
                  {getNombrePersona(item)}
                </Typography>
                <Typography
                  component="span"
                  style={{
                    fontFamily: FONT_FAMILY_SANS,
                    fontWeight: 400,
                    fontStyle: 'normal',
                    fontSize: '14px',
                    lineHeight: '21px',
                    letterSpacing: '0.01em',
                    color: '#29474C',
                    margin: 0,
                    whiteSpace: 'nowrap',
                    overflow: 'hidden',
                    textOverflow: 'ellipsis',
                  }}
                >
                  {getSubtitulo(item)}
                </Typography>
              </div>
            </div>
          );
 
          const hasFooterActions = hasView || hasEdit;

          const cardActions = hasFooterActions ? (
            <div
              style={{
                width: '100%',
                marginTop: CARD_ACTIONS_MARGIN_TOP,
                display: 'flex',
                alignItems: 'center',
                gap: 12,
                flexWrap: 'wrap',
                justifyContent: hasView && hasEdit ? 'space-between' : hasView ? 'flex-start' : 'flex-end',
              }}
            >
              {hasView && (
                <PrimaryActionButton
                  type="button"
                  variant="outline"
                  aria-label={`${viewActionText} ${getNombrePersona(item)}`}
                  onClick={(e) => {
                    e?.stopPropagation?.();
                    onViewClick?.(item, index, e);
                  }}
                  style={{ marginLeft: 0, minWidth: 'auto' }}
                  textStyle={{ fontWeight: 500 }}
                >
                  {viewActionText}
                </PrimaryActionButton>
              )}
              {hasEdit && (
                <PrimaryActionButton
                  type="button"
                  variant="primary"
                  aria-label={`${actionButtonText} ${getNombrePersona(item)}`}
                  onClick={(e) => {
                    e?.stopPropagation?.();
                    onActionClick?.(item, index, e);
                  }}
                  style={{ marginLeft: 0, minWidth: 'auto' }}
                  textStyle={{ fontWeight: 500 }}
                >
                  <span
                    style={{
                      display: 'inline-flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      gap: 8,
                    }}
                  >
                    <Icon
                      name="PencilSquareIcon"
                      variant="24-outline"
                      size={20}
                      style={{ width: 20, height: 20, color: '#FFFFFF', flexShrink: 0 }}
                    />
                    {actionButtonText}
                  </span>
                </PrimaryActionButton>
              )}
            </div>
          ) : null;
 
          const selected = typeof isItemSelected === 'function' ? !!isItemSelected(item) : false;
          const nombre = getNombrePersona(item);

          return (
            <Card
              key={item.id ?? index}
              hasData={true}
              variant="cortoMasEstado"
              title={truncateWithEllipsis(getCardTitleDocumento(item), documentoMaxChars)}
              titleVariant="small"
              status={(item.estado ?? item.status) || null}
              statusAsBadge={true}
              statusVariant={getStatusVariant(item)}
              height={CARD_HEIGHT}
              width="100%"
              onClick={onItemClick ? (e) => onItemClick(item, index, e) : undefined}
              ariaLabel={
                onItemClick
                  ? (selected ? `Deseleccionar ${nombre}` : `Seleccionar ${nombre}`)
                  : undefined
              }
              style={{
                cursor: 'default',
                ...(selected ? { backgroundColor: 'rgba(0, 0, 0, 0.04)' } : {}),
              }}
              actions={cardActions}
              className="anima-cardspersonas__card"
            >
              {cardBody}
            </Card>
          );
        })}
      </div>
    </div>
  );
};
 
export default CardsPersonas;
