import { useRef } from 'react';
import { PrimaryActionButton } from '../../Atoms/PrimaryActionButton/PrimaryActionButton';
import { PrimaryInput } from '../../Inputs/PrimaryInput/PrimaryInput';
import { PrimaryDropdownSelect } from '../../Inputs/PrimaryDropdownSelect/PrimaryDropdownSelect';
import { ModalShell } from '../ModalShell/ModalShell';
import { GreenScrollbar } from '../VistaDatos/GreenScrollbar';
import {
  MODAL_SHELL_FOOTER_BUTTON_BASE_STYLE,
  MODAL_SHELL_FOOTER_BUTTON_TEXT_STYLE,
} from '../ModalShell/modalShellStyles';
import {
  MODAL_ASIGNAR_PERSONA_DEFAULT_EMPRESA_OPTIONS,
  MODAL_ASIGNAR_PERSONA_DEFAULT_PERSONA_OPTIONS,
  MODAL_ASIGNAR_PERSONA_DEFAULT_UNIDAD_OPTIONS,
  MODAL_ASIGNAR_PERSONA_DEFAULT_VALUES,
} from './modalAsignarPersonaDefaults';
import {
  MODAL_ASIGNAR_PERSONA_HEIGHT_PX,
  MODAL_ASIGNAR_PERSONA_WIDTH_PX,
} from './modalAsignarPersonaStyles';

const FORM_SCROLLBAR_GUTTER_PX = 16;

export const ModalAsignarPersona = ({
  isOpen = false,
  onClose,
  title = 'Asignar persona a unidad',
  values = MODAL_ASIGNAR_PERSONA_DEFAULT_VALUES,
  onFieldChange,
  onSubmit,
  onCancel,
  empresaOptions = MODAL_ASIGNAR_PERSONA_DEFAULT_EMPRESA_OPTIONS,
  personaOptions = MODAL_ASIGNAR_PERSONA_DEFAULT_PERSONA_OPTIONS,
  unidadOptions = MODAL_ASIGNAR_PERSONA_DEFAULT_UNIDAD_OPTIONS,
  fieldLabels,
  fieldErrors,
  submitButtonLabel = 'Asignar persona',
  cancelButtonLabel = 'Cancelar',
  disableSubmit = false,
  footer,
  width = MODAL_ASIGNAR_PERSONA_WIDTH_PX,
  height = MODAL_ASIGNAR_PERSONA_HEIGHT_PX,
  closeOnOverlayClick = true,
  zIndex = 1500,
  className = '',
  panelStyle,
  ...props
}) => {
  const formScrollRef = useRef(null);
  const resolvedValues = { ...MODAL_ASIGNAR_PERSONA_DEFAULT_VALUES, ...(values || {}) };
  const labels = {
    empresaId: 'Empresa',
    personaId: 'Persona',
    unidadId: 'Unidad organizativa',
    rol: 'Rol / Puesto (opcional)',
    ...(fieldLabels || {}),
  };
  const errors = fieldErrors || {};

  const handleFieldChange = (field) => (event) => {
    const nextValue = event?.target?.value ?? '';
    onFieldChange?.(field, nextValue, event);
  };

  const handleCancel = () => {
    if (onCancel) onCancel();
    else onClose?.();
  };

  const defaultFooter = (
    <>
      <PrimaryActionButton
        variant="outline"
        text={cancelButtonLabel}
        onClick={handleCancel}
        textStyle={MODAL_SHELL_FOOTER_BUTTON_TEXT_STYLE}
        style={MODAL_SHELL_FOOTER_BUTTON_BASE_STYLE}
      />
      <PrimaryActionButton
        variant="primary"
        text={submitButtonLabel}
        disabled={disableSubmit}
        onClick={() => onSubmit?.(resolvedValues)}
        textStyle={MODAL_SHELL_FOOTER_BUTTON_TEXT_STYLE}
        style={MODAL_SHELL_FOOTER_BUTTON_BASE_STYLE}
      />
    </>
  );

  return (
    <ModalShell
      isOpen={isOpen}
      onClose={onClose}
      title={title}
      width={width}
      height={height}
      maxHeight="calc(100vh - 40px)"
      closeOnOverlayClick={closeOnOverlayClick}
      zIndex={zIndex}
      className={className}
      panelStyle={panelStyle}
      footer={footer ?? defaultFooter}
      bodyStyle={{ display: 'flex', flexDirection: 'column', minHeight: 0 }}
      {...props}
    >
      <div
        style={{
          position: 'relative',
          flex: '1 1 auto',
          minHeight: 0,
          display: 'flex',
          flexDirection: 'column',
          height: '100%',
        }}
      >
        <div
          ref={formScrollRef}
          style={{
            flex: '1 1 auto',
            minHeight: 0,
            overflowY: 'auto',
            overflowX: 'hidden',
            paddingRight: FORM_SCROLLBAR_GUTTER_PX,
            boxSizing: 'border-box',
            scrollbarWidth: 'none',
            msOverflowStyle: 'none',
          }}
        >
          <form
            style={{
              padding: 16,
              display: 'flex',
              flexDirection: 'column',
              gap: 16,
              boxSizing: 'border-box',
            }}
            onSubmit={(event) => {
              event.preventDefault();
              if (!disableSubmit) onSubmit?.(resolvedValues, event);
            }}
          >
            <PrimaryDropdownSelect
              id="modal-asignar-empresa"
              name="empresaId"
              label={labels.empresaId}
              options={empresaOptions}
              value={resolvedValues.empresaId ?? ''}
              onChange={handleFieldChange('empresaId')}
              required
              error={errors.empresaId}
            />

            <PrimaryDropdownSelect
              id="modal-asignar-persona"
              name="personaId"
              label={labels.personaId}
              options={personaOptions}
              value={resolvedValues.personaId ?? ''}
              onChange={handleFieldChange('personaId')}
              required
              error={errors.personaId}
            />

            <PrimaryDropdownSelect
              id="modal-asignar-unidad"
              name="unidadId"
              label={labels.unidadId}
              options={unidadOptions}
              value={resolvedValues.unidadId ?? ''}
              onChange={handleFieldChange('unidadId')}
              required
              error={errors.unidadId}
            />

            <PrimaryInput
              id="modal-asignar-rol"
              name="rol"
              label={labels.rol}
              placeholder="Ej: Analista, Developer…"
              value={resolvedValues.rol ?? ''}
              onChange={handleFieldChange('rol')}
              error={errors.rol}
            />
          </form>
        </div>
        <GreenScrollbar scrollRef={formScrollRef} insetRight={0} />
      </div>
    </ModalShell>
  );
};

export {
  MODAL_ASIGNAR_PERSONA_DEFAULT_VALUES,
  MODAL_ASIGNAR_PERSONA_DEFAULT_EMPRESA_OPTIONS,
  MODAL_ASIGNAR_PERSONA_DEFAULT_PERSONA_OPTIONS,
  MODAL_ASIGNAR_PERSONA_DEFAULT_UNIDAD_OPTIONS,
} from './modalAsignarPersonaDefaults';
export default ModalAsignarPersona;
