/**
 * Formulario Empresa: variante C (crear) o E (editar). Card con título, Badge de estado, dos columnas (fantasía + marca/upload | país, tipo ID, ID tributario, razón social) y botones Descartar + Guardar.
 * C = crear (NUEVA EMPRESA, Borrador). E = editar (EMPRESA, Activo, datos cargados). Reutiliza PrimaryInput, PrimarySelect, PrimaryActionButton, Badge, IdentidadVisual, Options. Responsive.
 */
import { useState, useEffect, useLayoutEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { Typography } from '../../Atoms/Typography/Typography';
import { PrimaryInput } from '../../Inputs/PrimaryInput/PrimaryInput';
import { PrimarySelect } from '../../Inputs/PrimarySelect/PrimarySelect';
import { PrimaryActionButton } from '../../Atoms/PrimaryActionButton/PrimaryActionButton';
import { Badge } from '../../Atoms/Badge/Badge';
import { IdentidadVisual } from '../IdentidadVisual/IdentidadVisual';
import { Options } from '../../Inputs/Options/Options';
import { Skeleton } from '../../Atoms/Skeleton/Skeleton';
import { Icon } from '../../Atoms/Icon/Icon';
import { FONT_FAMILY_SANS, FONT_FAMILY_MONO } from '../../../designTokens';
import { CardGrande } from '../CardGrande/CardGrande';

const CHEVRON_COLOR_BY_BADGE_VARIANT = {
  primary: '#334681',
  success: '#0A742C',
  default: '#334681',
  warning: '#F59E0B',
  danger: '#B30808',
};

/** Mensaje de error de logo (mismo texto que ConfiguracionMarcaTenant al subir imagen). */
const DEFAULT_LOGO_ERROR_TITLE = 'La imagen seleccionada, no cumple las especificaciones.';
const DEFAULT_LOGO_ERROR_SUBTITLE = 'Inténtelo nuevamente.';

/** Opciones de estado de ejemplo; el consumidor define y pasa statusOptions. */
export const DEFAULT_STATUS_OPTIONS = [
  { value: 'Borrador', label: 'Borrador', variant: 'default' },
  { value: 'Activa', label: 'Activa', variant: 'success' },
  { value: 'Inactiva', label: 'Inactiva', variant: 'neutral' },
  { value: 'Suspendida', label: 'Suspendida', variant: 'error' },
];

/** Variante C = crear, E = editar. Afecta solo defaults de título, badge y statusValue cuando no se pasan por props. */
export const Empresa = ({
  variant = 'C',
  loading = false,
  title: titleProp,
  titleStyle,
  titleClassName = '',
  statusBadgeText: statusBadgeTextProp,
  showStatusBadge = true,
  statusBadgeEndIcon,
  statusBadgeVariant: statusBadgeVariantProp,
  statusValue: statusValueProp,
  onStatusChange,
  statusOptions = [],
  statusDropdownOpen: statusDropdownOpenProp,
  onStatusDropdownOpenChange,

  // Columna izquierda: Nombre de fantasía
  nombreFantasiaLabel,
  nombreFantasiaValue = '',
  nombreFantasiaOnChange,
  nombreFantasiaPlaceholder,
  nombreFantasiaError = '',
  /** Nombre de fantasía es opcional por defecto; la creación se basa en país, identificador legal y razón social. */
  nombreFantasiaRequired = false,

  // Columna izquierda: Marca actual (IdentidadVisual)
  marcaActualTitle,
  marcaActualImage,
  marcaActualImageAlt = '',
  marcaActualNucleusText = 'N',
  formatoText = 'Formato cuadrado\nPNG de máximo 2Mb',
  uploadButtonText,
  uploadButtonOnClick,
  /** Mensaje de error de carga del logo; si tiene valor se muestra la caja de error debajo de Marca actual. Si es string se usa como título; si es truthy (ej. true) se usa el mensaje por defecto (igual que en tenant). */
  logoError = '',
  /** Subtítulo del error de logo (mismo default que ConfiguracionMarcaTenant). */
  logoErrorSubtitle,

  // Columna derecha: Tipo de identificación
  tipoIdentificacionLabel,
  tipoIdentificacionOptions = [],
  tipoIdentificacionValue = '',
  tipoIdentificacionOnChange,
  tipoIdentificacionPlaceholder = '',
  tipoIdentificacionError = '',
  tipoIdentificacionDisabled = false,

  // Columna derecha: ID tributario
  idTributarioLabel,
  idTributarioValue = '',
  idTributarioOnChange,
  idTributarioPlaceholder,
  idTributarioError = '',
  idTributarioDisabled = false,
  idTributarioRequired = false,

  // Columna derecha: Razón social
  razonSocialLabel,
  razonSocialValue = '',
  razonSocialOnChange,
  razonSocialPlaceholder,
  razonSocialError = '',
  razonSocialRequired = false,

  // Columna derecha: País
  paisLabel,
  paisOptions = [],
  paisValue = '',
  paisOnChange,
  paisPlaceholder = '',
  paisError = '',
  paisRequired = false,
  /** Si true, el select de País se muestra deshabilitado (solo lectura), alineado con tipoIdentificacionDisabled/idTributarioDisabled. */
  paisDisabled = false,

  // Footer
  discardButtonText,
  onDiscard,
  submitButtonText,
  submitButtonDisabled = false,
  /** (event, { variant: 'C'|'E', payload }) => void. C = crear → petición a un lado; E = editar → petición a otro. payload: { nombreFantasia, tipoIdentificacion, idTributario, razonSocial, pais, status }. */
  onSubmit,

  containerStyle,
  containerClassName = '',
  titleContainerStyle,
  titleContainerClassName = '',
  contentContainerStyle,
  contentContainerClassName = '',
  breakpointNarrowPx = 1023,

  className = '',
  ...props
}) => {
  const { t } = useTranslation();
  const isEdit = variant === 'E' || variant === 'edit';
  const title = titleProp ?? (isEdit
    ? t('empresa.form.title.edit', { defaultValue: 'EMPRESA' })
    : t('empresa.form.title.create', { defaultValue: 'NUEVA EMPRESA' }));
  const statusBadgeText = statusBadgeTextProp ?? (isEdit
    ? t('empresa.form.status.active', { defaultValue: 'Activo' })
    : t('empresa.form.status.draft', { defaultValue: 'Borrador' }));
  const statusBadgeVariant = statusBadgeVariantProp ?? (isEdit ? 'success' : 'primary');
  const statusValue = statusValueProp ?? (isEdit ? 'Activa' : undefined);

  const [isNarrow, setIsNarrow] = useState(
    () => (typeof window !== 'undefined' ? window.innerWidth <= breakpointNarrowPx : false)
  );
  const [statusDropdownOpenInternal, setStatusDropdownOpenInternal] = useState(false);
  const statusDropdownRef = useRef(null);

  const isStatusDropdownControlled = statusDropdownOpenProp !== undefined;
  const statusDropdownOpen = isStatusDropdownControlled ? statusDropdownOpenProp : statusDropdownOpenInternal;

  const setStatusDropdownOpen = (open) => {
    if (!isStatusDropdownControlled) setStatusDropdownOpenInternal(open);
    onStatusDropdownOpenChange?.(open);
  };

  useEffect(() => {
    if (!statusDropdownOpen) return;
    const handleClickOutside = (e) => {
      if (statusDropdownRef.current && !statusDropdownRef.current.contains(e.target)) {
        setStatusDropdownOpen(false);
      }
    };
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, [statusDropdownOpen, isStatusDropdownControlled]);

  const updateBreakpoint = () => setIsNarrow(window.innerWidth <= breakpointNarrowPx);
  useLayoutEffect(() => updateBreakpoint(), [breakpointNarrowPx]);
  useEffect(() => {
    window.addEventListener('resize', updateBreakpoint);
    return () => window.removeEventListener('resize', updateBreakpoint);
  }, [breakpointNarrowPx]);

  const handleSubmit = (e) => {
    e?.preventDefault?.();
    if (submitButtonDisabled || !onSubmit) return;
    const variantKey = isEdit ? 'E' : 'C';
    const payload = {
      nombreFantasia: nombreFantasiaValue,
      tipoIdentificacion: tipoIdentificacionValue,
      idTributario: idTributarioValue,
      razonSocial: razonSocialValue,
      pais: paisValue,
      status: statusValue,
    };
    onSubmit(e, { variant: variantKey, payload });
  };

  const contentGap = 'clamp(16px, 3vw, 24px)';
  const paddingH = isNarrow ? '16px' : '24px';

  return (
    <CardGrande
      className={`anima-empresa__container ${containerClassName} ${className}`}
      style={{
        ...(containerStyle || {}),
      }}
      {...props}
    >
      <style>{`
        .anima-empresa__status-badge-btn:hover,
        .anima-empresa__status-badge-btn:focus,
        .anima-empresa__status-badge-btn:active {
          background: transparent !important;
          outline: none !important;
          -webkit-tap-highlight-color: transparent;
        }
      `}</style>
      {/* Header: título + Badge estado */}
      <div
        className={`anima-empresa__title-container ${titleContainerClassName}`}
        style={{
          width: '100%',
          padding: `24px ${paddingH} 4px`,
          boxSizing: 'border-box',
          display: 'flex',
          flexDirection: 'row',
          alignItems: 'center',
          justifyContent: 'space-between',
          gap: '12px',
          flexWrap: 'wrap',
          ...(titleContainerStyle || {}),
        }}
      >
        {loading ? (
          <Skeleton variant="rectangular" height={24} width="40%" />
        ) : title ? (
          <Typography
            variant="body-md"
            className={titleClassName}
            style={{
              fontFamily: FONT_FAMILY_SANS,
              fontWeight: 500,
              fontSize: '16px',
              lineHeight: '30px',
              letterSpacing: '0%',
              textTransform: 'uppercase',
              color: 'var(--color-cyan-19)',
              margin: 0,
              ...(titleStyle || {}),
            }}
          >
            {title}
          </Typography>
        ) : null}
        {!loading && showStatusBadge && statusBadgeText && (
          <div ref={statusDropdownRef} style={{ position: 'relative', display: 'inline-block' }}>
            <button
              type="button"
              className="anima-empresa__status-badge-btn"
              onClick={() => setStatusDropdownOpen(!statusDropdownOpen)}
              style={{
                border: 'none',
                background: 'none',
                padding: 0,
                cursor: 'pointer',
                display: 'inline-block',
              }}
              aria-expanded={statusDropdownOpen}
              aria-haspopup="listbox"
              aria-label={t('empresa.form.status.aria', {
                defaultValue: `Estado: ${statusBadgeText}. Clic para cambiar`,
                status: statusBadgeText,
              })}
            >
              <Badge
                variant={statusBadgeVariant}
                size="medium"
                endIcon={
                  statusBadgeEndIcon ?? (
                    <Icon
                      name="ChevronDownIcon"
                      variant="20-solid"
                      size={16}
                      style={{ color: CHEVRON_COLOR_BY_BADGE_VARIANT[statusBadgeVariant] ?? CHEVRON_COLOR_BY_BADGE_VARIANT.primary }}
                    />
                  )
                }
              >
                {statusBadgeText}
              </Badge>
            </button>
            {statusDropdownOpen && statusOptions.length > 0 && (
              <div
                style={{
                  position: 'absolute',
                  top: '100%',
                  right: 0,
                  marginTop: '4px',
                  zIndex: 1000,
                  boxShadow: '0 4px 12px rgba(0,0,0,0.15)',
                  borderRadius: '12px',
                }}
              >
                <Options
                  items={statusOptions}
                  value={statusValue}
                  onChange={(value) => {
                    onStatusChange?.(value);
                    setStatusDropdownOpen(false);
                  }}
                  name="empresa-status"
                />
              </div>
            )}
          </div>
        )}

      </div>

      {/* Contenido: 2 columnas (en narrow 1 columna) */}
      <div
        className={`anima-empresa__content ${contentContainerClassName}`}
        style={{
          width: '100%',
          flex: 1,
          minWidth: 0,
          padding: `16px ${paddingH} 24px`,
          boxSizing: 'border-box',
          display: 'flex',
          flexDirection: 'column',
          gap: contentGap,
          ...(contentContainerStyle || {}),
        }}
      >
        {loading ? (
          <>
            <div style={{ display: 'grid', gridTemplateColumns: isNarrow ? '1fr' : '1fr 1fr', gap: contentGap }}>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                <Skeleton variant="rectangular" height={21} width={140} />
                <Skeleton variant="rectangular" height={42} width="100%" />
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                <Skeleton variant="rectangular" height={21} width={160} />
                <Skeleton variant="rectangular" height={42} width="100%" />
              </div>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              <Skeleton variant="rectangular" height={21} width={100} />
              <Skeleton variant="rectangular" height={42} width="100%" />
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              <Skeleton variant="rectangular" height={21} width={80} />
              <Skeleton variant="rectangular" height={42} width="100%" />
            </div>
            <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 12, marginTop: 8 }}>
              <Skeleton variant="rectangular" height={48} width={120} style={{ borderRadius: 8 }} />
              <Skeleton variant="rectangular" height={48} width={91} style={{ borderRadius: 8 }} />
            </div>
          </>
        ) : (
          <form
            onSubmit={handleSubmit}
            style={{
              display: 'flex',
              flexDirection: 'column',
              gap: contentGap,
              width: '100%',
              minWidth: 0,
            }}
          >
            <div
              style={{
                display: 'grid',
                gridTemplateColumns: isNarrow ? '1fr' : 'minmax(0, 1fr) minmax(0, 1fr)',
                gap: contentGap,
                alignItems: 'stretch',
                width: '100%',
                minWidth: 0,
              }}
            >
              <div
                style={{
                  display: 'flex',
                  flexDirection: 'column',
                  gap: contentGap,
                  minWidth: 0,
                  overflow: 'hidden',
                }}
              >
                <PrimaryInput
                  label={nombreFantasiaLabel ?? t('empresa.form.tradeName.label', { defaultValue: 'Nombre de fantasía' })}
                  value={nombreFantasiaValue}
                  onChange={nombreFantasiaOnChange}
                  placeholder={nombreFantasiaPlaceholder ?? t('empresa.form.tradeName.placeholder', { defaultValue: 'Ej. Nucleus S.A.' })}
                  error={nombreFantasiaError}
                  required={nombreFantasiaRequired}
                  showRequiredIndicator={false}
                />
                <div
                  style={
                    !isNarrow
                      ? {
                          marginTop: '62px',
                          flex: logoError ? '0 0 auto' : '1 1 0',
                          minWidth: 0,
                          width: '100%',
                          alignSelf: logoError ? 'flex-start' : 'stretch',
                          overflow: logoError ? 'visible' : 'hidden',
                          display: 'flex',
                          flexDirection: 'column',
                        }
                      : undefined
                  }
                >
                  <IdentidadVisual
                    isNarrow={isNarrow}
                    marcaActualTitle={marcaActualTitle ?? t('empresa.form.brandCurrent.title', { defaultValue: 'Marca actual' })}
                    marcaActualImage={marcaActualImage}
                    marcaActualImageAlt={marcaActualImageAlt}
                    marcaActualNucleusText={marcaActualNucleusText}
                    formatoText={formatoText}
                    uploadButtonText={uploadButtonText ?? t('empresa.form.uploadImage', { defaultValue: 'Subir imagen' })}
                    uploadButtonOnClick={uploadButtonOnClick}
                    containerStyle={
                      !isNarrow
                        ? {
                            minWidth: 0,
                            maxWidth: '100%',
                            ...(logoError ? { minHeight: 0, paddingBottom: 0 } : { flex: 1 }),
                          }
                        : undefined
                    }
                  />
                  {logoError && (
                    <div
                      className="anima-empresa__logoErrorBox"
                      style={{
                        marginTop: 12,
                        padding: '12px 16px',
                        gap: 4,
                        borderRadius: 8,
                        border: '1px solid #B30808',
                        backgroundColor: '#F8DBDB',
                        display: 'flex',
                        flexDirection: 'column',
                      }}
                    >
                      <Typography
                        component="span"
                        style={{
                          fontFamily: FONT_FAMILY_MONO,
                          fontWeight: 400,
                          fontStyle: 'normal',
                          fontSize: 14,
                          lineHeight: '21px',
                          letterSpacing: '0.02em',
                          color: '#B30808',
                          margin: 0,
                        }}
                      >
                        {typeof logoError === 'string' && logoError
                          ? logoError
                          : t('empresa.form.logoError.title', { defaultValue: DEFAULT_LOGO_ERROR_TITLE })}
                      </Typography>
                      {logoErrorSubtitle ? (
                        <Typography
                          component="span"
                          style={{
                            fontFamily: FONT_FAMILY_MONO,
                            fontWeight: 400,
                            fontStyle: 'normal',
                            fontSize: 14,
                            lineHeight: '21px',
                            letterSpacing: '0.02em',
                            color: '#B30808',
                            margin: 0,
                          }}
                        >
                          {logoErrorSubtitle ?? t('empresa.form.logoError.subtitle', { defaultValue: DEFAULT_LOGO_ERROR_SUBTITLE })}
                        </Typography>
                      ) : null}
                    </div>
                  )}
                </div>
              </div>

              <div style={{ display: 'flex', flexDirection: 'column', gap: contentGap, minWidth: 0 }}>
                <PrimarySelect
                  label={paisLabel ?? t('empresa.form.country.label', { defaultValue: 'País' })}
                  options={paisOptions}
                  value={paisValue}
                  onChange={paisOnChange}
                  placeholder={paisPlaceholder}
                  error={paisError}
                  required={paisRequired}
                  showRequiredIndicator={paisRequired}
                  disabled={paisDisabled}
                />
                <PrimarySelect
                  label={tipoIdentificacionLabel ?? t('empresa.form.identificationType.label', { defaultValue: 'Tipo de identificación' })}
                  options={tipoIdentificacionOptions}
                  value={tipoIdentificacionValue}
                  onChange={tipoIdentificacionOnChange}
                  placeholder={tipoIdentificacionPlaceholder}
                  error={tipoIdentificacionError}
                  disabled={tipoIdentificacionDisabled}
                />
                <PrimaryInput
                  label={idTributarioLabel ?? t('empresa.form.taxId.label', { defaultValue: 'ID tributario' })}
                  value={idTributarioValue}
                  onChange={idTributarioOnChange}
                  placeholder={idTributarioPlaceholder ?? t('empresa.form.taxId.placeholder', { defaultValue: 'Identificación tributaria de su país' })}
                  error={idTributarioError}
                  disabled={idTributarioDisabled}
                  required={idTributarioRequired}
                  showRequiredIndicator={idTributarioRequired}
                />
                <PrimaryInput
                  label={razonSocialLabel ?? t('empresa.form.legalName.label', { defaultValue: 'Razón social' })}
                  value={razonSocialValue}
                  onChange={razonSocialOnChange}
                  placeholder={razonSocialPlaceholder ?? t('empresa.form.legalName.placeholder', { defaultValue: 'Ej. Nucleus Corporate Group' })}
                  error={razonSocialError}
                  required={razonSocialRequired}
                  showRequiredIndicator={razonSocialRequired}
                />
              </div>
            </div>

            <div
              style={{
                display: 'flex',
                gap: '12px',
                justifyContent: 'flex-end',
                alignItems: 'center',
                marginTop: '8px',
                flexWrap: 'wrap',
              }}
            >
              <div style={{ display: 'flex', gap: '12px', alignItems: 'center', flexWrap: 'wrap' }}>
                {onDiscard && (
                  <PrimaryActionButton
                    type="button"
                    variant="outline"
                    text={discardButtonText ?? t('empresa.form.discard', { defaultValue: 'Descartar' })}
                    onClick={onDiscard}
                    fullWidth={false}
                    style={{ marginLeft: 0 }}
                  />
                )}
                <PrimaryActionButton
                  type="submit"
                  text={submitButtonText ?? t('empresa.form.save', { defaultValue: 'Guardar' })}
                  disabled={submitButtonDisabled}
                  fullWidth={false}
                  style={{ marginLeft: 0 }}
                />
              </div>
            </div>
          </form>
        )}
      </div>
    </CardGrande>
  );
};

export default Empresa;
