import { useMemo } from 'react';
import { Avatar } from '../../Atoms/Avatar/Avatar';
import { Icon } from '../../Atoms/Icon/Icon';
import { MenuAcciones } from '../MenuAcciones/MenuAcciones';
import { FONT_FAMILY_SANS } from '../../../designTokens';
import {
  ORGANIGRAMA_CARD_MIN_HEIGHT_PX,
  ORGANIGRAMA_CARD_WIDTH_PX,
  ORGANIGRAMA_NODE_HEADER_BG,
  ORGANIGRAMA_NODE_SUBTITLE_STYLE,
  ORGANIGRAMA_NODE_TITLE_STYLE,
} from './organigramaStyles';

const RESPONSABLE_LABEL_STYLE = {
  fontFamily: FONT_FAMILY_SANS,
  fontWeight: 400,
  fontSize: '12px',
  lineHeight: '18px',
  color: '#6B7280',
  margin: '0 0 8px',
};

const RESPONSABLE_NAME_STYLE = {
  fontFamily: FONT_FAMILY_SANS,
  fontWeight: 400,
  fontSize: '14px',
  lineHeight: '21px',
  color: '#29474C',
  margin: 0,
};

const MEMBERS_BUTTON_STYLE = {
  fontFamily: FONT_FAMILY_SANS,
  fontWeight: 400,
  fontSize: '12px',
  lineHeight: '18px',
  color: '#38656D',
  border: '1px solid #BDE4E9',
  borderRadius: 999,
  background: '#FFFFFF',
  padding: '4px 12px',
  cursor: 'pointer',
  whiteSpace: 'nowrap',
};

export const OrganigramaUnitCard = ({
  unit,
  onCreateSubunit,
  onEditUnit,
  onAssignPerson,
  onDeleteUnit,
  onUnitClick,
  onAssignMembersClick,
  className = '',
  style,
}) => {
  const menuActions = useMemo(() => {
    const actions = [];
    if (typeof onCreateSubunit === 'function') {
      actions.push({
        key: 'create-subunit',
        label: 'Crear subunidad',
        icon: 'PlusIcon',
        onClick: () => onCreateSubunit(unit),
      });
    }
    if (typeof onAssignPerson === 'function') {
      actions.push({
        key: 'assign-person',
        label: 'Asignar persona',
        icon: 'UserPlusIcon',
        onClick: () => onAssignPerson(unit),
      });
    }
    if (typeof onEditUnit === 'function') {
      actions.push({
        key: 'edit-unit',
        label: 'Editar unidad',
        icon: 'PencilSquareIcon',
        onClick: () => onEditUnit(unit),
      });
    }
    if (typeof onDeleteUnit === 'function') {
      actions.push({
        key: 'delete-unit',
        label: 'Eliminar unidad',
        icon: 'TrashIcon',
        danger: true,
        onClick: () => onDeleteUnit(unit),
      });
    }
    return actions;
  }, [onAssignPerson, onCreateSubunit, onDeleteUnit, onEditUnit, unit]);

  const miembros = unit?.miembros ?? [];
  const miembrosCount = unit?.miembrosCount ?? miembros.length;
  const responsable = unit?.responsable ?? null;
  const visibleAvatars = miembros.slice(0, 3);

  return (
    <article
      className={className}
      role="button"
      tabIndex={0}
      onClick={() => onUnitClick?.(unit)}
      onKeyDown={(event) => {
        if (event.key === 'Enter' || event.key === ' ') {
          event.preventDefault();
          onUnitClick?.(unit);
        }
      }}
      style={{
        width: ORGANIGRAMA_CARD_WIDTH_PX,
        minHeight: ORGANIGRAMA_CARD_MIN_HEIGHT_PX,
        borderRadius: 12,
        overflow: 'hidden',
        background: '#FFFFFF',
        boxShadow: '0 1px 3px rgba(15, 23, 42, 0.08), 0 4px 12px rgba(15, 23, 42, 0.06)',
        boxSizing: 'border-box',
        cursor: onUnitClick ? 'pointer' : 'default',
        ...style,
      }}
    >
      <header
        style={{
          background: ORGANIGRAMA_NODE_HEADER_BG,
          padding: '12px 16px',
          display: 'flex',
          alignItems: 'flex-start',
          justifyContent: 'space-between',
          gap: 8,
        }}
        onClick={(event) => event.stopPropagation()}
      >
        <div style={{ minWidth: 0, flex: 1 }}>
          <p style={ORGANIGRAMA_NODE_TITLE_STYLE}>{unit?.nombre ?? '—'}</p>
          {unit?.empresaNombre ? (
            <p style={{ ...ORGANIGRAMA_NODE_SUBTITLE_STYLE, marginTop: 2 }}>{unit.empresaNombre}</p>
          ) : null}
        </div>
        {menuActions.length > 0 ? (
          <div
            style={{
              flexShrink: 0,
              marginTop: -2,
            }}
          >
            <MenuAcciones
              actions={menuActions}
              ariaLabel={`Acciones de ${unit?.nombre ?? 'unidad'}`}
              menuWidth={210}
              triggerIconColor="#FFFFFF"
            />
          </div>
        ) : null}
      </header>

      <div style={{ padding: '12px 16px 16px' }}>
        <p style={RESPONSABLE_LABEL_STYLE}>Responsable</p>
        {responsable?.nombre ? (
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
            <Avatar
              src={responsable.avatarSrc}
              name={responsable.nombre}
              size="small"
              alt={responsable.nombre}
            />
            <p style={RESPONSABLE_NAME_STYLE}>{responsable.nombre}</p>
          </div>
        ) : (
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
              gap: 10,
              marginBottom: 12,
              color: '#9CA3AF',
            }}
          >
            <div
              style={{
                width: 32,
                height: 32,
                borderRadius: '50%',
                background: '#F3F4F6',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
              }}
            >
              <Icon name="UserIcon" variant="24-outline" size={18} style={{ color: '#9CA3AF' }} />
            </div>
            <p style={{ ...RESPONSABLE_NAME_STYLE, color: '#9CA3AF' }}>Sin responsable</p>
          </div>
        )}

        <div
          style={{
            borderTop: '1px solid #E5E7EB',
            paddingTop: 12,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
            gap: 8,
          }}
        >
          <div style={{ display: 'flex', alignItems: 'center' }}>
            {visibleAvatars.map((miembro, index) => (
              <div
                key={miembro.id ?? index}
                style={{
                  marginLeft: index === 0 ? 0 : -8,
                  border: '2px solid #FFFFFF',
                  borderRadius: '50%',
                }}
              >
                <Avatar
                  src={miembro.avatarSrc}
                  name={miembro.nombre}
                  size="small"
                  alt={miembro.nombre ?? 'Miembro'}
                />
              </div>
            ))}
          </div>
          <button
            type="button"
            style={MEMBERS_BUTTON_STYLE}
            onClick={(event) => {
              event.stopPropagation();
              onAssignMembersClick?.(unit);
            }}
          >
            {`+ ${miembrosCount} ${miembrosCount === 1 ? 'persona' : 'personas'}`}
          </button>
        </div>
      </div>
    </article>
  );
};

export default OrganigramaUnitCard;
