import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { PATHS } from '@/shared/constants/paths';
import { useNavigate } from '@/shared/lib/hooks/use-navigate';
import { HeaderType } from '@/entities/common/model/types';
import {
	useSetHeaderTitle,
	useSetHeaderType,
	useSetFooterMode,
  useSetOnBack
} from '@/widgets/sub-layout/use-sub-layout';
import { useUserChangeCancelPasswordMutation } from '@/entities/user/api/use-user-change-cancel-password-mutation';
import { useStore } from '@/shared/model/store';
import { snackBar } from '@/shared/lib/toast';

export const PasswordModifyCancelPasswordPage = () => {
  const { t } = useTranslation();
  const { navigate } = useNavigate();
  const midOptionsWithoutGids = useStore.getState().UserStore.selectOptionsMidsWithoutGids;
  const userMid = useStore.getState().UserStore.mid;
  let midItem = midOptionsWithoutGids.filter((value, index) => {
    return value.value === userMid;
  });

  const [mid, setMid] = useState<string>((midItem.length > 0)? userMid: '');
  const [password, setPassword] = useState<string>('');
  const [confirmPassword, setConfirmPassword] = useState<string>('');

  const changeCancelPasswordMutation = useUserChangeCancelPasswordMutation({
    onSuccess: () => {
      snackBar(t('account.passwordChangedSuccessfully'));
      // Clear form
      setPassword('');
      setConfirmPassword('');
      // Navigate back
      navigate(PATHS.account.password.manage);
    },
    onError: (error) => {
      snackBar(error?.response?.data?.message || t('account.passwordChangeFailed'));
    }
  });

  useSetHeaderTitle(t('account.changeCancelPassword'));
  useSetHeaderType(HeaderType.LeftArrow);
  useSetFooterMode(false);
  useSetOnBack(() => {
    navigate(PATHS.account.password.manage);
  });

  // 저장 버튼 활성화 조건 체크
  const isFormValid = () => {
    return (
      password.length >= 8 &&
      confirmPassword.length >= 8 &&
      password === confirmPassword
    );
  };

  // 저장 버튼 클릭 핸들러
  const handleSave = () => {
    if (!isFormValid()) return;

    changeCancelPasswordMutation.mutate({
      mid,
      password: password
    });
  };

  return (
    <>
      <main>
        <div className="tab-content">
          <div className="tab-pane sub active">
            <div className="ing-list add">
              <div className="user-add">
                <div className="ua-row">
                  <div className="ua-label">{t('account.merchant')} <span className="red">*</span></div>
                  <select
                    className="wid-100"
                    value={mid}
                    onChange={(e) => setMid(e.target.value)}
                  >
                  {
                    midOptionsWithoutGids.map((value) => (
                      <option
                        key={value.value}
                        value={value.value}
                      >{value.name}</option>
                    ))
                  }
                  </select>
                </div>
                <div className="ua-row">
                  <div className="ua-label">{t('account.newPassword')} <span className="red">*</span></div>
                  <input
                    className={`wid-100 ${confirmPassword && password !== confirmPassword ? 'error' : ''}`}
                    type="password"
                    placeholder={t('account.enterPassword')}
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                  />
                </div>
                <div className="ua-row">
                  <div className="ua-label">{t('account.reEnterNewPassword')} <span className="red">*</span></div>
                  <input
                    className={`wid-100 ${confirmPassword && password !== confirmPassword ? 'error' : ''}`}
                    type="password"
                    placeholder={t('account.reEnterPassword')}
                    value={confirmPassword}
                    onChange={(e) => setConfirmPassword(e.target.value)}
                  />
                </div>
                {confirmPassword && password !== confirmPassword && (
                  <div className="ua-help error">{t('account.inputMismatch')}</div>
                )}
              </div>

              <div className="apply-row">
                <button
                  className="btn-50 btn-blue flex-1"
                  type="button"
                  disabled={!isFormValid() || changeCancelPasswordMutation.isPending}
                  onClick={handleSave}
                >{changeCancelPasswordMutation.isPending ? t('account.processing') : t('common.save')}</button>
              </div>
            </div>
          </div>
        </div>
      </main>
    </>
  );
};