import { useCallback, useEffect, useId, useState } from 'react';
import { createPortal } from 'react-dom';
import { Icon } from '../../Atoms/Icon/Icon';
import { Typography } from '../../Atoms/Typography/Typography';
import { Badge } from '../../Atoms/Badge/Badge';
import { PrimaryActionButton } from '../../Atoms/PrimaryActionButton/PrimaryActionButton';
import { FONT_FAMILY_SANS } from '../../../designTokens';

/** Ancho del panel (Figma, escritorio). */
export const VISTA_RAPIDA_PERFIL_WIDTH_PX = 393;
/** Alto del panel (Figma, escritorio); en viewport bajo pasa a pantalla completa. */
export const VISTA_RAPIDA_PERFIL_HEIGHT_PX = 971;
/**
 * Por defecto, viewport con ancho ≤ este valor (px) usa panel a **pantalla completa**.
 * El consumidor puede pasar `responsiveMaxWidthPx` para alinearlo a su breakpoint (p. ej. 600 o 1024).
 */
export const VISTA_RAPIDA_PERFIL_DEFAULT_RESPONSIVE_MAX_PX = 768;

const PANEL_CLASS = 'anima-vista-rapida-perfil__panel';

function clampResponsiveBreakpoint(px) {
  const n = Number(px);
  if (!Number.isFinite(n)) return VISTA_RAPIDA_PERFIL_DEFAULT_RESPONSIVE_MAX_PX;
  return Math.min(Math.max(Math.round(n), 320), 2400);
}

function VistaRapidaPerfilResponsiveStyles({ maxWidthPx }) {
  const w = clampResponsiveBreakpoint(maxWidthPx);
  return (
    <style>{`
@media (max-width: ${w}px) {
  .${PANEL_CLASS} {
    width: 100% !important;
    max-width: 100%;
    left: 0 !important;
    right: 0 !important;
    height: 100vh !important;
    height: 100dvh !important;
    max-height: 100dvh !important;
    min-height: 100dvh !important;
    border-left: none !important;
    box-shadow: none !important;
  }
}
`}</style>
  );
}

const COLOR_MAIN_TEXT = '#29474C';
const COLOR_MAIN_TEAL = '#38656D';
const COLOR_LABEL = '#6B7280';
const COLOR_BORDER = '#C4C4C4';
const Z_BACKDROP = 1040;
const Z_PANEL = 1050;

const PANEL_INNER_PADDING = {
  paddingLeft: 24,
  paddingRight: 24,
  paddingTop: 24,
  paddingBottom: 24,
  boxSizing: 'border-box',
};

const cardShellStyle = {
  border: `1px solid ${COLOR_BORDER}`,
  borderRadius: 14,
  backgroundColor: '#FFFFFF',
  boxSizing: 'border-box',
};

const getInitials = (name) => {
  const text = (name || '').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();
};

function PerfilAvatarRapido({ nombre, fotoUrl }) {
  const [failed, setFailed] = useState(false);
  const src = typeof fotoUrl === 'string' ? fotoUrl.trim() : '';
  const showImg = !!src && !failed;
  const size = 96;

  return (
    <div
      style={{
        width: size,
        height: size,
        borderRadius: '999px',
        border: `1px solid ${COLOR_MAIN_TEAL}`,
        backgroundColor: '#FFFFFF',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        overflow: 'hidden',
        flexShrink: 0,
      }}
    >
      {showImg ? (
        <img
          src={src}
          alt=""
          onError={() => setFailed(true)}
          style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }}
        />
      ) : (
        <Typography
          component="span"
          style={{
            fontFamily: FONT_FAMILY_SANS,
            fontWeight: 500,
            fontSize: 28,
            lineHeight: 1,
            color: COLOR_MAIN_TEAL,
            margin: 0,
          }}
        >
          {getInitials(nombre)}
        </Typography>
      )}
    </div>
  );
}

function CampoInformacion({ label, value }) {
  if (value == null || String(value).trim() === '') return null;
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
      <Typography
        component="span"
        style={{
          fontFamily: FONT_FAMILY_SANS,
          fontWeight: 400,
          fontSize: 14,
          lineHeight: '21px',
          letterSpacing: '0.01em',
          color: COLOR_LABEL,
          margin: 0,
        }}
      >
        {label}
      </Typography>
      <Typography
        component="span"
        style={{
          fontFamily: FONT_FAMILY_SANS,
          fontWeight: 500,
          fontSize: 16,
          lineHeight: '24px',
          color: COLOR_MAIN_TEXT,
          margin: 0,
          wordBreak: 'break-word',
        }}
      >
        {value}
      </Typography>
    </div>
  );
}

/**
 * Panel lateral “vista rápida” de perfil: se fija a la **derecha** (overlay + panel 393×971 según diseño).
 *
 * @param {boolean} [props.isOpen=false]
 * @param {() => void} props.onClose — Cierre (backdrop, botón X o Escape).
 * @param {string} [props.title='Perfil']
 * @param {object} props.perfil — `nombreCompleto`, `rol`, `email`, `fechaCreacion`, `fotoUrl`, `estadoLabel`, `estadoBadgeVariant` (`success` por defecto si hay `estadoLabel`).
 * @param {string} [props.informacionTitle='Información']
 * @param {string} [props.emailLabel='Email']
 * @param {string} [props.fechaCreacionLabel='Fecha de creación']
 * @param {string} [props.legajoDigitalLabel='Ver legajo digital'] — Texto del botón principal (consumidor: traducción o otro CTA).
 * @param {(event: unknown) => void} [props.onLegajoDigitalClick] — **Punto de extensión del host:** navegación (`navigate`, `href`), nueva pestaña, modal, etc. Si no es una función, el botón queda deshabilitado.
 * @param {number} [props.responsiveMaxWidthPx=768] — Si el viewport es ≤ este ancho (px), el panel ocupa todo el ancho y alto de la pantalla (mobile / tablet estrecho). Ajustalo al breakpoint del host.
 */
export const VistaRapidaPerfil = ({
  isOpen = false,
  onClose,
  title = 'Perfil',
  perfil = {},
  informacionTitle = 'Información',
  emailLabel = 'Email',
  fechaCreacionLabel = 'Fecha de creación',
  /** Etiqueta del botón; el consumidor puede cambiarla o internacionalizarla. */
  legajoDigitalLabel = 'Ver legajo digital',
  /**
   * Clic en el botón principal: el consumidor define destino (ruta, URL externa, modal, etc.).
   * El DS no enruta. Sin función, el botón se muestra deshabilitado.
   */
  onLegajoDigitalClick,
  /** Viewport con ancho ≤ este valor (px): panel ancho y alto completos (`100dvh`). Default 768. */
  responsiveMaxWidthPx = VISTA_RAPIDA_PERFIL_DEFAULT_RESPONSIVE_MAX_PX,
  className = '',
  style = {},
  ...props
}) => {
  const titleId = useId();
  const {
    nombreCompleto = '',
    rol = '',
    email = '',
    fechaCreacion = '',
    fotoUrl = '',
    estadoLabel = '',
    estadoBadgeVariant = 'success',
  } = perfil;

  useEffect(() => {
    if (!isOpen) return undefined;
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => {
      document.body.style.overflow = prev;
    };
  }, [isOpen]);

  const handleEscape = useCallback(
    (e) => {
      if (e.key === 'Escape') onClose?.();
    },
    [onClose],
  );

  useEffect(() => {
    if (!isOpen) return undefined;
    document.addEventListener('keydown', handleEscape);
    return () => document.removeEventListener('keydown', handleEscape);
  }, [isOpen, handleEscape]);

  if (!isOpen) return null;

  const content = (
    <>
      <VistaRapidaPerfilResponsiveStyles maxWidthPx={responsiveMaxWidthPx} />
      <div
        role="presentation"
        style={{
          position: 'fixed',
          inset: 0,
          zIndex: Z_BACKDROP,
          backgroundColor: 'rgba(17, 24, 39, 0.45)',
          opacity: 1,
        }}
        onClick={onClose}
        aria-hidden="true"
      />
      <div
        role="dialog"
        aria-modal="true"
        aria-labelledby={titleId}
        className={`${PANEL_CLASS} ${className}`.trim()}
        style={{
          position: 'fixed',
          top: 0,
          right: 0,
          width: VISTA_RAPIDA_PERFIL_WIDTH_PX,
          height: VISTA_RAPIDA_PERFIL_HEIGHT_PX,
          maxHeight: '100vh',
          zIndex: Z_PANEL,
          backgroundColor: '#FFFFFF',
          borderLeft: `1px solid ${COLOR_BORDER}`,
          boxSizing: 'border-box',
          display: 'flex',
          flexDirection: 'column',
          opacity: 1,
          boxShadow: '-4px 0 24px rgba(0, 0, 0, 0.06)',
          ...style,
        }}
        onClick={(e) => e.stopPropagation()}
        {...props}
      >
        <div
          style={{
            display: 'flex',
            flexDirection: 'column',
            flex: 1,
            minHeight: 0,
            ...PANEL_INNER_PADDING,
          }}
        >
          <header
            style={{
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'space-between',
              flexShrink: 0,
              marginBottom: 24,
            }}
          >
            <Typography
              id={titleId}
              component="h2"
              style={{
                fontFamily: FONT_FAMILY_SANS,
                fontWeight: 400,
                fontStyle: 'normal',
                fontSize: 24,
                lineHeight: '30px',
                letterSpacing: '0%',
                verticalAlign: 'middle',
                color: COLOR_MAIN_TEXT,
                margin: 0,
              }}
            >
              {title}
            </Typography>
            <button
              type="button"
              onClick={onClose}
              aria-label="Cerrar"
              style={{
                border: 'none',
                background: 'transparent',
                padding: 8,
                margin: -8,
                cursor: 'pointer',
                display: 'inline-flex',
                alignItems: 'center',
                justifyContent: 'center',
                color: COLOR_LABEL,
              }}
            >
              <Icon name="XMarkIcon" variant="24-outline" size={24} style={{ color: COLOR_MAIN_TEXT }} />
            </button>
          </header>

          <div
            style={{
              flex: 1,
              minHeight: 0,
              overflowY: 'auto',
              display: 'flex',
              flexDirection: 'column',
              gap: 24,
            }}
          >
            <section
              style={{
                ...cardShellStyle,
                padding: 24,
                display: 'flex',
                flexDirection: 'column',
                alignItems: 'center',
                textAlign: 'center',
                gap: 16,
              }}
            >
              <PerfilAvatarRapido nombre={nombreCompleto} fotoUrl={fotoUrl} />
              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4 }}>
                <Typography
                  component="p"
                  style={{
                    fontFamily: FONT_FAMILY_SANS,
                    fontWeight: 500,
                    fontSize: 20,
                    lineHeight: '30px',
                    color: COLOR_MAIN_TEXT,
                    margin: 0,
                  }}
                >
                  {nombreCompleto || '—'}
                </Typography>
                {!!String(rol).trim() && (
                  <Typography
                    component="p"
                    style={{
                      fontFamily: FONT_FAMILY_SANS,
                      fontWeight: 400,
                      fontSize: 14,
                      lineHeight: '21px',
                      color: COLOR_LABEL,
                      margin: 0,
                    }}
                  >
                    {rol}
                  </Typography>
                )}
              </div>
              {!!String(estadoLabel).trim() && (
                <Badge variant={estadoBadgeVariant} size="medium">
                  {estadoLabel}
                </Badge>
              )}
            </section>

            <PrimaryActionButton
              type="button"
              variant="primary"
              fullWidth
              disabled={typeof onLegajoDigitalClick !== 'function'}
              onClick={(e) => {
                e?.stopPropagation?.();
                onLegajoDigitalClick?.(e);
              }}
              aria-label={legajoDigitalLabel}
              textStyle={{
                fontFamily: FONT_FAMILY_SANS,
                fontWeight: 500,
                fontStyle: 'normal',
                fontSize: '16px',
                lineHeight: '24px',
                letterSpacing: '0%',
              }}
            >
              {legajoDigitalLabel}
            </PrimaryActionButton>

            <section
              style={{
                ...cardShellStyle,
                padding: 24,
                display: 'flex',
                flexDirection: 'column',
                gap: 20,
              }}
            >
              <Typography
                component="h3"
                style={{
                  fontFamily: FONT_FAMILY_SANS,
                  fontWeight: 400,
                  fontStyle: 'normal',
                  fontSize: 20,
                  lineHeight: '30px',
                  letterSpacing: '0px',
                  color: COLOR_MAIN_TEAL,
                  margin: 0,
                }}
              >
                {informacionTitle}
              </Typography>
              <CampoInformacion label={emailLabel} value={email} />
              <CampoInformacion label={fechaCreacionLabel} value={fechaCreacion} />
            </section>
          </div>
        </div>
      </div>
    </>
  );

  if (typeof document !== 'undefined' && document.body) {
    return createPortal(content, document.body);
  }
  return content;
};

export default VistaRapidaPerfil;
