import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { PasswordInput } from '../../Inputs/PasswordInput/PasswordInput';
import { Typography } from '../../Atoms/Typography/Typography';
import { Button } from '../../Atoms/Button/Button';
import { Alert } from '../../Atoms/Alert/Alert';

const CANCEL_BUTTON_MIN_WIDTH_PX = 1024;
const THEME_COLOR = '#29474C';

function useMediaQuery(query) {
  const [matches, setMatches] = useState(() =>
    typeof window !== 'undefined' ? window.matchMedia(query).matches : false
  );

  useEffect(() => {
    if (typeof window === 'undefined') return;
    const mql = window.matchMedia(query);
    const handle = () => setMatches(mql.matches);
    handle();
    mql.addEventListener('change', handle);
    return () => mql.removeEventListener('change', handle);
  }, [query]);

  return matches;
}

export const ChangePasswordConfig = ({
  onSubmit,
  className = '',
  ...props
}) => {
  const { t } = useTranslation();
  const showCancelButton = useMediaQuery(`(min-width: ${CANCEL_BUTTON_MIN_WIDTH_PX}px)`);
  const [formData, setFormData] = useState({
    currentPassword: '',
    newPassword: '',
    confirmPassword: '',
  });
  const [errors, setErrors] = useState({});
  const [success, setSuccess] = useState(false);
  const [hasTriedSubmit, setHasTriedSubmit] = useState(false);
  const isSaveDisabled = !formData.currentPassword || !formData.newPassword || !formData.confirmPassword;

  const handleChange = (field, value) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
    if (errors[field]) {
      setErrors((prev) => ({ ...prev, [field]: null }));
    }
    setSuccess(false);
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    setHasTriedSubmit(true);
    const newErrors = {};

    if (!formData.currentPassword) {
      newErrors.currentPassword = t('validation.required', { field: t('form.currentPassword') });
    }
    if (!formData.newPassword) {
      newErrors.newPassword = t('validation.required', { field: t('form.newPassword') });
    } else if (formData.newPassword.length < 8) {
      newErrors.newPassword = t('validation.passwordMinLength', { min: 8 });
    }
    if (!formData.confirmPassword) {
      newErrors.confirmPassword = t('validation.confirmPasswordRequired');
    } else if (formData.newPassword !== formData.confirmPassword) {
      newErrors.confirmPassword = t('validation.passwordsDoNotMatch');
    }

    if (Object.keys(newErrors).length > 0) {
      setErrors(newErrors);
      return;
    }

    if (onSubmit) {
      onSubmit(formData);
    }
    setSuccess(true);
    setHasTriedSubmit(false);
    setFormData({
      currentPassword: '',
      newPassword: '',
      confirmPassword: '',
    });
  };

  return (
    <form
      onSubmit={handleSubmit}
      className={`anima-change-password-config w-full bg-white p-6 shadow-md ${className}`}
      style={{ width: '100%', boxSizing: 'border-box', borderRadius: '16px' }}
      {...props}
    >
      <style>{`
        .anima-change-password-config .anima-passwordfield input::placeholder {
          font-family: 'IBM Plex Sans', sans-serif;
          font-weight: 300;
          font-style: italic;
          font-size: 16px;
          line-height: 24px;
          letter-spacing: 0px;
          color: #474747;
          opacity: 1;
        }
      `}</style>

      {success && (
        <Alert variant="success" className="mb-4">
          {t('changePassword.success')}
        </Alert>
      )}

      <div className="space-y-4">
        <Typography
          variant="body-lg"
          component="div"
          style={{
            fontFamily: "'IBM Plex Sans', sans-serif",
            fontWeight: 400,
            fontStyle: 'normal',
            fontSize: '20px',
            lineHeight: '30px',
            letterSpacing: '0px',
            verticalAlign: 'middle',
            color: '#29474C',
          }}
        >
          {t('form.changePassword')}
        </Typography>

        <PasswordInput
          label={t('form.currentPassword')}
          placeholder={t('placeholder.currentPassword')}
          themeColor={THEME_COLOR}
          value={formData.currentPassword}
          onChange={(e) => handleChange('currentPassword', e.target.value)}
          error={errors.currentPassword}
          required
          hideRequiredAsterisk
        />

        <div
          aria-hidden="true"
          style={{
            width: '100%',
            height: '1px',
            backgroundColor: '#DDDDDD',
          }}
        />

        <PasswordInput
          label={t('form.newPassword')}
          placeholder={t('placeholder.password')}
          themeColor={THEME_COLOR}
          value={formData.newPassword}
          onChange={(e) => handleChange('newPassword', e.target.value)}
          error={errors.newPassword}
          required
          hideRequiredAsterisk
        />
        {hasTriedSubmit && errors.newPassword && formData.newPassword && formData.newPassword.length < 8 && (
          <p className="mt-1 text-sm text-gray-500">{t('changePassword.helper.minLength', { min: 8 })}</p>
        )}

        <PasswordInput
          label={t('changePassword.repeatPassword')}
          placeholder={t('placeholder.password')}
          themeColor={THEME_COLOR}
          value={formData.confirmPassword}
          onChange={(e) => handleChange('confirmPassword', e.target.value)}
          error={errors.confirmPassword}
          required
          hideRequiredAsterisk
        />
      </div>

      {showCancelButton ? (
        <div
          className="flex justify-end gap-4 mt-6"
          style={{ width: '100%', boxSizing: 'border-box' }}
        >
          <Button
            type="button"
            variant="Secondary"
            color="Teal"
            disabled={false}
            aria-label={t('common.cancel')}
            title={t('common.cancel')}
            className="flex items-center justify-center w-[82px] min-w-[82px] h-[37px] p-0"
          >
            {t('common.cancel')}
          </Button>
          <Button
            type="submit"
            variant="Primary"
            color="Teal"
            disabled={isSaveDisabled}
            aria-label={t('common.save')}
            title={t('common.save')}
            className="flex items-center justify-center w-[82px] min-w-[82px] h-[37px] p-0"
          >
            {t('common.save')}
          </Button>
        </div>
      ) : (
        <Button type="submit" variant="Primary" color="Teal" disabled={isSaveDisabled} className="w-full mt-6">
          {t('common.save')}
        </Button>
      )}
    </form>
  );
};

export default ChangePasswordConfig;

