import { useState, useEffect, useMemo } from 'react';
import styled from '@emotion/styled';
import { createPortal } from 'react-dom';
import { ModalBackdrop } from '../../../../components/Stages/Modal.styles';
import Modal from '../../../../components/common/Modal/Modal';
import {
  Stack,
  Typography,
  TextField,
  Box,
  IconButton,
  InputAdornment,
} from '@mui/material';
import EditOutlinedIcon from '@mui/icons-material/EditOutlined';
import {
  ROLES_ID_RUSSIAN_NAME_ARRAY as ROLES,
  ROLES_ID_RUSSIAN_NAME,
} from '../../../../constants/constants';
import SelectWithOptions from '../../components/SelectWithOptions';
import useAbbreviation from './hooks/useAbbreviation';
import {
  PrimaryButton,
  SecondaryButton,
} from '../../../../components/common/Buttons/Buttons';

const FullScreenBackdrop = styled(ModalBackdrop)`
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100vw;
  height: 100vh;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 100;
`;

const FormStack = styled(Stack)`
  margin-top: 0.5rem;
  gap: 1rem;
`;

const StyledTextField = styled(TextField)`
  width: 28.25rem;

  & .MuiOutlinedInput-root {
    height: 2.56rem;
    border-radius: 0.5rem;

    & fieldset {
      border: 1px solid rgba(0, 0, 0, 0.1);
      transition: border-color 0.2s;
    }

    &:hover fieldset {
      border-color: rgba(0, 0, 0, 0.2);
    }

    &.Mui-focused fieldset {
      border-color: #1976d2;
      border-width: 1px;
    }
  }

  & .MuiOutlinedInput-input {
    padding: 0.25rem 0.75rem;
    height: 2.56rem;
    box-sizing: border-box;
  }
`;

const ReadOnlyField = styled(Box)`
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 28.25rem;
  height: 2.56rem;
  padding: 0.25rem 0.75rem;
  border: 1px solid rgba(0, 0, 0, 0.1);
  border-radius: 0.5rem;
  background-color: #f5f5f5;
  box-sizing: border-box;
  background-color: initial;
`;

const FieldLabel = styled(Typography)`
  color: rgba(0, 0, 0, 0.6);
  font-size: 0.75rem;
  margin-bottom: 0.25rem;
`;

const FieldValue = styled(Typography, {
  shouldForwardProp: (prop) => prop !== 'isEditing',
})`
  font-size: 0.875rem;
  color: ${(props) => (props.isEditing ? 'inherit' : 'rgba(0, 0, 0, 0.6)')};
  line-height: 1.5;
`;

export const EditUserModal = ({
  isOpen,
  onClose,
  onConfirm,
  user,
  onEditSsp,
}) => {
  const { createAbbreviation, shouldAbbreviate } = useAbbreviation();
  const [editUser, setEditUser] = useState(user);

  const [editingFields, setEditingFields] = useState({
    full_name: false,
    username: false,
    email: false,
    role_id: false,
    ssp: false,
  });

  useEffect(() => {
    setEditingFields({
      full_name: false,
      username: false,
      email: false,
      role_id: false,
      ssp: false,
    });
  }, [isOpen]);

  useEffect(() => {
    if (user) {
      setEditUser(user);
    }
  }, [user]);

  const handleBackdropClick = (e) => {
    if (e.target === e.currentTarget) {
      onClose();
    }
  };

  const handleCancel = () => {
    onClose();
  };

  const handleChange = (field) => (event) => {
    setEditUser((prev) => ({
      ...prev,
      [field]: event.target.value,
    }));
  };

  const handleRoleChange = (roleId) => {
    setEditUser((prev) => ({ ...prev, role_id: roleId }));
  };

  const toggleEdit = (field) => {
    setEditingFields((prev) => ({
      ...prev,
      [field]: !prev[field],
    }));
  };

  const handleSubmit = () => {
    if (onConfirm && user) {
      onConfirm({
        ...user,
        ...editUser,
      });
    }
    onClose();
  };

  const renderField = (label, field, value, type = 'text') => {
    const isEditing = editingFields[field];

    if (isEditing) {
      return (
        <Box>
          <FieldLabel>{label}</FieldLabel>
          <StyledTextField
            type={type}
            value={value}
            onChange={handleChange(field)}
            variant="outlined"
            size="small"
            autoFocus
            InputProps={{
              endAdornment: (
                <InputAdornment position="end">
                  <IconButton
                    edge="end"
                    onClick={() => toggleEdit(field)}
                    size="small"
                    sx={{ padding: '4px' }}
                  >
                    <EditOutlinedIcon fontSize="small" />
                  </IconButton>
                </InputAdornment>
              ),
            }}
          />
        </Box>
      );
    }

    return (
      <Box>
        <FieldLabel>{label}</FieldLabel>
        <ReadOnlyField>
          <FieldValue isEditing={false}>{value || '—'}</FieldValue>
          <IconButton
            onClick={() => toggleEdit(field)}
            size="small"
            sx={{ padding: '4px' }}
          >
            <EditOutlinedIcon fontSize="small" />
          </IconButton>
        </ReadOnlyField>
      </Box>
    );
  };

  const renderRoleField = () => {
    const isEditing = editingFields.role_id;
    const selectedRoleId = editUser.role_id;

    if (isEditing) {
      return (
        <Box>
          <FieldLabel>Роль</FieldLabel>
          <Box sx={{ display: 'flex', alignItems: 'center' }}>
            <SelectWithOptions
              style={{ height: '2.56rem' }}
              value={selectedRoleId}
              options={ROLES}
              width="12.63rem"
              placeholder="Роль"
              onChange={(selectedId) => {
                handleRoleChange(selectedId);
              }}
            ></SelectWithOptions>
          </Box>
        </Box>
      );
    }

    return (
      <Box>
        <FieldLabel>Роль</FieldLabel>
        <ReadOnlyField style={{ width: '12.63rem' }}>
          <FieldValue isEditing={false}>
            {ROLES_ID_RUSSIAN_NAME[selectedRoleId]}
          </FieldValue>
          <IconButton
            onClick={() => toggleEdit('role_id')}
            size="small"
            sx={{ padding: '.25rem' }}
          >
            <EditOutlinedIcon fontSize="small" />
          </IconButton>
        </ReadOnlyField>
      </Box>
    );
  };

  const renderSspField = () => {
    const isEditing = editingFields.ssp;

    if (isEditing) {
      Promise.resolve().then(() => {
        onClose();
        onEditSsp?.(editUser);
      });
    }
    const selectedSsps = (editUser.org_units ?? []).map((s) => s.title);
    return (
      <Box>
        <FieldLabel>Подразделение</FieldLabel>
        <ReadOnlyField
          style={{
            width: '55.13rem',
            padding: '0.25rem 0.75rem',
            minHeight: '2rem',
            height: 'max-content',
          }}
        >
          <Box
            sx={{
              borderRadius: '0.5rem',
              width: 'max-content',
              maxWidth: '100%',
              display: 'flex',
              flexDirection: 'row',
              gap: '.25rem',
              boxSizing: 'border-box',
              flexWrap: 'wrap',
              height: 'max-content',
            }}
          >
            {selectedSsps.length > 0 ? (
              selectedSsps.map((ssp, index) => {
                const needsAbbreviation = shouldAbbreviate(ssp);
                const displayText = needsAbbreviation
                  ? createAbbreviation(ssp)
                  : ssp;
                return (
                  <Box
                    key={index}
                    sx={{
                      boxSizing: 'border-box',
                      border: '1px solid #d1d5dc',
                      borderRadius: '0.38rem',
                      padding: '0.1rem 0.5rem',
                      backgroundColor: '#f3f4f6',
                      color: '#364153',
                      position: 'relative',
                      fontSize: '.7rem',
                      height: '1.38rem',
                      // width: 'max-content',
                      cursor: needsAbbreviation ? 'help' : 'default',
                      '&:hover': {
                        backgroundColor: needsAbbreviation
                          ? '#e5e7eb'
                          : '#f3f4f6',
                      },
                    }}
                    title={displayText}
                  >
                    {displayText}
                  </Box>
                );
              })
            ) : (
              <FieldValue isEditing={false}>—</FieldValue>
            )}
          </Box>
          <IconButton
            onClick={() => toggleEdit('ssp')}
            size="small"
            sx={{ padding: '4px' }}
          >
            <EditOutlinedIcon fontSize="small" />
          </IconButton>
        </ReadOnlyField>
      </Box>
    );
  };

  if (!isOpen) return null;

  return createPortal(
    <FullScreenBackdrop isOpen={isOpen} onClick={handleBackdropClick}>
      <Modal
        open={isOpen}
        title={'Информация о пользователе'}
        onClose={onClose}
        customSize={58.13}
      >
        <FormStack>
          <Box sx={{ display: 'flex', gap: '1.5rem', flexDirection: 'column' }} >
            <Box sx={{ display: 'flex', gap: '.5rem', flexDirection: 'column' }} >
              {renderField('ФИО', 'full_name', editUser.full_name)}
              {renderField('Почта', 'email', editUser.email, 'email')}
            </Box>

            {renderRoleField()}
            {renderSspField()}
          </Box>
        </FormStack>

        <Box
          sx={{
            display: 'flex',
            gap: '1rem',
            justifyContent: 'end',
            paddingTop: '1.5rem',
          }}
        >
          <SecondaryButton onClick={handleCancel} width={'5.88rem'}>
            Отмена
          </SecondaryButton>
          <PrimaryButton onClick={handleSubmit} width={'5.88rem'}>
            Сохранить
          </PrimaryButton>
        </Box>
      </Modal>
    </FullScreenBackdrop>,
    document.body,
  );
};
