/**
 * CardsEmpresas: vista en cards de empresas (mismo formato de items que ListaEmpresas).
 * Muestra nombre fantasía, razón social y badge de estado por card. Opcional: onItemClick, acción por card.
 */
import { Card } from '../../DataDisplay/Card/Card';
import { Typography } from '../../Atoms/Typography/Typography';
import { Icon } from '../../Atoms/Icon/Icon';
import { FONT_FAMILY_SANS } from '../../../designTokens';

const COLOR_SECONDARY = 'var(--color-gray-600, #4b5563)';
const COLOR_ACCENT = '#38656D';
const CARD_WIDTH = 346.6666564941406;
const CARD_HEIGHT = 194;
const CARD_BODY_ROW_WIDTH = 298.6666564941406;
const CARD_AVATAR_SIZE = 60;
const CARD_BODY_TEXT_CONTAINER_WIDTH = 214.66665649414062;

const DEFAULT_STATUS_VARIANT = {
  Borrador: 'primary',
  Activa: 'success',
  Activo: 'success',
  Inactiva: 'inactive',
  Inactivo: 'inactive',
  Suspendida: 'error',
  Error: 'error',
};

const getNombreComercial = (item) => item.nombreComercial ?? item.nombreFantasia ?? '';
/** Subtítulo de la card: nombre legal/razón social y, si no hay, actividad (fecha u otro). */
const getSubtitulo = (item) => item.razonSocial ?? item.legalName ?? item.actividad ?? '';
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();
};

/** Items: { id, nombreComercial?|nombreFantasia?, pais?, estado?|status?, actividad?, ... } */
export const CardsEmpresas = ({
  items = [],
  /** Si true, muestra skeleton de carga en lugar de las cards */
  loading = false,
  onItemClick,
  actionButtonText = '',
  onActionClick,
  deleteActionText = 'Eliminar',
  onDeleteClick,
  showEditButton = true,
  showDeleteButton = true,
  shouldShowEditButton,
  shouldShowDeleteButton,
  emptyMessage = 'No hay empresas 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-cardsempresas anima-cardsempresas--loading ${className}`}
        style={{
          width: '100%',
          boxSizing: 'border-box',
          ...style,
        }}
        {...props}
      >
        <div
          className="anima-cardsempresas__grid"
          style={{
            display: 'flex',
            flexDirection: 'column',
            gap: 16,
            ...gridStyle,
          }}
        >
          {Array.from({ length: skeletonCount }).map((_, index) => (
            <Card
              key={index}
              loading={true}
              height={CARD_HEIGHT}
            />
          ))}
        </div>
      </div>
    );
  }

  if (items.length === 0) {
    return (
      <div
        className={`anima-cardsempresas anima-cardsempresas--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-cardsempresas ${className}`}
      style={{
        width: '100%',
        boxSizing: 'border-box',
        ...style,
      }}
      {...props}
    >
      <div
        className="anima-cardsempresas__grid"
        style={{
          display: 'flex',
          flexDirection: 'column',
          gap: 16,
          ...gridStyle,
        }}
      >
        {items.map((item, index) => {
          const isEditVisible = typeof shouldShowEditButton === 'function'
            ? !!shouldShowEditButton(item, index)
            : showEditButton;
          const isDeleteVisible = typeof shouldShowDeleteButton === 'function'
            ? !!shouldShowDeleteButton(item, index)
            : showDeleteButton;

          const cardBody = (
            <div
              style={{
                width: CARD_BODY_ROW_WIDTH,
                height: CARD_AVATAR_SIZE,
                gap: 16,
                paddingRight: 4,
                paddingLeft: 4,
                boxSizing: 'border-box',
                display: 'flex',
                alignItems: 'center',
              }}
            >
              <div
                style={{
                  width: CARD_AVATAR_SIZE,
                  height: CARD_AVATAR_SIZE,
                  gap: 10,
                  opacity: 1,
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                }}
              >
                <div
                  style={{
                    width: CARD_AVATAR_SIZE,
                    height: CARD_AVATAR_SIZE,
                    borderRadius: 16,
                    border: `1px solid ${COLOR_ACCENT}`,
                    padding: 16,
                    background: '#FFFFFF',
                    boxSizing: 'border-box',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                  }}
                >
                  <Typography
                    component="span"
                    style={{
                      width: 33,
                      height: 36,
                      fontFamily: FONT_FAMILY_SANS,
                      fontWeight: 400,
                      fontStyle: 'normal',
                      fontSize: '24px',
                      lineHeight: '36px',
                      letterSpacing: '0px',
                      color: COLOR_ACCENT,
                      margin: 0,
                      textAlign: 'center',
                    }}
                  >
                    {getInitials(getNombreComercial(item))}
                  </Typography>
                </div>
              </div>
              <div
                style={{
                  width: CARD_BODY_TEXT_CONTAINER_WIDTH,
                  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',
                  }}
                >
                  {getNombreComercial(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 cardActions = (
            <>
              {isDeleteVisible && deleteActionText && (
                <button
                  type="button"
                  aria-label={deleteActionText ? `Eliminar ${getNombreComercial(item)}` : undefined}
                  onClick={(e) => {
                    e?.stopPropagation?.();
                    onDeleteClick?.(item, index, e);
                  }}
                  style={{
                    width: 'auto',
                    minWidth: 86,
                    height: 26,
                    gap: 8,
                    paddingTop: 4,
                    paddingRight: 8,
                    paddingBottom: 4,
                    paddingLeft: 8,
                    borderRadius: 8,
                    border: `1px solid ${COLOR_ACCENT}`,
                    background: '#FFFFFF',
                    boxSizing: 'border-box',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    cursor: 'pointer',
                    marginRight: 8,
                  }}
                >
                  <Icon
                    name="TrashIcon"
                    variant="24-outline"
                    size={11}
                    style={{ width: 11, height: 11, color: COLOR_ACCENT, flexShrink: 0 }}
                  />
                  <Typography
                    component="span"
                    style={{
                      fontFamily: FONT_FAMILY_SANS,
                      fontWeight: 500,
                      fontStyle: 'normal',
                      fontSize: '12px',
                      lineHeight: '18px',
                      letterSpacing: '0.02em',
                      verticalAlign: 'middle',
                      color: COLOR_ACCENT,
                      margin: 0,
                      whiteSpace: 'nowrap',
                    }}
                  >
                    {deleteActionText}
                  </Typography>
                </button>
              )}
              {isEditVisible && actionButtonText && (
                <button
                  type="button"
                  aria-label={actionButtonText ? `Editar ${getNombreComercial(item)}` : undefined}
                  onClick={(e) => {
                    e?.stopPropagation?.();
                    onActionClick?.(item, index, e);
                  }}
                  style={{
                    width: 70,
                    height: 26,
                    gap: 8,
                    paddingTop: 4,
                    paddingRight: 8,
                    paddingBottom: 4,
                    paddingLeft: 8,
                    borderRadius: 8,
                    border: `1px solid ${COLOR_ACCENT}`,
                    background: '#FFFFFF',
                    boxSizing: 'border-box',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    cursor: 'pointer',
                  }}
                >
                  <Icon
                    name="PencilIcon"
                    variant="24-outline"
                    size={11}
                    style={{ width: 11, height: 11, color: COLOR_ACCENT, flexShrink: 0 }}
                  />
                  <Typography
                    component="span"
                    style={{
                      width: 35,
                      height: 18,
                      fontFamily: FONT_FAMILY_SANS,
                      fontWeight: 500,
                      fontStyle: 'normal',
                      fontSize: '12px',
                      lineHeight: '18px',
                      letterSpacing: '0.02em',
                      verticalAlign: 'middle',
                      color: COLOR_ACCENT,
                      margin: 0,
                      whiteSpace: 'nowrap',
                    }}
                  >
                    {actionButtonText}
                  </Typography>
                </button>
              )}
            </>
          );

          return (
            <Card
              key={item.id ?? index}
              hasData={true}
              variant="cortoMasEstado"
              title={item.cuit ?? '—'}
              titleVariant="small"
              status={(item.estado ?? item.status) || null}
              statusAsBadge={true}
              statusVariant={getStatusVariant(item)}
              height={CARD_HEIGHT}
              onClick={onItemClick ? () => onItemClick(item, index) : undefined}
              ariaLabel={onItemClick ? `Abrir ${getNombreComercial(item)}` : undefined}
              actions={cardActions}
              className="anima-cardsempresas__card"
            >
              {cardBody}
            </Card>
          );
        })}
      </div>
    </div>
  );
};

export default CardsEmpresas;
